diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 0d4deca36f..9e2a63a9c1 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,12 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and -/// `VECTORCRAFT_CONFIG_DIR` apply as they do there. +/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there and starts new +/// documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they +/// do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 03a9b8848c..8622a19223 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -71,7 +71,7 @@ fn open_extensions(exts: &[impl AsRef], any_case: bool) -> Vec { /// `d` set up for `request`: its title, file types, folder and suggested name. fn dialog_for(d: D, request: &PickRequest) -> D { let pick = match request { - PickRequest::Open(pick) | PickRequest::Save(pick) => pick, + PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, PickRequest::OpenMany => { return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { d.filter( @@ -81,8 +81,9 @@ fn dialog_for(d: D, request: &PickRequest) -> D { }); } PickRequest::Folder => return d, + PickRequest::FolderAt(folder) => return d.folder(folder), }; - let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_)); + let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_)); let d = pick.filters.iter().fold(d, |d, (name, exts)| { d.filter( vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), @@ -96,6 +97,37 @@ fn dialog_for(d: D, request: &PickRequest) -> D { if pick.name.is_empty() { d } else { d.file_name(&pick.name) } } +#[cfg(test)] +#[test] +fn a_folder_picker_asked_for_a_folder_starts_there() { + /// The settings a dialog was given, by name. + #[derive(Default)] + struct Recorded(Vec); + impl DialogSettings for Recorded { + fn parent(self, _: &winit::window::Window) -> Self { + self + } + fn title(mut self, title: &str) -> Self { + self.0.push(format!("title {title}")); + self + } + fn filter(mut self, name: &str, _: &[impl ToString]) -> Self { + self.0.push(format!("filter {name}")); + self + } + fn folder(mut self, folder: &str) -> Self { + self.0.push(format!("folder {folder}")); + self + } + fn file_name(mut self, name: &str) -> Self { + self.0.push(format!("name {name}")); + self + } + } + assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]); + assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty()); +} + /// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the /// window and keeps it in front). #[cfg(not(target_os = "macos"))] @@ -128,9 +160,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) } let paths = match request { PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), - PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(), + PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(), PickRequest::Save(_) => dialog.save_file().into_iter().collect(), - PickRequest::Folder => dialog.pick_folder().into_iter().collect(), + PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(), }; paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() } @@ -313,7 +345,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti let picked = dialog.pick_file(); Box::pin(async move { picked.await.iter().map(path).collect() }) } - PickRequest::OpenMany => { + PickRequest::OpenMany | PickRequest::OpenFiles(_) => { let picked = dialog.pick_files(); Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) } @@ -332,7 +364,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti // on that nil; treat the pick as cancelled instead (#5980). Err(()) => Box::pin(async move { Vec::new() }), }, - PickRequest::Folder => { + PickRequest::Folder | PickRequest::FolderAt(_) => { let picked = dialog.pick_folder(); Box::pin(async move { picked.await.iter().map(path).collect() }) } @@ -353,7 +385,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { .and_then(|w| w.window_handle().ok()) .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); let (clip, clip_probe) = (parent.clone(), parent.clone()); - let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); + let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); #[cfg(any(target_os = "macos", target_os = "linux"))] let sampled_ui = ui.clone(); #[cfg(target_os = "linux")] @@ -361,6 +393,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { Services { pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())), pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))), + pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))), pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows // dialogs run the window's events while they are open. @@ -407,6 +440,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), + pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())), // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] screen_color: Some(mac_screen_color::sampler(sampled_ui)), diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c2b40e37e6..92088fd67b 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -479,6 +479,7 @@ fn main() -> std::process::ExitCode { // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); + prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 11afcfe121..80b42ef219 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -73,6 +73,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { } } +/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people +/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first +/// needs them. +pub fn attach_script_data(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Script Data") { + session.attach_script_data(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0fccbcdecb..264581e3ed 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -67,8 +67,9 @@ log = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["std", "process"] } -# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`). -# Already in Cargo.lock (walkdir), so this adds no new crate. +# 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 +# (walkdir), so this adds no new crate. [target.'cfg(windows)'.dependencies] same-file = "1.0.6" diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index f5edf1f91d..623ab8a87f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB, and writing, the file dialogs and execute return false or null with error set. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -90,6 +90,24 @@ pub fn specs() -> Vec { always, list_installed ), + cmd!( + query "script.grants", + "List Script File Permissions", + [], + None, + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}", + always, + grants + ), + cmd!( + query "script.grants.revoke", + "Revoke Script File Permissions", + [], + None, + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed; refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + always, + grants_revoke + ), cmd!( query "script.check", "Check Script", @@ -228,6 +246,18 @@ impl Session { self.scripts_dir = Some(dir); } + /// Keep each script's data folder (`Folder.userData`) in the folder `dir`, and the file access + /// people allow scripts with Always in [`script::files::GRANTS_FILE`] beside it. The folders are + /// made when a script first needs them. + pub fn attach_script_data(&mut self, dir: std::path::PathBuf) { + self.script_data_dir = Some(dir); + } + + /// The folder of the scripts' data folders ([`Session::attach_script_data`]); none on the web. + pub fn script_data_dir(&self) -> Option<&std::path::Path> { + self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + /// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders. pub fn scripts_dir(&self) -> Option<&std::path::Path> { self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) @@ -308,6 +338,40 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { Ok(json!({"folder": folder, "scripts": scripts, "truncated": listing.truncated, "unreadable": listing.unreadable})) } +fn grants(s: &mut Session, _: &Value) -> Result { + let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; + let file = dir.with_file_name(script::files::GRANTS_FILE); + Ok(json!({"grants": script::files::stored_grants(dir), "file": file.to_string_lossy()})) +} + +fn grants_revoke(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.grants.revoke"; + let path_of = |key: &str| match p.get(key) { + None => Ok(None), + Some(Value::String(t)) if !t.is_empty() => { + Ok(Some(std::fs::canonicalize(t).map_or_else(|_| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()))) + } + Some(_) => Err(bad(C, format!("`{key}` must be a path"))), + }; + let (script_path, path) = (path_of("script")?, path_of("path")?); + let all = match p.get("all") { + None => false, + Some(Value::Bool(true)) => true, + Some(_) => return Err(bad(C, "`all` must be true")), + }; + if all == (script_path.is_some() || path.is_some()) { + return Err(bad(C, "give `all`, or `script` and `path` or one of them")); + } + // A running script holds the grants it started with until it ends. + if s.script_running() { + return Err(EngineError::Busy); + } + let Some(dir) = s.script_data_dir() else { return Ok(json!({"removed": 0})) }; + let removed = script::files::revoke_grants(dir, script_path.as_deref(), path.as_deref()) + .map_err(|e| EngineError::Other(format!("the script file permissions could not be saved: {e}")))?; + Ok(json!({"removed": removed})) +} + /// The folder a script is in, which its included files are read from. struct Folder { dir: std::path::PathBuf, diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 6ca724d810..9aaeb58dab 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -25,7 +25,9 @@ //! guard against other programs on the computer. //! //! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`) -//! are read from, inside the roots. +//! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. +//! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the +//! files of the open documents. use std::cell::RefCell; use std::ffi::OsString; @@ -185,22 +187,87 @@ pub fn unconfined(f: impl FnOnce() -> T) -> T { with_scope(Some(Scope::Unconfined), f) } -/// This thread's scope, to carry to work it hands to another thread ([`ScopeHandle::run`]). +/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to +/// another thread ([`ScopeHandle::run`]). #[derive(Clone, Debug)] -pub struct ScopeHandle(Option); +pub struct ScopeHandle(Option, Option>); impl ScopeHandle { /// The scope of the calling thread. pub fn capture() -> Self { - Self(SCOPE.with(|s| s.borrow().clone())) + Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone())) } /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { - with_scope(self.0, f) + let Self(scope, gate) = self; + with_gate(gate, || with_scope(scope, f)) } } +/// What a command a running script runs (`vc.run`) may read and write: the places the script's +/// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app +/// were opened from or saved to. The automation roots apply as well. A path refused by its name +/// alone ([`ScriptScope::refused_by_name`]) is refused here too. +#[derive(Clone, Debug)] +pub(crate) struct ScriptGate { + pub(crate) read: ScriptScope, + pub(crate) write: ScriptScope, + /// The paths of the open documents' files, as the documents hold them. + pub(crate) documents: Vec, +} + +impl ScriptGate { + fn check(&self, path: &str, access: Access) -> Result<(), String> { + let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; + let allowed = real.is_some_and(|real| { + let scoped = match access { + Access::Read => self.read.allows(&real) || self.write.allows(&real), + Access::Write => self.write.allows(&real), + }; + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) + }); + if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } + } +} + +thread_local! { + /// The gate of the script command this thread runs ([`with_script_gate`]). + static GATE: RefCell>> = const { RefCell::new(None) }; +} + +/// Puts the gate it replaced back when dropped (also when `f` panics). +struct RestoreGate(Option>); + +impl Drop for RestoreGate { + fn drop(&mut self) { + let previous = self.0.take(); + GATE.with(|g| *g.borrow_mut() = previous); + } +} + +fn with_gate(gate: Option>, f: impl FnOnce() -> T) -> T { + let _restore = RestoreGate(GATE.with(|g| g.replace(gate))); + f() +} + +/// Runs `f`, a command a script runs, with `gate` in force on this thread: every path it reads or +/// writes must pass the gate as well as the automation roots. Reads of the app's own folders, +/// inside [`unconfined`], are not checked; writes there are, so a script's command does not save +/// into the app's libraries. +pub(crate) fn with_script_gate(gate: ScriptGate, f: impl FnOnce() -> T) -> T { + with_gate(Some(Arc::new(gate)), f) +} + +/// May `path` be read (or written) by the script command this thread runs? Always outside one, +/// and for a read inside [`unconfined`]. +fn check_gate(path: &str, access: Access) -> Result<(), String> { + if matches!(access, Access::Read) && SCOPE.with(|s| matches!(*s.borrow(), Some(Scope::Unconfined))) { + return Ok(()); + } + GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) +} + /// The roots in force on this thread, if any. pub fn current() -> Option> { match SCOPE.with(|s| s.borrow().clone()) { @@ -210,9 +277,11 @@ pub fn current() -> Option> { } } -/// May `path` be read here? Always, without roots in force. +/// May `path` be read here? Always, without roots in force and outside a script's command +/// ([`with_script_gate`]). pub fn check_read(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Read)) + current().map_or(Ok(()), |r| r.check(path, Access::Read))?; + check_gate(path, Access::Read) } /// Is `path`, under a read root, written as an absolute path of another platform: outside Windows, one @@ -229,9 +298,11 @@ pub fn is_path_key(key: &str) -> bool { matches!(key, "path" | "paths" | "file" | "files" | "folder") || ["Path", "Paths", "File", "Files", "Folder"].iter().any(|end| key.ends_with(end)) } -/// May `path` be written here? Always, without roots in force. +/// May `path` be written here? Always, without roots in force and outside a script's command +/// ([`with_script_gate`]). pub fn check_write(path: &str) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + check_gate(path, Access::Write)?; WRITES.with(|w| { if let Some(paths) = w.borrow_mut().as_mut() && !paths.iter().any(|(p, _)| p == path) @@ -323,6 +394,12 @@ fn inside(path: &Path, root: &Path) -> bool { root.components().all(|r| path.next().is_some_and(|p| same_component(p, r))) } +/// Is `path` `root` or inside it, both with their links followed, compared as [`AutomationRoots`] +/// compares them? +pub(crate) fn path_inside(path: &Path, root: &Path) -> bool { + inside(path, root) +} + fn same_component(a: Component, b: Component) -> bool { if a == b { return true; @@ -374,10 +451,21 @@ fn windows_name_refusal(path: &str) -> Option<&'static str> { /// The file opened is the path with its links followed, and after reading, the path is followed /// again and must still lead to the same place: a process that changes the folders twice in between /// can still win that race. +/// +/// A scope can also be given more folders ([`ScriptScope::add`]) and single files +/// ([`ScriptScope::add_file`]), and folders it keeps out even inside a granted folder +/// ([`ScriptScope::fence`]), each but the places inside it that stay open. A granted file grants its +/// own path only, also when a folder later takes its place. #[derive(Clone, Debug, Default)] pub(crate) struct ScriptScope { /// The granted folders, made absolute with their links followed. roots: Vec, + /// The granted files, made absolute with their links followed. + files: Vec, + /// The folders kept out, with their links followed. + fenced: Vec, + /// The places inside a fenced folder that are not kept out. + open: Vec, } /// Why a script's file was not read. @@ -396,12 +484,62 @@ pub(crate) enum ScriptRead { impl ScriptScope { /// The scope of a script run from a file in folder `dir`: that folder. pub(crate) fn of_folder(dir: &Path) -> Self { - Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() } + Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect(), ..Self::default() } + } + + /// Grants the folder `real`, a path with its links followed, with everything inside it. + pub(crate) fn add(&mut self, real: PathBuf) { + if !self.roots.contains(&real) { + self.roots.push(real); + } + } + + /// Grants the file `real`, a path with its links followed: that path and nothing below it. + pub(crate) fn add_file(&mut self, real: PathBuf) { + if !self.files.contains(&real) { + self.files.push(real); + } + } + + /// Takes back the grant of the folder (`folder`) or file `real` that [`ScriptScope::add`] or + /// [`ScriptScope::add_file`] gave. + pub(crate) fn remove(&mut self, real: &Path, folder: bool) { + if folder { self.roots.retain(|r| r != real) } else { self.files.retain(|r| r != real) } + } + + /// Is nothing granted? + fn is_empty(&self) -> bool { + self.roots.is_empty() && self.files.is_empty() + } + + /// Keeps the folder `real` (links followed) and everything in it out, but for `open` and the + /// places inside it. + pub(crate) fn fence(&mut self, real: PathBuf, open: &[PathBuf]) { + self.fenced.push(real); + self.open.extend(open.iter().cloned()); + } + + /// Leaves the place `real` (links followed) and everything in it open inside a fenced folder. + pub(crate) fn fence_open(&mut self, real: PathBuf) { + self.open.push(real); + } + + /// The granted folders, with their links followed. + pub(crate) fn roots(&self) -> &[PathBuf] { + &self.roots + } + + /// Is the real path `real` a granted file or inside a granted folder, and not kept out? A place + /// left open counts only inside the fenced folder: one that holds the fenced folder opens none of it. + pub(crate) fn allows(&self, real: &Path) -> bool { + (self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count()) + || self.roots.iter().any(|r| inside(real, r))) + && !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) } /// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or /// stream, or a computer on the network? - fn refused_by_name(path: &Path) -> bool { + pub(crate) fn refused_by_name(path: &Path) -> bool { let text = path.to_string_lossy(); text.contains('\0') || path.components().any(|c| c == Component::ParentDir) @@ -411,7 +549,7 @@ impl ScriptScope { /// The real path of the file at `path` and its first `max` bytes, at most. pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec), ScriptRead> { use std::io::Read; - if self.roots.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { + if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { return Err(ScriptRead::Refused); } let real = match std::fs::canonicalize(path) { @@ -422,7 +560,7 @@ impl ScriptScope { } Err(e) => return Err(ScriptRead::Failed(e.to_string())), }; - if !self.roots.iter().any(|r| inside(&real, r)) { + if !self.allows(&real) { return Err(ScriptRead::Refused); } let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; @@ -450,24 +588,24 @@ impl ScriptScope { self.roots.first().map(|r| crate::cmd::findfiles::plain(r.clone())) } - /// Does the absolute path `path` name a granted folder or a place inside one, by its names - /// alone, without regard to case? A path that does not is refused before the file system is - /// asked anything about it. + /// Does the absolute path `path` name a granted file, a granted folder or a place inside one, + /// by its names alone, without regard to case? A path that does not is refused before the file + /// system is asked anything about it. fn names_inside(&self, path: &Path) -> bool { let lower = |c: Component| c.as_os_str().to_string_lossy().to_lowercase(); - path.is_absolute() - && self.roots.iter().any(|r| { - let root = crate::cmd::findfiles::plain(r.clone()); - let mut names = path.components(); - root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c))) - }) + let names_under = |r: &PathBuf| { + let root = crate::cmd::findfiles::plain(r.clone()); + let mut names = path.components(); + root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c))) + }; + path.is_absolute() && (self.roots.iter().any(names_under) || self.files.iter().any(names_under)) } /// The real path of the file or folder at `path`, which must be absolute: refused as /// [`ScriptScope::read`] refuses a path, and also when its names alone place it outside every /// granted folder, in which case the file system is not asked about it. pub(crate) fn locate(&self, path: &Path) -> Result { - if self.roots.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { + if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { return Err(ScriptRead::Refused); } probed(); @@ -484,22 +622,72 @@ impl ScriptScope { } Err(e) => return Err(ScriptRead::Failed(e.to_string())), }; - if !self.roots.iter().any(|r| inside(&real, r)) { + if !self.allows(&real) { return Err(ScriptRead::Refused); } Ok(real) } - /// Is the missing `path` inside a granted folder: does the nearest folder above it that exists - /// lie inside one? On a file system where case matters, `MAIN/x` beside the granted `main` is - /// outside, whether `MAIN` exists or not. A link above it that leads to nothing is outside too, - /// so a script cannot tell whether the folder a link leads to exists. + /// The real path that writing to `path` writes: `path` with its links followed (the last + /// name's too only when `follow`), and for a path that does not exist yet, its nearest existing + /// folder's links followed and the rest appended. Refused as [`ScriptScope::locate`] refuses a + /// path, also when a link on the way leads nowhere, and when the automation write roots in force + /// ([`check_write`]) do not take it. + pub(crate) fn target(&self, path: &Path, follow: bool) -> Result { + if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { + return Err(ScriptRead::Refused); + } + probed(); + if check_write(&path.to_string_lossy()).is_err() { + return Err(ScriptRead::Refused); + } + let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { return Err(ScriptRead::Refused) }; + let real = match std::fs::symlink_metadata(path) { + Ok(_) if follow => std::fs::canonicalize(path).map_err(|_| ScriptRead::Refused)?, + Ok(m) => { + // Where case does not matter, the name given can differ in case from the name the + // file system keeps, so a file or folder that is not a link is checked under the + // kept name too. + if !m.file_type().is_symlink() && !std::fs::canonicalize(path).is_ok_and(|kept| self.allows(&kept)) { + return Err(ScriptRead::Refused); + } + std::fs::canonicalize(parent).map_err(|_| ScriptRead::Refused)?.join(name) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + let mut missing = vec![name.to_os_string()]; + let mut at = parent; + loop { + match std::fs::symlink_metadata(at) { + Ok(_) => break, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + missing.push(at.file_name().ok_or(ScriptRead::Refused)?.to_os_string()); + at = at.parent().ok_or(ScriptRead::Refused)?; + } + Err(e) => return Err(ScriptRead::Failed(e.to_string())), + } + } + let mut real = std::fs::canonicalize(at).map_err(|_| ScriptRead::Refused)?; + real.extend(missing.iter().rev()); + real + } + Err(e) => return Err(ScriptRead::Failed(e.to_string())), + }; + // The automation write roots take the place written as well as the path named. + if !self.allows(&real) || check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_err() { + return Err(ScriptRead::Refused); + } + Ok(real) + } + + /// Is the missing `path` inside a granted place: with the links of the nearest folder above it + /// that exists followed, and the rest of its names appended, is it granted? On a file system + /// where case matters, `MAIN/x` beside the granted `main` is outside, whether `MAIN` exists or + /// not. A link above it that leads to nothing is outside too, so a script cannot tell whether + /// the folder a link leads to exists. fn missing_inside(&self, path: &Path) -> bool { - path.ancestors() - .skip(1) - .find(|a| std::fs::symlink_metadata(a).is_ok()) - .and_then(|a| std::fs::canonicalize(a).ok()) - .is_some_and(|real| self.roots.iter().any(|r| inside(&real, r))) + let Some(found) = path.ancestors().skip(1).find(|a| std::fs::symlink_metadata(a).is_ok()) else { return false }; + let (Ok(real), Ok(rest)) = (std::fs::canonicalize(found), path.strip_prefix(found)) else { return false }; + self.allows(&real.join(rest)) } /// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. @@ -542,7 +730,7 @@ impl ScriptScope { continue; } let Ok(target) = std::fs::canonicalize(entry.path()) else { continue }; - if !self.roots.iter().any(|r| inside(&target, r)) || check_read(&entry.path().to_string_lossy()).is_err() { + if !self.allows(&target) || check_read(&entry.path().to_string_lossy()).is_err() { continue; } if out.len() >= max { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3c3460ecb2..ebf52fb27f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -180,6 +180,10 @@ pub struct Session { /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). new_doc_profile_dir: Option, + /// The folder of each script's data folder (`Folder.userData`), beside which the grants file + /// keeps the file access people allowed scripts; `None`: no folder + /// ([`Session::attach_script_data`]). + script_data_dir: Option, /// A filter's output that a run made in the background handed in for `plugin.run` to apply /// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it. plugin_output: Option, diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ec848a973e..37f3b93213 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -21,7 +21,8 @@ //! `File` for an existing file, only where the path may be read. //! - Opening reads the whole file, at most [`MAX_FILE_BYTES`], checked from its size before any of //! it is read; a run reads at most [`MAX_RUN_BYTES`] in all and ends past that, and has at most -//! [`MAX_OPEN`] files open at once. +//! [`MAX_OPEN`] files open at once. A file opened again after its objects closed counts only the +//! bytes it has grown by; a file open in another object counts again. //! - The encoding of an opened file is the one its byte order mark gives (UTF-8, UTF-16LE or //! UTF-16BE), otherwise the one the script set, otherwise UTF-8 when the bytes are valid UTF-8, //! otherwise CP1252. `read`, `readln` and `readch` count characters and `seek` and `tell` bytes; @@ -29,12 +30,45 @@ //! as `"\n"`. A character the encoding cannot decode fails the read with [`UNDECODABLE`] and //! leaves the position where it was. //! - `getFiles` lists at most [`MAX_ENTRIES`] entries, sorted by name, and looks at most -//! [`crate::file_access::MAX_LISTED`] names; a mask matches `*` and `?` without regard to case, -//! in at most [`MAX_MASK_STEPS`] steps for one listing. +//! [`crate::file_access::MAX_LISTED`] names; a mask matches `*` and `?`, without regard to case +//! on Windows and macOS, in at most [`MAX_MASK_STEPS`] steps for one listing. //! - A path longer than [`MAX_PATH_CHARS`] characters is refused before it is split into names. -//! - Writing (`open` with `w`, `e` or `a`, `write`, `copy`, `remove`, `rename`, `create` and the -//! property setters), the file and folder dialogs and `execute` are not available: they return -//! `false` or `null` and set `error`. `execute` is counted in the report's `fileExecutes`. +//! - A script writes only in its run's temporary folder (`Folder.temp`, made when it is first +//! named and deleted when the run ends), its own data folder (`Folder.userData`: for a script run +//! from a file a folder of its own beside the settings, kept between runs, and for a script given +//! as text a folder inside the temporary one), and the files and folders a person granted it. +//! Its own folder is only read. The automation write roots apply as well, and the folder that +//! holds the settings, with the Scripts and Plug-ins folders, is kept out of every grant but the +//! script's data folder. +//! - In the app, `File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' +//! `openDlg`, `saveDlg` and `selectDlg` wait for the person, who picks a file or a folder and then +//! allows the script that one, once or always, or denies it ([`ScriptPicker`]). A picked file is +//! granted for reading (open) or for reading and writing (save), and a picked folder for reading +//! and writing with everything inside it. A `filter` that is a function is called with each file +//! picked, and the files it refuses are left out of what the dialog gives. Always keeps the grant in the grants file beside the +//! settings, for that script file with that text (its SHA-256): a changed or moved script has none, +//! and a kept grant whose path now leads elsewhere through a link is not used. +//! The grant also holds the SHA-256 of each source the run evaluated (a file `$.evalFile` ran, a +//! string given to `eval` or `Function`), up to the run's end: a later run that evaluates other +//! code, or whose named engine holds code its earlier runs compiled that the grant was not kept +//! for, loses the grant before that code runs. A run with nobody to ask gets `null` and +//! [`NO_PICKER`]. +//! - The commands a script runs with `vc.run` read and write only in the places above and in the +//! files of the open documents ([`crate::file_access::ScriptGate`]). +//! - `open('w')` empties the file at once; what a script writes is kept in memory, at most +//! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at +//! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an +//! ASCII or ISO-8859-1 file refuses a character it cannot hold, BINARY writes each character's low +//! byte) and `writeln` adds the `lineFeed`'s line end. `copy` replaces a file that is there, +//! `remove` deletes at once and takes a folder only when it is empty, `rename` takes a name without +//! a folder and refuses one in use, and `length` and `readonly` change a file (on Unix, clearing +//! `readonly` gives back the write bits the run cleared, or else the owner's). Each object that has +//! a file open holds its own bytes, so what `length` adds and what `copy` writes count once for the +//! file and once more for each such object. `write` joins its values only for an open file and +//! only up to twice [`MAX_FILE_BYTES`] UTF-16 code units. Each file written is named in the +//! report's `written` (at most [`super::MAX_WRITTEN`]), also after a run that failed. +//! - Hidden settings, aliases and `execute` are not available: they return `false` and set `error`. +//! `execute` is counted in the report's `fileExecutes`. //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; @@ -49,6 +83,9 @@ use crate::file_access::{ScriptRead, ScriptScope}; /// The most bytes of one file a script opens. pub const MAX_FILE_BYTES: usize = 8 << 20; +/// The most files a run remembers the bytes counted for, so opening one again counts only what it +/// grew by; a file past them counts in full each time it is opened. +const MAX_CHARGED: usize = 4096; /// The most bytes of files one run opens, all of them counted together. pub const MAX_RUN_BYTES: usize = 32 << 20; /// The most entries `getFiles` gives. @@ -69,36 +106,659 @@ pub(crate) const NOT_FOUND: &str = "Script file does not exist"; pub(crate) const READ_FAILED: &str = "Script file could not be read"; pub(crate) const LISTING_TOO_LARGE: &str = "Script folder has more than 2,048 entries"; pub(crate) const BAD_MODE: &str = "Script file open mode must be r, w, e or a"; -pub(crate) const NO_WRITES: &str = "Script file writing is not available"; -pub(crate) const NO_PICKER: &str = "Script file dialogs are not available"; +pub(crate) const NO_PICKER: &str = "Script file dialogs need a person to answer them"; pub(crate) const NO_EXECUTE: &str = "Script files cannot be opened in another application"; pub(crate) const NO_WEB: &str = "Script file access is unavailable on the web"; pub(crate) const TOO_MANY_OPEN: &str = "Script has 256 files open"; pub(crate) const PATH_TOO_LONG: &str = "Script file path exceeds 32,767 characters"; pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many steps to match"; +pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing"; +pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text"; +pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; +pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; +pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; +pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; +pub(crate) const NO_ALIAS: &str = "Script files cannot make aliases"; +pub(crate) const NO_HIDDEN: &str = "Script file hidden setting cannot be changed"; +pub(crate) const PROTECTED: &str = "Script file access to the app's own folders is not allowed"; +pub(crate) const NOT_SAVED: &str = "Script file permission could not be saved"; +pub(crate) const NO_ALWAYS: &str = "Script file permission can be kept only for a script run from a file"; const OVER_RUN_BYTES: &str = "the script opened more file data than one run may open (32 MiB)"; +const OVER_RUN_WRITES: &str = "the script wrote more file data than one run may write (32 MiB)"; +/// The most grants the grants file keeps. +pub const MAX_STORED_GRANTS: usize = 4096; +/// The most bytes of the grants file that are read. +const MAX_STORE_BYTES: usize = 4 << 20; +/// The name of the grants file, beside the folder of the scripts' data folders. +pub const GRANTS_FILE: &str = "Script Grants.json"; +/// The most distinct sources a run evaluates whose SHA-256 is kept; past them no kept grant is in +/// force for the rest of the run, and the run's grants keep the sources counted before. +pub const MAX_RUN_CODE: usize = 256; + +/// The SHA-256 of `units`, source text a script evaluated, as UTF-16 code units in little-endian +/// order. +pub(crate) fn code_hash(units: &[u16]) -> String { + let bytes: Vec = units.iter().flat_map(|u| u.to_le_bytes()).collect(); + vectorcraft_plugins::permissions::sha256_hex(&bytes) +} /// The id of the next file a script opens. Ids are unique across runs, so a `File` that a named /// engine kept from an earlier run does not name a file a later run opened. static NEXT_HANDLE: AtomicU32 = AtomicU32::new(1); -/// The script's file state: its scope, where `Folder.current` starts, the files it has open and how -/// much it has read. +/// The number in the name of the next run's temporary folder. +static NEXT_TEMP: AtomicU32 = AtomicU32::new(1); + +/// Which file dialog a script opened. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PickerKind { + /// `File.openDialog` and `openDlg`: a file to read. + Open, + /// `File.saveDialog` and `saveDlg`: a file to write, which may not exist yet. + Save, + /// `Folder.selectDialog` and `selectDlg`: a folder to read and write. + Folder, +} + +impl PickerKind { + /// The kind's name: `open`, `save` or `folder`. + pub fn id(self) -> &'static str { + match self { + Self::Open => "open", + Self::Save => "save", + Self::Folder => "folder", + } + } +} + +/// A file dialog a running script waits at: the person picks a file or a folder, then allows the +/// script that one, once or always, or denies it ([`PickAnswer`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScriptPicker { + pub kind: PickerKind, + /// The script's prompt, empty when it gave none. + pub prompt: String, + /// An open dialog that may pick more than one file. + pub multiple: bool, + /// The file or folder the dialog starts at, when the script's object gave one. + pub start: Option, + /// The file types the dialog shows, from the script's filter ([`dialog_filters`]): each one's + /// name and extensions (`*` for every file). Empty: every file. + pub filters: Vec<(String, Vec)>, + /// Whether the grant can be kept for later runs: the script was run from a file, and the app + /// has a settings folder for the grants file. + pub can_always: bool, +} + +/// The answer to a [`ScriptPicker`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PickAnswer { + /// Cancel or Deny: the script gets `null`. + Deny, + /// The paths picked, allowed for this run, or with `always` for later runs of the same script too. + Allow { paths: Vec, always: bool }, +} + +/// What a run's `File` and `Folder` objects start with. +#[derive(Clone, Debug, Default)] +pub(crate) struct Setup { + /// The run is in the app, where a person answers its file dialogs. + pub framed: bool, + /// The file the script was read from. + pub script: Option, + /// The script's text with the files it includes, whose SHA-256 the grants it keeps are for. + pub source: String, + /// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]). + pub data_dir: Option, + /// The code the run's named engine kept from its earlier runs: the SHA-256 of each source + /// ([`code_hash`] for evaluated code), and whether there was more than it keeps. + pub engine_code: (Vec, bool), +} + +/// A grant the grants file keeps that is in force for the run: the real path, whether it may be +/// written, whether it is a folder's, and the evaluated code the script ran in the run that kept it. +struct Stored { + path: std::path::PathBuf, + write: bool, + folder: bool, + code: std::collections::BTreeSet, +} + +/// The script's file state: where it reads and writes, where `Folder.current` starts, the files it +/// has open, how much it has read and written, and the file dialog it waits at. pub(crate) struct Disk { scope: ScriptScope, + /// Where the script writes: its temporary and data folders and what was granted for writing. + writes: ScriptScope, home: String, start: String, open: HashMap, temps: u32, bytes: usize, + /// The most bytes counted in `bytes` for each file read, by its real path ([`Disk::charge_read`]). + charged: HashMap, + written: usize, + framed: bool, + /// The script's file with its links followed, and the SHA-256 of its text. + script: Option<(std::path::PathBuf, String)>, + /// The SHA-256 of the script's text with the files it includes, also for a script given as + /// text, which its named engine keeps as code the engine holds. + own: String, + data_dir: Option, + /// The folder that holds the settings, with its links followed, which no grant reaches. + fenced: Option, + /// The run's temporary folder and the script's data folder, with their links followed, once made. + temp: Option, + user_data: Option, + /// The file dialog the script waits at. + pub(crate) picker: Option, + /// The error that ended the run when a dialog's answer could not reach the script. + pub(crate) failed: Option, + /// The files written since the host last took them ([`Disk::take_written`]). + wrote: Vec, + /// The places granted at the start (the script's own folder) and by the run itself (its + /// temporary and data folders and what a person allowed in a dialog), each with whether it + /// may be written and whether it is a folder: a withdrawn kept grant leaves these in force. + held: Vec<(std::path::PathBuf, bool, bool)>, + /// The kept grants in force: each is withdrawn once the run evaluates code it was not kept for. + stored: Vec, + /// The SHA-256 of each source other than the script itself that the run's code may run: what + /// it evaluated ([`code_hash`]) and what its named engine kept from earlier runs. + ran: std::collections::BTreeSet, + /// The run evaluated more distinct sources than [`MAX_RUN_CODE`]: no kept grant is in force. + ran_too_much: bool, + /// The grants this run kept with Always (path, write, folder), and how many sources `ran` held + /// when they were last written to the grants file. + kept: Vec<(std::path::PathBuf, bool, bool)>, + recorded: usize, + /// The write bits setting `readonly` cleared from each file in this run, by its device and + /// inode, which a rename keeps, at most [`MAX_ENTRIES`] files: clearing `readonly` gives them back. + #[cfg(unix)] + cleared: HashMap<(u64, u64), u32>, +} + +impl Drop for Disk { + fn drop(&mut self) { + // The run's end has flushed these already and reported what it could not write. + let _ = self.flush_all(); + if let Some(temp) = self.temp.take() { + let _ = std::fs::remove_dir_all(temp); + } + } } impl Disk { /// The state of a run whose own files are read in `scope`. - pub(crate) fn new(scope: &ScriptScope) -> Self { + pub(crate) fn new(scope: &ScriptScope, setup: Setup) -> Self { let home = home_folder(); let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned()); - Self { scope: scope.clone(), home, start, open: HashMap::new(), temps: 0, bytes: 0 } + let web = cfg!(target_arch = "wasm32"); + let script = setup.script.as_deref().filter(|_| !web).and_then(|p| std::fs::canonicalize(p).ok()); + let own = vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes()); + let script = script.map(|p| (p, own.clone())); + let fenced = setup.data_dir.as_deref().filter(|_| !web).and_then(Path::parent).and_then(real_or_planned); + let held = scope.roots().iter().map(|r| (r.clone(), false, true)).collect(); + let mut d = Self { + scope: scope.clone(), + writes: ScriptScope::default(), + home, + start, + open: HashMap::new(), + temps: 0, + bytes: 0, + charged: HashMap::new(), + written: 0, + framed: setup.framed, + script, + own, + data_dir: setup.data_dir, + fenced: fenced.clone(), + temp: None, + user_data: None, + picker: None, + failed: None, + wrote: Vec::new(), + held, + stored: Vec::new(), + ran: std::collections::BTreeSet::new(), + ran_too_much: setup.engine_code.1, + kept: Vec::new(), + recorded: 0, + #[cfg(unix)] + cleared: HashMap::new(), + }; + for hash in setup.engine_code.0 { + let _ = d.saw(hash); + } + if let Some(f) = fenced { + let own = d.scope.roots().to_vec(); + d.scope.fence(f.clone(), &own); + d.writes.fence(f, &[]); + } + if d.framed { + for g in d.stored() { + for (scope, granted) in [(&mut d.writes, g.write), (&mut d.scope, true)] { + match (granted, g.folder) { + (false, _) => {} + (true, true) => scope.add(g.path.clone()), + (true, false) => scope.add_file(g.path.clone()), + } + } + d.stored.push(g); + } + d.withdraw(); + } + d + } + + /// Notes that the run evaluates the source `units` (`eval`, `Function`, `$.evalFile`), before + /// it runs: the kept grants that were not kept for it are withdrawn. + pub(crate) fn saw_code(&mut self, units: &[u16]) { + if self.saw(code_hash(units)) { + self.withdraw(); + } + } + + /// Adds the source with SHA-256 `hash` to what the run's code may run. → whether it was new. + fn saw(&mut self, hash: String) -> bool { + if self.ran_too_much || self.ran.contains(&hash) || self.own == hash { + return false; + } + if self.ran.len() >= MAX_RUN_CODE { + self.ran_too_much = true; + } else { + self.ran.insert(hash); + } + true + } + + /// What the run's code may run, for its named engine to keep: each source's SHA-256 (the + /// script's own included, also for a script given as text) and whether there was more than + /// [`MAX_RUN_CODE`]. + pub(crate) fn code(&self) -> (Vec, bool) { + (std::iter::once(self.own.clone()).chain(self.ran.iter().cloned()).collect(), self.ran_too_much) + } + + /// Withdraws each kept grant whose run did not evaluate every source this run has: its place + /// is no longer read or written, unless the run holds it some other way, and files opened for + /// writing there are written now and take no more writes. + fn withdraw(&mut self) { + let (ran, all) = (&self.ran, self.ran_too_much); + let (stay, gone): (Vec, Vec) = std::mem::take(&mut self.stored).into_iter().partition(|g| !all && ran.is_subset(&g.code)); + self.stored = stay; + if gone.is_empty() { + return; + } + for g in &gone { + let held = |write: bool| { + self.held.iter().any(|(p, w, f)| *p == g.path && *f == g.folder && (*w || !write)) + || self.stored.iter().any(|s| s.path == g.path && s.folder == g.folder && (s.write || !write)) + }; + if !held(false) { + self.scope.remove(&g.path, g.folder); + } + if g.write && !held(true) { + self.writes.remove(&g.path, g.folder); + } + } + let ids: Vec = + self.open.iter().filter(|(_, o)| o.target.as_deref().is_some_and(|t| !self.writes.allows(t))).map(|(id, _)| *id).collect(); + for id in ids { + let written = self.flush(id).is_ok(); + if let Some(o) = self.open.get_mut(&id) { + // Changes that could not be written stay, so the run's end tries them again and + // reports the file when it still cannot. + o.withdrawn = true; + if written { + o.target = None; + } + } + } + } + + /// Writes the evaluated code this run ran into the grants it kept with Always, so a later run + /// of the same script that evaluates the same code keeps them in force. A grant that cannot be + /// updated keeps the code it was kept with. + pub(crate) fn record_code(&mut self) { + if self.kept.is_empty() || self.ran_too_much || self.ran.len() == self.recorded { + return; + } + let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return }; + let (script, code) = (shown(script), self.ran.iter().cloned().collect::>()); + let mut grants = read_store(&store); + for g in &mut grants { + let ours = g["script"] == *script + && g["sha256"] == *hash + && self.kept.iter().any(|(p, w, f)| g["path"] == *shown(p) && g["write"] == *w && g["folder"] == *f); + if ours { + g["code"] = serde_json::json!(code); + } + } + if write_store(&store, grants).is_ok() { + self.recorded = self.ran.len(); + } + } + + /// The gate for a command the script runs: the places it reads and writes now, and the files of + /// the open documents, `documents`. + pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents } + } + + /// The files written since this was last asked, to name in the report. + pub(crate) fn take_written(&mut self) -> Vec { + std::mem::take(&mut self.wrote) + } + + fn wrote(&mut self, real: &Path) { + let shown = crate::cmd::findfiles::plain(real.to_path_buf()).to_string_lossy().into_owned(); + if !self.wrote.contains(&shown) { + self.wrote.push(shown); + } + } + + /// Grants the real path `real`, a folder with everything in it (`folder`) or a file, for + /// reading, and with `write` for writing too. + fn grant(&mut self, real: std::path::PathBuf, write: bool, folder: bool) { + let scopes = if write { vec![&mut self.writes, &mut self.scope] } else { vec![&mut self.scope] }; + for scope in scopes { + if folder { scope.add(real.clone()) } else { scope.add_file(real.clone()) } + } + self.held.push((real, write, folder)); + } + + /// The run's temporary folder, made the first time it is asked for; `None` when it cannot be + /// made, when the automation write roots do not take it, and on the web. + fn temp_dir(&mut self) -> Option { + if cfg!(target_arch = "wasm32") { + return None; + } + if self.temp.is_none() { + let base = std::env::temp_dir(); + let made = (0..64).find_map(|_| { + let n = NEXT_TEMP.fetch_add(1, Ordering::Relaxed); + let dir = base.join(format!("VectorCraft Script {}-{n}", std::process::id())); + crate::file_access::check_write(&dir.to_string_lossy()).ok()?; + std::fs::create_dir(&dir).ok().and_then(|()| std::fs::canonicalize(&dir).ok()) + })?; + self.grant(made.clone(), true, true); + self.temp = Some(made); + } + self.temp.clone().map(crate::cmd::findfiles::plain) + } + + /// The script's data folder, made the first time it is asked for: for a script run from a file, + /// a folder named by the SHA-256 of its path in the data folder, and otherwise a folder in the + /// run's temporary folder. `None` when that folder is a link, cannot be made, or is outside the + /// automation write roots. + fn user_data_dir(&mut self) -> Option { + if cfg!(target_arch = "wasm32") { + return None; + } + if self.user_data.is_none() { + let dir = match (&self.script, &self.data_dir) { + (Some((path, _)), Some(data)) => { + let key = vectorcraft_plugins::permissions::sha256_hex(path.to_string_lossy().as_bytes()); + data.join(key.get(..16).unwrap_or(&key)) + } + _ => self.temp_dir()?.join("userData"), + }; + crate::file_access::check_write(&dir.to_string_lossy()).ok()?; + // Each missing folder above it that is made on the way must be inside the write roots too. + for missing in dir.ancestors().skip(1).take_while(|a| !a.as_os_str().is_empty() && std::fs::symlink_metadata(a).is_err()) { + crate::file_access::check_write(&missing.to_string_lossy()).ok()?; + } + // The data folder that holds the folder, and then the folder, are folders where they are + // named, not links; the folder is made only once the data folder is checked. + let direct = |d: &Path| -> Option { + let (parent, name) = (std::fs::canonicalize(d.parent()?).ok()?, d.file_name()?); + let real = std::fs::canonicalize(d).ok()?; + (real == parent.join(name) && std::fs::symlink_metadata(d).is_ok_and(|m| m.is_dir())).then_some(real) + }; + std::fs::create_dir_all(dir.parent()?).ok()?; + direct(dir.parent()?)?; + std::fs::create_dir_all(&dir).ok()?; + let real = direct(&dir)?; + self.scope.fence_open(real.clone()); + self.writes.fence_open(real.clone()); + self.grant(real.clone(), true, true); + self.user_data = Some(real); + } + self.user_data.clone().map(crate::cmd::findfiles::plain) + } + + /// The grants file, beside the scripts' data folders. + fn store_path(&self) -> Option { + self.data_dir.as_ref().map(|d| d.with_file_name(GRANTS_FILE)) + } + + /// The grants the grants file keeps for this script with this text: each path, whether it may + /// be written, whether it is a folder, and the evaluated code it was kept for. A grant whose + /// path no longer is its own real path is left out. + fn stored(&self) -> Vec { + let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Vec::new() }; + let script = shown(script); + read_store(&store) + .into_iter() + .filter(|g| g["script"] == *script && g["sha256"] == *hash) + .filter_map(|g| { + let code = g["code"].as_array()?.iter().map(|c| c.as_str().map(str::to_string)).collect::>()?; + let (write, folder) = (g["write"].as_bool()?, g["folder"].as_bool()?); + // The grant stays on the real path it was kept for: a path that now leads elsewhere, + // through a link put in its place or in a folder above it, is not granted. + let saved = g["path"].as_str()?; + let path = real_of(Path::new(saved)).filter(|real| shown(real) == saved)?; + Some(Stored { path, write, folder, code }) + }) + .filter(|g| self.fenced.as_ref().is_none_or(|f| !crate::file_access::path_inside(&g.path, f))) + .collect() + } + + /// Adds grants of `paths` (with `write`, folders when `folder`) for this script to the grants + /// file, with the code the run has evaluated so far, written whole to a file beside it that then + /// takes its place. + fn keep(&self, paths: &[std::path::PathBuf], write: bool, folder: bool) -> Result<(), &'static str> { + let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Err(NO_ALWAYS) }; + let mut grants = read_store(&store); + let script = shown(script); + let code: Vec<&String> = self.ran.iter().collect(); + for p in paths { + let path = shown(p); + grants + .retain(|g| !(g["script"] == *script && g["sha256"] == *hash && g["path"] == *path && g["write"] == write && g["folder"] == folder)); + grants.push(serde_json::json!({"script": script, "sha256": hash, "code": code, "path": path, "write": write, "folder": folder})); + } + if grants.len() > MAX_STORED_GRANTS { + return Err(NOT_SAVED); + } + write_store(&store, grants).map_err(|_| NOT_SAVED) + } + + /// The paths a person picked in the dialog the script waits at, allowed (`always`: kept for + /// later runs too), or denied; → what the dialog's call gives the script (a path, a list of + /// paths for an open dialog that picks more than one, `null`, or `{error}`), `None` when no + /// dialog waits. + pub(crate) fn answer(&mut self, answer: PickAnswer) -> Option { + let picker = self.picker.take()?; + let PickAnswer::Allow { paths, always } = answer else { return Some(Data::Null) }; + Some(self.allow(&picker, &paths, always).unwrap_or_else(error)) + } + + fn allow(&mut self, picker: &ScriptPicker, paths: &[String], always: bool) -> Result { + let wanted = if picker.multiple { paths.len().min(MAX_ENTRIES) } else { 1 }; + let mut reals = Vec::new(); + for p in paths.iter().take(wanted) { + reals.push(self.picked(picker.kind, p)?); + } + if reals.is_empty() { + return Ok(Data::Null); + } + let (write, folder) = (picker.kind != PickerKind::Open, picker.kind == PickerKind::Folder); + if always { + self.keep(&reals, write, folder)?; + self.kept.extend(reals.iter().map(|r| (r.clone(), write, folder))); + self.recorded = self.ran.len(); + } + let mut picked = Vec::new(); + for real in reals { + picked.push(Data::String(self.pathname(&shown(&real), &self.start, false).fs())); + self.grant(real, write, folder); + } + Ok(match picked.len() { + 1 if !picker.multiple => picked.swap_remove(0), + _ => Data::Array(picked), + }) + } + + /// The real path of `path`, which a person picked in a dialog of `kind`: a file that is there + /// (open), a folder that is there (folder), or a file whose folder is there (save). A network or + /// device path, and a place in the folder that holds the settings, are refused. + fn picked(&self, kind: PickerKind, path: &str) -> Result { + let p = self.checked(path)?; + if ScriptScope::refused_by_name(p) { + return Err(ACCESS_DENIED); + } + let real = match kind { + PickerKind::Save if std::fs::symlink_metadata(p).is_err() => { + let (Some(dir), Some(name)) = (p.parent(), p.file_name()) else { return Err(ACCESS_DENIED) }; + std::fs::canonicalize(dir).map_err(|_| NOT_FOUND)?.join(name) + } + _ => std::fs::canonicalize(p).map_err(|_| NOT_FOUND)?, + }; + match kind { + PickerKind::Folder if !real.is_dir() => return Err(NOT_FOUND), + PickerKind::Open if !real.is_file() => return Err(NOT_REGULAR), + PickerKind::Save if real.is_dir() => return Err(NOT_REGULAR), + _ => {} + } + if self.fenced.as_ref().is_some_and(|f| crate::file_access::path_inside(&real, f)) + && !self.user_data.as_ref().is_some_and(|u| crate::file_access::path_inside(&real, u)) + { + return Err(PROTECTED); + } + Ok(real) + } + + /// The real path writing to `path` writes, or why it may not ([`ScriptScope::target`]). + fn target(&self, path: &str, follow: bool) -> Result { + let p = self.checked(path)?; + match self.writes.target(p, follow) { + Ok(real) => Ok(real), + Err(ScriptRead::Failed(_)) => Err(WRITE_FAILED), + Err(_) => Err(ACCESS_DENIED), + } + } + + /// Counts `n` more bytes written in the run, which ends past [`MAX_RUN_BYTES`]. + fn charge_write(&mut self, n: usize) -> Result<(), HostError> { + self.written = self.written.saturating_add(n); + if self.written > MAX_RUN_BYTES { + return Err(HostError::Abort(OVER_RUN_WRITES.to_string())); + } + Ok(()) + } + + /// Opens the file at `path` for writing in `mode` (`w`, `e` or `a`). + fn open_write(&mut self, path: &str, encoding: &str, mode: &str) -> Result { + let fail = |m: &str| Err(HostError::Error(m.to_string())); + if self.open.len() >= MAX_OPEN { + return fail(TOO_MANY_OPEN); + } + let real = match self.target(path, true) { + Ok(real) => real, + Err(m) => return fail(m), + }; + let meta = std::fs::metadata(&real).ok(); + if meta.as_ref().is_some_and(|m| !m.is_file()) { + return fail(NOT_REGULAR); + } + if mode == "e" && meta.is_none() { + return fail(NOT_FOUND); + } + // Changes other open objects hold for the file are written before it is opened again, so + // they do not later replace what this one writes. + let ids: Vec = self.open.iter().filter(|(_, o)| o.target.as_deref() == Some(real.as_path())).map(|(id, _)| *id).collect(); + if let Err(m) = ids.iter().try_for_each(|id| self.flush(*id)) { + return fail(m); + } + let bytes = if mode == "w" || meta.is_none() { + // An encoding that is not one is refused before the file is emptied. + if Open::new(Vec::new(), encoding).is_none() { + return Err(HostError::Error(UNDECODABLE.to_string())); + } + if std::fs::File::create(&real).is_err() { + return fail(WRITE_FAILED); + } + self.wrote(&real); + Vec::new() + } else { + if meta.as_ref().is_some_and(|m| m.len() > MAX_FILE_BYTES as u64) { + return fail(TOO_LARGE); + } + // The bytes kept are read under the rules for reading. + let bytes = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { + Ok((at, bytes)) if at == real => bytes, + Ok(_) | Err(ScriptRead::Refused) => return fail(ACCESS_DENIED), + Err(ScriptRead::TooLarge) => return fail(TOO_LARGE), + Err(ScriptRead::Missing) => return fail(NOT_FOUND), + Err(ScriptRead::Failed(_)) => return fail(READ_FAILED), + }; + if bytes.len() > MAX_FILE_BYTES { + return fail(TOO_LARGE); + } + self.charge_read(&real, bytes.len())?; + bytes + }; + let mut file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; + if mode == "a" { + file.pos = file.bytes.len(); + } + file.read_from = Some(real.clone()); + file.target = Some(real); + Ok(self.insert(file)) + } + + fn insert(&mut self, file: Open) -> u32 { + let mut id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + while id == 0 || self.open.contains_key(&id) { + id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + } + self.open.insert(id, file); + id + } + + /// Writes the open file `id`'s bytes to its file when it has changed. `Err` when it could not. + fn flush(&mut self, id: u32) -> Result<(), &'static str> { + let Some(file) = self.open.get_mut(&id) else { return Ok(()) }; + let Some(real) = file.target.clone().filter(|_| file.dirty) else { return Ok(()) }; + // A link put in the file's place, or in place of a folder above it, since it was opened is + // not written through. + let moved = real.parent().is_some_and(|p| std::fs::canonicalize(p).is_ok_and(|c| c != p)); + if moved || std::fs::symlink_metadata(&real).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(ACCESS_DENIED); + } + // The file stays changed until its bytes are written, so the run's end tries it again. + std::fs::write(&real, &file.bytes).map_err(|_| WRITE_FAILED)?; + file.dirty = false; + self.wrote(&real); + Ok(()) + } + + /// Writes every open file that has changed: at the end of the run. → the files that could not + /// be written, as the report gives them. + pub(crate) fn flush_all(&mut self) -> Vec { + // In the order the files were opened, so the object opened last writes a file last. + let mut ids: Vec = self.open.keys().copied().collect(); + ids.sort_unstable(); + let mut failed = Vec::new(); + for id in ids { + if self.flush(id).is_err() + && let Some(real) = self.open.get(&id).and_then(|o| o.target.as_deref()) + { + failed.push(shown(real)); + } + } + failed } /// The path `text` names from the folder `base`, a platform path; `text`'s URI escapes are @@ -150,30 +810,131 @@ impl Disk { if entry.len > MAX_FILE_BYTES as u64 { return fail(TOO_LARGE); } - if self.bytes.saturating_add(entry.len as usize) > MAX_RUN_BYTES { - return Err(HostError::Abort(OVER_RUN_BYTES.to_string())); - } - let bytes = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { - Ok((_, bytes)) => bytes, + let (real, bytes) = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { + Ok(read) => read, Err(ScriptRead::TooLarge) => return fail(TOO_LARGE), Err(ScriptRead::Missing) => return fail(NOT_FOUND), Err(ScriptRead::Refused) => return fail(ACCESS_DENIED), Err(ScriptRead::Failed(_)) => return fail(READ_FAILED), }; - if self.bytes.saturating_add(bytes.len()) > MAX_RUN_BYTES { + self.charge_read(&real, bytes.len())?; + let mut file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; + file.read_from = Some(real); + Ok(self.insert(file)) + } + + /// Counts `n` bytes read from the file `real` in the run, which ends past [`MAX_RUN_BYTES`]. A + /// file opened again once no open object holds it counts only the bytes past the most read from + /// it before; while another object holds it, all of them count, as each holds its own copy. + fn charge_read(&mut self, real: &Path, n: usize) -> Result<(), HostError> { + let held = self.open.values().any(|o| o.read_from.as_deref() == Some(real)); + let before = if held { 0 } else { self.charged.get(real).copied().unwrap_or(0) }; + let more = n.saturating_sub(before); + if self.bytes.saturating_add(more) > MAX_RUN_BYTES { return Err(HostError::Abort(OVER_RUN_BYTES.to_string())); } - self.bytes += bytes.len(); - let file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; - let mut id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); - while id == 0 || self.open.contains_key(&id) { - id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + self.bytes += more; + if !held && n > before && (self.charged.contains_key(real) || self.charged.len() < MAX_CHARGED) { + self.charged.insert(real.to_path_buf(), n); } - self.open.insert(id, file); - Ok(id) + Ok(()) } } +/// The real path `real` as the grants file and the report give it. +fn shown(real: &Path) -> String { + crate::cmd::findfiles::plain(real.to_path_buf()).to_string_lossy().into_owned() +} + +/// The path `p` with its links followed; for a missing file whose folder is there, that folder's +/// real path and the file's name. +fn real_of(p: &Path) -> Option { + std::fs::canonicalize(p).ok().or_else(|| Some(std::fs::canonicalize(p.parent()?).ok()?.join(p.file_name()?))) +} + +/// The path `p` with its links followed, also when it is not there yet: the real path of the +/// nearest folder above it that is there, and the names below that folder. +fn real_or_planned(p: &Path) -> Option { + let mut names = Vec::new(); + let mut at = p; + loop { + if let Ok(real) = std::fs::canonicalize(at) { + return Some(names.iter().rev().fold(real, |real, name| real.join(name))); + } + names.push(at.file_name()?); + at = at.parent()?; + } +} + +/// The first `max` bytes of the file at `real`, and one more when it has more. +fn read_head(real: &Path, max: usize) -> std::io::Result> { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(real)?.take(max as u64 + 1).read_to_end(&mut bytes)?; + Ok(bytes) +} + +/// The grants the grants file at `store` holds; none when it is missing or cannot be read. +fn read_store(store: &Path) -> Vec { + let Ok(bytes) = read_head(store, MAX_STORE_BYTES) else { return Vec::new() }; + if bytes.len() > MAX_STORE_BYTES { + return Vec::new(); + } + let Ok(v) = serde_json::from_slice::(&bytes) else { return Vec::new() }; + if v["version"] != 1 { + return Vec::new(); + } + let valid = |g: &serde_json::Value| { + g["script"].is_string() + && g["sha256"].is_string() + && g["code"].as_array().is_some_and(|c| c.iter().all(serde_json::Value::is_string)) + && g["path"].is_string() + && g["write"].is_boolean() + && g["folder"].is_boolean() + }; + v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default() +} + +/// Writes `grants` as the grants file at `store`: to a file beside it, which then takes its place. +/// `Err`, with the file left as it was, when the grants take more than [`MAX_STORE_BYTES`]. +fn write_store(store: &Path, grants: Vec) -> std::io::Result<()> { + let text = serde_json::to_vec_pretty(&serde_json::json!({"version": 1, "grants": grants})).map_err(std::io::Error::other)?; + if text.len() > MAX_STORE_BYTES { + return Err(std::io::Error::other("the grants file would be too large")); + } + if let Some(dir) = store.parent() { + std::fs::create_dir_all(dir)?; + } + let part = store.with_extension("json.part"); + std::fs::write(&part, text)?; + // `rename` replaces a grants file that is there, on Windows too (`MOVEFILE_REPLACE_EXISTING`). + std::fs::rename(&part, store).inspect_err(|_| { + let _ = std::fs::remove_file(&part); + }) +} + +/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of +/// its text, the path and whether it may be written (`script.grants`). +pub(crate) fn stored_grants(data_dir: &Path) -> Vec { + read_store(&data_dir.with_file_name(GRANTS_FILE)) +} + +/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path +/// `path`, of both when both are given and of every grant when neither is (`script.grants.revoke`). +/// → how many were removed. +pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result { + let store = data_dir.with_file_name(GRANTS_FILE); + let grants = read_store(&store); + let before = grants.len(); + let kept: Vec = + grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); + let removed = before - kept.len(); + if removed > 0 { + write_store(&store, kept)?; + } + Ok(removed) +} + /// Whether paths are read as Windows reads them. const WINDOWS: bool = cfg!(windows); @@ -188,21 +949,20 @@ fn home_folder() -> String { std::env::var(var).unwrap_or_else(|_| if WINDOWS { r"C:\".to_string() } else { "/".to_string() }) } -/// The folders `Folder.temp`, `Folder.desktop` and the others name, `null` where there is none. -/// On the web every one is `null`, and no platform folder is looked up. -fn locations(home: &str) -> Data { +/// The folders `Folder.temp`, `Folder.desktop` and the others name, `null` where there is none: +/// `temp` and `user_data` are the run's own. On the web every one is `null`, and no platform folder +/// is looked up. +fn locations(home: &str, temp: Option, user_data: Option) -> Data { if cfg!(target_arch = "wasm32") { return Data::Object(PLACES.iter().map(|k| (k.to_string(), Data::Null)).collect()); } let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); let join = |a: &str, b: &str| Path::new(a).join(b).to_string_lossy().into_owned(); let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_string_lossy().into_owned())); - let temp = temp_folder().to_string_lossy().into_owned(); - let (user_data, app_data, common, system, trash) = if WINDOWS { - (env("APPDATA"), env("PROGRAMDATA"), env("CommonProgramFiles"), env("SystemRoot"), None) + let (app_data, common, system, trash) = if WINDOWS { + (env("PROGRAMDATA"), env("CommonProgramFiles"), env("SystemRoot"), None) } else if cfg!(target_os = "macos") { ( - Some(join(home, "Library/Application Support")), Some("/Library/Application Support".to_string()), Some("/Library/Application Support".to_string()), Some("/System".to_string()), @@ -210,7 +970,7 @@ fn locations(home: &str) -> Data { ) } else { let data = env("XDG_DATA_HOME").unwrap_or_else(|| join(home, ".local/share")); - (Some(data.clone()), Some("/usr/share".to_string()), Some("/usr/share".to_string()), Some("/".to_string()), Some(join(&data, "Trash"))) + (Some("/usr/share".to_string()), Some("/usr/share".to_string()), Some("/".to_string()), Some(join(&data, "Trash"))) }; let s = |v: Option| v.map_or(Data::Null, Data::String); let places = vec![ @@ -221,7 +981,7 @@ fn locations(home: &str) -> Data { ("myDocuments", Some(join(home, "Documents"))), ("startup", exe), ("system", system), - ("temp", Some(temp)), + ("temp", temp), ("trash", trash), ("userData", user_data), ]; @@ -231,7 +991,8 @@ fn locations(home: &str) -> Data { /// The names [`locations`] gives. const PLACES: [&str; 10] = ["appData", "appPackage", "commonFiles", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; -/// The folder for temporary files: the platform's, or on the web the root, where nothing is read. +/// The folder for temporary files when the run's own cannot be made: the platform's, or on the web +/// the root, where nothing is read. fn temp_folder() -> std::path::PathBuf { if cfg!(target_arch = "wasm32") { std::path::PathBuf::from("/") } else { std::env::temp_dir() } } @@ -395,31 +1156,44 @@ fn decode(s: &str) -> String { String::from_utf8(out).unwrap_or_else(|_| s.to_string()) } +/// Do file names match a mask without regard to case: on Windows and macOS, whose file systems +/// usually do not tell names apart by case. Elsewhere case matters. +const MASK_IGNORES_CASE: bool = cfg!(any(windows, target_os = "macos")); + /// A `getFiles` mask, where `*` stands for any run of characters and `?` for one, without regard -/// to case, read once for a whole listing. +/// to case where the file system does not tell names apart by case ([`MASK_IGNORES_CASE`]), read +/// once for a whole listing. struct Mask { - /// The mask in lower case, each run of `*` written as one. + /// The mask, in lower case when case does not matter, each run of `*` written as one. chars: Vec, /// How many of its characters are not `*`: a name with fewer characters does not match. fixed: usize, + /// Names are compared without regard to case. + fold: bool, } impl Mask { fn new(mask: &str) -> Self { + Self::with_case(mask, MASK_IGNORES_CASE) + } + + /// The mask `mask`, which compares names without regard to case when `fold`. + fn with_case(mask: &str, fold: bool) -> Self { let mut chars: Vec = Vec::new(); - for c in mask.to_lowercase().chars() { + let text = if fold { mask.to_lowercase() } else { mask.to_string() }; + for c in text.chars() { if !(c == '*' && chars.last() == Some(&'*')) { chars.push(c); } } let fixed = chars.iter().filter(|c| **c != '*').count(); - Self { chars, fixed } + Self { chars, fixed, fold } } /// Does `name` match, taking a step from `steps` for each character compared? `None` when the /// steps run out first. fn matches(&self, name: &str, steps: &mut usize) -> Option { - let n: Vec = name.to_lowercase().chars().collect(); + let n: Vec = if self.fold { name.to_lowercase().chars().collect() } else { name.chars().collect() }; if n.len() < self.fixed { return Some(false); } @@ -427,7 +1201,7 @@ impl Mask { } } -/// Does `n` match the lower-case mask `m`? `None` when `steps` run out first. +/// Does `n` match the mask `m`, both in the same case? `None` when `steps` run out first. fn matched(m: &[char], n: &[char], steps: &mut usize) -> Option { let (mut i, mut j, mut star, mut mark) = (0usize, 0usize, None, 0usize); while j < n.len() { @@ -488,6 +1262,30 @@ impl Encoding { }) } + /// `text` in this encoding; `None` when a character has no form in it. BINARY writes each + /// character's low byte. + fn encode(self, text: &str) -> Option> { + let mut out = Vec::with_capacity(text.len()); + for c in text.chars() { + let code = u32::from(c); + match self { + Self::Utf8 => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()), + Self::Ascii if code < 0x80 => out.push(code as u8), + Self::Binary => out.push((code & 0xFF) as u8), + Self::Latin1 if code <= 0xFF => out.push(code as u8), + Self::Cp1252 if code < 0x80 || (0xA0..=0xFF).contains(&code) => out.push(code as u8), + Self::Cp1252 => out.push(0x80 + CP1252_HIGH.iter().position(|h| u32::from(*h) == code)? as u8), + Self::Utf16Le | Self::Utf16Be => { + for unit in c.encode_utf16(&mut [0; 2]) { + out.extend_from_slice(&if self == Self::Utf16Le { unit.to_le_bytes() } else { unit.to_be_bytes() }); + } + } + Self::Ascii | Self::Latin1 => return None, + } + } + Some(out) + } + fn name(self) -> &'static str { match self { Self::Utf8 => "UTF-8", @@ -501,12 +1299,20 @@ impl Encoding { } } -/// An opened file: its bytes, the byte position and the encoding it is read in. +/// An opened file: its bytes, the byte position and the encoding it is read in; for a file opened +/// for writing, the real path its bytes are written to and whether they changed since. struct Open { bytes: Vec, pos: usize, encoding: Encoding, name: String, + target: Option, + /// The real path of the file the object was opened on, whose bytes it holds. + read_from: Option, + dirty: bool, + /// The grant the file was opened under was withdrawn while its changes could not be written: + /// they are written again when the run ends, and the object takes no more writes. + withdrawn: bool, } impl Open { @@ -526,7 +1332,28 @@ impl Open { } else { (Encoding::Cp1252, 0) }; - Some(Self { bytes, pos, encoding, name: encoding.name().to_string() }) + Some(Self { bytes, pos, encoding, name: encoding.name().to_string(), target: None, read_from: None, dirty: false, withdrawn: false }) + } + + /// Writes `text` at the position, over what is there and past the end, when it takes at most + /// `left` bytes; → the bytes written. + fn write(&mut self, text: &str, left: usize) -> Result { + if self.target.is_none() || self.withdrawn { + return Err(NOT_WRITABLE); + } + let bytes = self.encoding.encode(text).ok_or(UNENCODABLE)?; + if bytes.len() > left { + return Err(OVER_RUN_WRITES); + } + let end = self.pos.saturating_add(bytes.len()); + if end.max(self.bytes.len()) > MAX_FILE_BYTES { + return Err(TOO_LARGE); + } + let over = end.min(self.bytes.len()); + self.bytes.splice(self.pos..over, bytes.iter().copied()); + self.pos = end; + self.dirty = true; + Ok(bytes.len()) } /// The character at byte `at` and its length in bytes; `Ok(None)` at the end, `Err` where the @@ -661,12 +1488,22 @@ fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem::Function(Rc::new(move |a| { let h = super::current(&l)?; bump(&h.counts.file_calls); - let r = f(&h, &a)?; + let r = f(&h, &a); + h.note_written(h.disk.borrow_mut().take_written()); + let r = r?; h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?; Ok(r) })) } +/// `Ok(true)`, or `{error}` for a failure. +fn done(r: Result<(), &'static str>) -> Data { + match r { + Ok(()) => Data::Bool(true), + Err(m) => error(m), + } +} + fn handle(a: &[Data]) -> u32 { arg_number(a, 0).filter(|n| n.is_finite() && *n >= 0.0 && *n <= f64::from(u32::MAX)).map_or(0, |n| n as u32) } @@ -720,16 +1557,384 @@ fn stat(host: &Host, a: &[Data]) -> Result { }) } +/// `open(path, encoding, mode)`: `r` reads, `w`, `e` and `a` write. fn open(host: &Host, a: &[Data]) -> Result { - match host.disk.borrow_mut().open_file(&arg_text(a, 0), &arg_text(a, 1)) { + let (path, encoding, mode) = (arg_text(a, 0), arg_text(a, 1), arg_text(a, 2)); + let mut disk = host.disk.borrow_mut(); + let opened = match mode.as_str() { + "w" | "e" | "a" => disk.open_write(&path, &encoding, &mode), + _ => disk.open_file(&path, &encoding), + }; + match opened { Ok(id) => Ok(Data::Object(vec![("id".into(), Data::Number(f64::from(id)))])), Err(HostError::Error(m)) => Ok(error(&m)), Err(e) => Err(e), } } +/// Closes the open file, writing what changed: `true`, `false` when it was not open, or `{error}` +/// when it could not be written. A file that could not be written is kept for the run's end to +/// write again. fn close(host: &Host, a: &[Data]) -> Result { - Ok(Data::Bool(host.disk.borrow_mut().open.remove(&handle(a)).is_some())) + let mut disk = host.disk.borrow_mut(); + let id = handle(a); + Ok(match disk.flush(id) { + Err(m) => error(m), + Ok(()) => Data::Bool(disk.open.remove(&id).is_some()), + }) +} + +/// `write(id, text)`. A write past the run's limit ends the run and leaves the file as it was. +fn write(host: &Host, a: &[Data]) -> Result { + let text = arg_text(a, 1); + let mut disk = host.disk.borrow_mut(); + let left = MAX_RUN_BYTES.saturating_sub(disk.written); + let r = match disk.open.get_mut(&handle(a)) { + Some(file) => file.write(&text, left), + None => Err(NOT_OPEN), + }; + match r { + Ok(n) => { + disk.charge_write(n)?; + Ok(Data::Bool(true)) + } + Err(OVER_RUN_WRITES) => Err(HostError::Abort(OVER_RUN_WRITES.to_string())), + Err(m) => Ok(error(m)), + } +} + +/// `copy(from, to)`: the file `from` to `to`, replacing a file that is there. +fn copy(host: &Host, a: &[Data]) -> Result { + let (from, to) = (arg_text(a, 0), arg_text(a, 1)); + let mut disk = host.disk.borrow_mut(); + let source = match disk.stat(&from) { + Ok(Some(e)) if e.file => disk.checked(&from).ok().and_then(|p| disk.scope.locate(p).ok()), + Ok(Some(_)) => return Ok(error(NOT_REGULAR)), + Ok(None) => return Ok(error(NOT_FOUND)), + Err(m) => return Ok(error(m)), + }; + let Some(source) = source else { return Ok(error(ACCESS_DENIED)) }; + let target = match disk.target(&to, true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + if std::fs::metadata(&target).is_ok_and(|m| !m.is_file()) { + return Ok(error(NOT_REGULAR)); + } + // A file copied onto itself, by its own name or by another link to it, is already its copy once + // its open objects are written, and copying could empty it. + let one = |t: &std::fs::Metadata| std::fs::metadata(&source).is_ok_and(|s| same_file((&source, &s), (&target, t))); + let itself = real_of(&target).is_some_and(|t| t == source) || std::fs::metadata(&target).is_ok_and(|t| one(&t)); + // The source's open objects write what they hold first, so the copy has it. + let ids: Vec = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(source.as_path())).map(|(id, _)| *id).collect(); + if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { + return Ok(error(m)); + } + let n = std::fs::metadata(&source).map_or(0, |m| m.len()); + if n > MAX_FILE_BYTES as u64 { + return Ok(error(TOO_LARGE)); + } + // The target's open objects each take a copy of the bytes, which count as written too, as does + // the copy itself when it is written. + let holders = disk.open.values().filter(|o| o.target.as_deref() == Some(target.as_path())).count(); + disk.charge_write(usize::try_from(n).unwrap_or(usize::MAX).saturating_mul(holders.saturating_add(usize::from(!itself))))?; + let r = if itself { Ok(n) } else { std::fs::copy(&source, &target) }; + if !itself && (r.is_ok() || target.exists()) { + disk.wrote(&target); + } + // Open objects of the target hold the copy, so closing them does not write their older bytes. + if r.is_ok() && disk.open.values().any(|o| o.target.as_deref() == Some(target.as_path())) { + let copied = read_head(&target, MAX_FILE_BYTES).unwrap_or_default(); + for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + file.bytes.clone_from(&copied); + file.pos = file.pos.min(copied.len()); + file.dirty = false; + } + } + Ok(done(r.map(drop).map_err(|_| WRITE_FAILED))) +} + +/// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to. +fn remove(host: &Host, a: &[Data]) -> Result { + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&arg_text(a, 0), false) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + let r = match std::fs::symlink_metadata(&target) { + Err(_) => Err(NOT_FOUND), + Ok(m) if m.is_dir() => std::fs::remove_dir(&target) + .map_err(|_| if std::fs::read_dir(&target).is_ok_and(|mut d| d.next().is_some()) { NOT_EMPTY } else { WRITE_FAILED }), + Ok(m) => std::fs::remove_file(&target).map_err(|_| WRITE_FAILED).inspect(|()| { + // A file made later in its place, which may take its inode, gets none of its write bits. + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if m.nlink() <= 1 { + disk.cleared.remove(&(m.dev(), m.ino())); + } + } + #[cfg(not(unix))] + let _ = m; + }), + }; + if r.is_ok() { + // Other open objects of the file drop their changes and take no more writes, so neither + // their close nor the run's end makes the file again. + for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + file.dirty = false; + file.target = None; + } + disk.wrote(&target); + } + Ok(done(r)) +} + +/// `rename(path, name)`: the file or folder named `name` in the same folder; → `{fs}`, its new path. +fn rename(host: &Host, a: &[Data]) -> Result { + let (path, name) = (arg_text(a, 0), arg_text(a, 1)); + let bad = name.is_empty() || name == "." || name == ".." || name.contains('/') || (WINDOWS && (name.contains('\\') || name.contains(':'))); + if bad || name.contains('\0') { + return Ok(error(BAD_NAME)); + } + let Some(new) = Path::new(&path).parent().map(|p| p.join(&name).to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) }; + let mut disk = host.disk.borrow_mut(); + let (from, to) = match (disk.target(&path, false), disk.target(&new, false)) { + (Ok(f), Ok(t)) => (f, t), + (Err(m), _) | (_, Err(m)) => return Ok(error(m)), + }; + let Ok(was) = std::fs::symlink_metadata(&from) else { return Ok(error(NOT_FOUND)) }; + // A folder that holds the settings folder is not moved, also when its name is given in another + // case where case does not matter. + let holds = |f: &Path| std::fs::canonicalize(&from).map_or(true, |kept| crate::file_access::path_inside(f, &kept)); + if was.is_dir() && disk.fenced.as_deref().is_some_and(holds) { + return Ok(error(ACCESS_DENIED)); + } + // A name that differs in case alone may name the same file, which then takes the new name. + if let Ok(there) = std::fs::symlink_metadata(&to) + && !(from.to_string_lossy().eq_ignore_ascii_case(&to.to_string_lossy()) && same_file((&from, &was), (&to, &there))) + { + return Ok(error(NAME_TAKEN)); + } + if std::fs::rename(&from, &to).is_err() { + return Ok(error(WRITE_FAILED)); + } + // Open objects of the file, or of files in the folder, write to the new path. + for file in disk.open.values_mut() { + if let Some(rest) = file.target.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + file.target = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); + } + } + disk.wrote(&to); + Ok(Data::Object(vec![("fs".into(), Data::String(new))])) +} + +/// Do the paths `a` and `b`, with their metadata, name one file? On Unix by device and inode; on +/// Windows by volume and file index, with links followed; elsewhere by the paths with their links +/// followed, which give the name as the file system keeps it. +fn same_file(a: (&Path, &std::fs::Metadata), b: (&Path, &std::fs::Metadata)) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + a.1.dev() == b.1.dev() && a.1.ino() == b.1.ino() + } + #[cfg(windows)] + { + ::same_file::is_same_file(a.0, b.0).unwrap_or(false) + } + #[cfg(not(any(unix, windows)))] + { + matches!((std::fs::canonicalize(a.0), std::fs::canonicalize(b.0)), (Ok(x), Ok(y)) if x == y) + } +} + +/// `create(path)`: the folder, with the folders above it that are missing. +fn create(host: &Host, a: &[Data]) -> Result { + let disk = host.disk.borrow(); + let target = match disk.target(&arg_text(a, 0), true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + // Each missing folder above it that is made on the way must be a place the script may write too. + let outside = target.ancestors().skip(1).take_while(|a| !a.as_os_str().is_empty() && std::fs::symlink_metadata(a).is_err()).any(|a| { + !disk.writes.allows(a) || crate::file_access::check_write(&crate::cmd::findfiles::plain(a.to_path_buf()).to_string_lossy()).is_err() + }); + if outside { + return Ok(error(ACCESS_DENIED)); + } + Ok(done(std::fs::create_dir_all(&target).map_err(|_| WRITE_FAILED))) +} + +/// `setLength(path, length)`: the file cut or padded with zero bytes to `length` bytes. +fn set_length(host: &Host, a: &[Data]) -> Result { + let n = arg_number(a, 1).filter(|n| n.is_finite() && *n >= 0.0).map_or(0, |n| n as u64); + if n > MAX_FILE_BYTES as u64 { + return Ok(error(TOO_LARGE)); + } + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&arg_text(a, 0), true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + let r = match std::fs::metadata(&target) { + Err(_) => Err(NOT_FOUND), + Ok(m) if !m.is_file() => Err(NOT_REGULAR), + Ok(m) => { + // Each open object of the file holds its own bytes, so what each one grows by counts too. + let len = usize::try_from(n).unwrap_or(usize::MAX); + let held = disk + .open + .values() + .filter(|o| o.target.as_deref() == Some(target.as_path())) + .fold(0usize, |sum, o| sum.saturating_add(len.saturating_sub(o.bytes.len()))); + disk.charge_write(usize::try_from(n.saturating_sub(m.len())).unwrap_or(usize::MAX).saturating_add(held))?; + // The file's open objects write what they hold first, and then hold the new length. + let ids: Vec = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(target.as_path())).map(|(id, _)| *id).collect(); + ids.iter() + .try_for_each(|id| disk.flush(*id)) + .and_then(|()| std::fs::OpenOptions::new().write(true).open(&target).and_then(|f| f.set_len(n)).map_err(|_| WRITE_FAILED)) + } + }; + if r.is_ok() { + let len = usize::try_from(n).unwrap_or(usize::MAX); + for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + file.bytes.resize(len, 0); + file.pos = file.pos.min(len); + } + disk.wrote(&target); + } + Ok(done(r)) +} + +/// `setReadonly(path, readonly)`. +fn set_readonly(host: &Host, a: &[Data]) -> Result { + let on = matches!(a.get(1), Some(Data::Bool(true))); + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&arg_text(a, 0), true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + let r = std::fs::metadata(&target).map_err(|_| NOT_FOUND).and_then(|m| { + let mut p = m.permissions(); + // On Unix setting it clears every write bit; clearing it gives back the bits this run + // cleared from the file, or else the owner's write bit. + #[cfg(unix)] + let (back, file) = { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let (mode, file) = (p.mode(), (m.dev(), m.ino())); + // Saved bits are given back only to a file that is still without write bits. + let saved = disk.cleared.get(&file).copied().filter(|_| mode & 0o222 == 0); + let back = if on { mode & 0o222 } else { saved.unwrap_or(0o200) }; + p.set_mode(if on { mode & !0o222 } else { mode | back }); + (back, file) + }; + #[cfg(not(unix))] + p.set_readonly(on); + std::fs::set_permissions(&target, p).map_err(|_| WRITE_FAILED)?; + #[cfg(unix)] + if !on { + disk.cleared.remove(&file); + } else if back != 0 && (disk.cleared.len() < MAX_ENTRIES || disk.cleared.contains_key(&file)) { + disk.cleared.insert(file, back); + } + Ok(()) + }); + if r.is_ok() { + disk.wrote(&target); + } + Ok(done(r)) +} + +/// `pick(kind, prompt, multiple, start)`: the file dialog of `kind` (`open`, `save` or `folder`), +/// which the run waits at in the app; elsewhere `{error}`. +fn pick(host: &Host, a: &[Data]) -> Result { + let kind = match arg_text(a, 0).as_str() { + "open" => PickerKind::Open, + "save" => PickerKind::Save, + _ => PickerKind::Folder, + }; + if cfg!(target_arch = "wasm32") { + return Ok(error(NO_WEB)); + } + let mut disk = host.disk.borrow_mut(); + if !disk.framed { + return Ok(error(NO_PICKER)); + } + if !host.can_wait.get() { + let name = match kind { + PickerKind::Open => "File.openDialog", + PickerKind::Save => "File.saveDialog", + PickerKind::Folder => "Folder.selectDialog", + }; + return Err(HostError::Error(format!( + "{name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code" + ))); + } + let prompt = super::dialogs::cut_to(&arg_text(a, 1), super::dialogs::MAX_MESSAGE_BYTES).to_string(); + let start = Some(arg_text(a, 3)).filter(|s| !s.is_empty() && !too_long(s)); + let can_always = disk.script.is_some() && disk.data_dir.is_some(); + let multiple = kind == PickerKind::Open && matches!(a.get(2), Some(Data::Bool(true))); + let filters = if kind == PickerKind::Folder { Vec::new() } else { dialog_filters(&arg_text(a, 4)) }; + disk.picker = Some(ScriptPicker { kind, prompt, multiple, start, filters, can_always }); + Err(HostError::Wait) +} + +/// The most file types a dialog's filter gives, and the most extensions of one. +const MAX_FILTERS: usize = 32; +/// The most characters of a dialog's filter that are read. +const MAX_FILTER_CHARS: usize = 4096; + +/// The file types of a dialog's `filter`, a string such as `"JavaScript:*.jsx;All files:*.*"`: +/// each `name:pattern` starts a type, a pattern without a name adds to the type before it (the +/// first one starts a type named by the patterns), and patterns are separated by `,` or `;`. A +/// `*.ext` pattern gives the extension `ext`, and `*` and `*.*` give `*`, every file; other patterns +/// are left out, and so is a type left without extensions. Only types that give every file: none +/// (every file). +pub(crate) fn dialog_filters(filter: &str) -> Vec<(String, Vec)> { + let filter: String = filter.chars().take(MAX_FILTER_CHARS).collect(); + let mut out: Vec<(String, Vec)> = Vec::new(); + // Whether the last type was started by a pattern without a name, and is named by its patterns. + let mut unnamed = false; + for piece in filter.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) { + let (name, pattern) = match piece.split_once(':') { + Some((n, p)) => (Some(n.trim()), p.trim()), + None => (None, piece), + }; + let ext = match pattern { + "*" | "*.*" => Some("*".to_string()), + p => p + .strip_prefix("*.") + .filter(|e| !e.is_empty() && e.len() <= 32 && e.chars().all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))) + .map(str::to_string), + }; + match (name, out.last_mut()) { + (Some(n), _) => { + out.push((if n.is_empty() { pattern.to_string() } else { n.to_string() }, Vec::new())); + unnamed = false; + } + (None, None) => { + out.push((pattern.to_string(), Vec::new())); + unnamed = true; + } + (None, Some((name, _))) if unnamed && ext.is_some() && name.len() < 256 => { + name.push(';'); + name.push_str(pattern); + } + (None, Some(_)) => {} + } + if let (Some(ext), Some((_, exts))) = (ext, out.last_mut()) + && exts.len() < MAX_FILTERS + && !exts.contains(&ext) + { + exts.push(ext); + } + } + out.retain(|(_, exts)| !exts.is_empty()); + out.truncate(MAX_FILTERS); + if out.iter().all(|(_, exts)| exts.iter().all(|e| e == "*")) { + return Vec::new(); + } + out } fn read(host: &Host, a: &[Data]) -> Result { @@ -849,15 +2054,24 @@ fn execute(host: &Host, _: &[Data]) -> Result { Ok(error(NO_EXECUTE)) } +/// A name for a new file in the run's temporary folder. fn temp_name(host: &Host, _: &[Data]) -> Result { let mut disk = host.disk.borrow_mut(); disk.temps += 1; let name = format!("vc{:05}.tmp", disk.temps); - Ok(Data::String(temp_folder().join(name).to_string_lossy().into_owned())) + let dir = disk.temp_dir().unwrap_or_else(temp_folder); + Ok(Data::String(dir.join(name).to_string_lossy().into_owned())) } -fn locations_of(host: &Host, _: &[Data]) -> Result { - Ok(locations(&host.disk.borrow().home)) +/// `locations(place)`: the folders [`locations`] gives. The run's temporary folder and the script's +/// data folder are made only when `place` names them. +fn locations_of(host: &Host, a: &[Data]) -> Result { + let place = arg_text(a, 0); + let mut disk = host.disk.borrow_mut(); + let shown = |p: Option| p.map(|p| p.to_string_lossy().into_owned()); + let temp = if place == "temp" { shown(disk.temp_dir()) } else { None }; + let user_data = if place == "userData" { shown(disk.user_data_dir()) } else { None }; + Ok(locations(&disk.home, temp, user_data)) } fn encode_text(_: &Host, a: &[Data]) -> Result { @@ -890,9 +2104,10 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr let value = |s: &str| HostItem::Value(Data::String(s.to_string())); let text = HostItem::Object(vec![ ("notOpen".into(), value(NOT_OPEN)), - ("noWrites".into(), value(NO_WRITES)), - ("noPicker".into(), value(NO_PICKER)), ("badMode".into(), value(BAD_MODE)), + ("noAlias".into(), value(NO_ALIAS)), + ("noHidden".into(), value(NO_HIDDEN)), + ("tooLarge".into(), value(TOO_LARGE)), ]); let system = if WINDOWS { "Windows" @@ -903,6 +2118,7 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr }; let items = vec![ ("text".into(), text), + ("maxWrite".into(), HostItem::Value(Data::Number(MAX_FILE_BYTES as f64))), ("system".into(), value(system)), ("lineFeed".into(), value(if WINDOWS { "Windows" } else { "Unix" })), ("current".into(), unchecked(start_folder)), @@ -927,6 +2143,14 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("list".into(), call(link, list)), ("resolve".into(), call(link, resolve)), ("execute".into(), call(link, execute)), + ("write".into(), call(link, write)), + ("copy".into(), call(link, copy)), + ("remove".into(), call(link, remove)), + ("rename".into(), call(link, rename)), + ("create".into(), call(link, create)), + ("setLength".into(), call(link, set_length)), + ("setReadonly".into(), call(link, set_readonly)), + ("pick".into(), call(link, pick)), ]; realm.define_file_classes(items) } @@ -985,7 +2209,7 @@ mod tests { #[test] fn masks_match_stars_and_question_marks_without_case() { - let matches = |mask: &str, name: &str| Mask::new(mask).matches(name, &mut { usize::MAX }) == Some(true); + let matches = |mask: &str, name: &str| Mask::with_case(mask, true).matches(name, &mut { usize::MAX }) == Some(true); assert!(matches("*.JSX", "a.jsx")); assert!(matches("a?c*", "abcdef")); assert!(!matches("*.txt", "a.jsx")); @@ -995,6 +2219,17 @@ mod tests { assert!(!matches("?", "")); } + #[test] + fn masks_match_case_where_the_file_system_tells_names_apart_by_case() { + let matches = |mask: &str, name: &str| Mask::with_case(mask, false).matches(name, &mut { usize::MAX }) == Some(true); + assert!(!matches("*.JSX", "a.jsx")); + assert!(matches("*.JSX", "a.JSX")); + assert!(matches("A?c*", "Abcdef")); + assert!(!matches("A?c*", "abcdef")); + assert_eq!(MASK_IGNORES_CASE, cfg!(any(windows, target_os = "macos"))); + assert_eq!(Mask::new("*.JSX").matches("a.jsx", &mut { usize::MAX }), Some(MASK_IGNORES_CASE)); + } + #[test] fn masks_stop_when_their_steps_run_out() { let mask = Mask::new(&format!("*{}b", "a".repeat(100))); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 53f6e18f75..8b4a0294d2 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -37,7 +37,8 @@ //! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the //! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`. //! -//! `File` and `Folder` read files inside the script's own folder ([`files`]). +//! `File` and `Folder` read files inside the script's own folder, and write in the run's temporary +//! folder, the script's data folder and what a person allowed it in a file dialog ([`files`]). //! //! A script with `#targetengine name` runs in that named engine, which the session keeps with the //! globals its runs leave, at most [`MAX_ENGINES`] of them with [`ENGINE_HEAP_BYTES`] of heap each @@ -102,6 +103,31 @@ pub const MAX_ARGS_BYTES: usize = 1 << 20; const SLICE_HOST_CALLS: u32 = 256; /// The bytes that may cross between a script and the host in one run. const MAX_BRIDGE_BYTES: u64 = 4 << 30; +/// The most files a run's report names in `written`; past them the report has `writtenMore`. +pub const MAX_WRITTEN: usize = 4096; + +/// The files a run wrote, as its report names them: at most [`MAX_WRITTEN`], each once, in the +/// order they were first written, and whether it wrote more. +#[derive(Default)] +struct Written { + paths: Vec, + seen: std::collections::HashSet, + more: bool, +} + +impl Written { + fn add(&mut self, path: String) { + if self.seen.contains(&path) { + return; + } + if self.paths.len() >= MAX_WRITTEN { + self.more = true; + return; + } + self.seen.insert(path.clone()); + self.paths.push(path); + } +} /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; @@ -255,9 +281,29 @@ struct KeptMap { struct KeptMaps { maps: std::collections::VecDeque, bytes: usize, + /// The SHA-256 of each source the engine's runs compiled (their scripts and what they + /// evaluated), at most [`MAX_ENGINE_CODE`], and whether there were more: a later run's kept file + /// grants are in force only for code they were kept for ([`files::Disk`]). + code: std::collections::BTreeSet, + code_full: bool, } +/// The most sources whose SHA-256 a named engine keeps. +pub const MAX_ENGINE_CODE: usize = 1024; + impl KeptMaps { + /// Adds the sources `code` (and whether a run had more than it counted) to the engine's code. + fn keep_code(&mut self, (code, more): (Vec, bool)) { + self.code_full |= more; + for hash in code { + if self.code.len() >= MAX_ENGINE_CODE && !self.code.contains(&hash) { + self.code_full = true; + } else { + self.code.insert(hash); + } + } + } + fn keep(&mut self, tag: u32, map: include::SourceMap, script: Option>) { let bytes = map.bytes() + script.as_ref().map_or(0, |s| s.len()); let limit = kept_map_bytes(); @@ -696,7 +742,7 @@ struct Host { waiting: Cell, log: RefCell>, log_bytes: Cell, - written: RefCell>, + written: RefCell, /// The run's number in its session, and the script's name, which its console lines carry. run: u64, name: Arc, @@ -813,6 +859,7 @@ impl Host { return; } let mut kept = kept.borrow_mut(); + kept.keep_code(self.disk.borrow().code()); kept.keep(tag, std::mem::take(&mut *self.script_map.borrow_mut()), Some(self.report_name.clone())); for (n, map) in std::mem::take(&mut *self.eval_maps.borrow_mut()).into_iter().enumerate() { match u32::try_from(n + 1).ok().and_then(|n| tag.checked_add(n)).filter(|t| *t != vectorcraft_js::UNKNOWN_SOURCE) { @@ -884,6 +931,35 @@ impl Host { Some(left) } + /// Adds `paths`, files the script's `File` and `Folder` objects wrote, to the report's `written`. + fn note_written(&self, paths: Vec) { + let mut written = self.written.borrow_mut(); + for path in paths { + written.add(path); + } + } + + /// Adds `writtenMore: true` to `report` when the run wrote more files than its `written` names. + fn more_written(&self, report: &mut Value) { + if self.written.borrow().more + && let Some(o) = report.as_object_mut() + { + o.insert("writtenMore".into(), json!(true)); + } + } + + /// Writes the files the script left open and adds every file written to the report's `written`. + /// → the files it could not write. + fn flush_files(&self) -> Vec { + let mut disk = self.disk.borrow_mut(); + let failed = disk.flush_all(); + disk.record_code(); + let paths = disk.take_written(); + drop(disk); + self.note_written(paths); + failed + } + fn over(&self, limit: &str) -> HostError { HostError::Abort(limit.to_string()) } @@ -1100,13 +1176,13 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); - let r = s.execute(id, params); + // The command reads and writes only where the script's own files may, and the open documents' files. + let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); + let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); // A file a command wrote before it failed is on disk all the same. let mut written = host.written.borrow_mut(); for path in crate::file_access::finish_recording_writes(r.is_ok()) { - if !written.contains(&path) { - written.push(path); - } + written.add(path); } drop(written); match r { @@ -1664,6 +1740,32 @@ impl Session { with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) } + /// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' + /// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no + /// longer waits. + pub fn script_picker(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.disk.borrow().picker.clone())).flatten() + } + + /// Gives the file dialog the running script waits at its answer: the paths the person picked + /// and allowed, or a denial. The next [`Session::script_pump`] goes on from the call. → false + /// when no file dialog waits. + pub fn script_pick(&mut self, answer: files::PickAnswer) -> bool { + let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false }; + with_job(k, |j| { + let Some(data) = j.host.disk.borrow_mut().answer(answer) else { return false }; + j.host.note_written(j.host.disk.borrow_mut().take_written()); + if let Err(e) = j.realm.answer(data) { + j.host.disk.borrow_mut().failed = Some(e); + } + true + }) + .unwrap_or(false) + } + /// The name of the running script. pub fn script_name(&self) -> Option { self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone())) @@ -1790,7 +1892,17 @@ impl Session { realm.set_limits(limits); realm } - None => Realm::with_options(options, limits), + None => { + let mut realm = Realm::with_options(options, limits); + // Code the run evaluates withdraws the kept file grants not kept for it, before it runs. + let l = link.clone(); + realm.observe_code(move |units| { + if let Ok(h) = current(&l) { + h.disk.borrow_mut().saw_code(units); + } + }); + realm + } }; realm.share_interrupt(&self.script_stop); realm.set_data_limits(DataLimits::default()); @@ -1810,7 +1922,7 @@ impl Session { waiting: Cell::new(false), log: RefCell::new(Vec::new()), log_bytes: Cell::new(0), - written: RefCell::new(Vec::new()), + written: RefCell::new(Written::default()), run: self.script_runs, name: console::line_name(&name), console: RefCell::default(), @@ -1819,7 +1931,20 @@ impl Session { commands: RefCell::default(), run_nanos: Cell::new(0), dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers), - disk: RefCell::new(files::Disk::new(files.scope())), + disk: RefCell::new(files::Disk::new( + files.scope(), + files::Setup { + framed: self.script_frames, + script: request.file.clone(), + // The text with its included files, so a changed included file asks again. + source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()), + data_dir: self.script_data_dir.clone(), + engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| { + let m = m.borrow(); + (m.code.iter().cloned().collect(), m.code_full) + }), + }, + )), files: RefCell::new(files), script_map: RefCell::default(), eval_maps: RefCell::default(), @@ -1902,14 +2027,16 @@ impl Session { self.script_gone(key, console::Ending::Internal); return Some(Err(EngineError::Other(JOB_GONE.to_string()))); }; - if let Some(e) = job.host.dialogs.take_failure() { + let picker_failed = job.host.disk.borrow_mut().failed.take(); + if let Some(e) = job.host.dialogs.take_failure().or(picker_failed) { return Some(self.script_failed(job, &e)); } // A canceled request ends a sleep or a wait at this pump. if vectorcraft_doc::cancel::check().is_err() { self.script_stop.set(); } - if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() { + let picking = job.host.disk.borrow().picker.is_some(); + if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting() || picking) && !self.script_stop.is_set() { JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); self.script_key = Some(key); return None; @@ -1949,6 +2076,9 @@ impl Session { fn script_failed(&mut self, job: Job, e: &RunError) -> Result { job.host.dialogs.stopped(); + job.host.disk.borrow_mut().picker = None; + // The run fails already; a file it could not write is left out of `written`. + let _ = job.host.flush_files(); let fuel_left = job.realm.fuel_left(); let (e, file) = located(&job.host, &job.realm, e); let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); @@ -1966,6 +2096,12 @@ impl Session { /// Makes the working copy the session's state: one undo step for each document whose art /// changed, nothing for the others. fn script_commit(&mut self, mut job: Job) -> Result { + let unwritten = job.host.flush_files(); + if !unwritten.is_empty() { + let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", ")); + let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 }; + return self.script_failed(job, &e); + } // The working copy goes into the session; `job.world` holds the state before the run. job.world.swap(self); self.prefs = merged_prefs(&job.world.start_prefs, &self.prefs, &job.world.choices.prefs); @@ -2029,11 +2165,12 @@ impl Session { "ok": true, "name": job.name, "changed": changed_names, - "written": *host.written.borrow(), + "written": host.written.borrow().paths, "log": *host.log.borrow(), "fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(), "hostCalls": host.calls.get(), }); + host.more_written(&mut report); close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); @@ -2060,6 +2197,7 @@ impl Session { const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; const INVALID_RESULT: &str = "the script left a document that cannot be kept"; +const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written"; const JOB_GONE: &str = "the script's run is no longer available"; const HISTORY_LOST: &str = "a failed command changed undo steps that could not be put back, so the script was stopped"; // Text a script reads from the errors it catches, or that ends its run with its name and place. @@ -2088,12 +2226,13 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue "name": name, "line": e.line, "column": e.column, - "written": *host.written.borrow(), + "written": host.written.borrow().paths, "log": *host.log.borrow(), "fuelLeft": fuel_left, "fuelUsed": fuel_used, "hostCalls": host.calls.get(), }); + host.more_written(&mut report); if let (Some(file), Some(o)) = (file, report.as_object_mut()) { o.insert("file".into(), json!(file)); } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 3e9ae56423..865d822652 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -90,6 +90,7 @@ impl Session { plugin_dir: None, scripts_dir: None, new_doc_profile_dir: None, + script_data_dir: None, plugin_output: None, plugin_install_approval: None, plugin_grants_from_requests: false, diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e056ea2f7c..0d09bd2796 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1,6 +1,7 @@ //! `File` and `Folder` in a script: their classes and names, reading inside the script's own folder, -//! the paths refused before anything is looked up, the read limits, and the parts that write, which -//! are not available. +//! the paths refused before anything is looked up, the read limits, writing in the run's temporary +//! folder, the script's data folder and what a person allowed in a file dialog, and the grants kept +//! for a script. use std::path::{Path, PathBuf}; @@ -267,10 +268,12 @@ fn script_file_oversize_refused_before_read() { #[test] fn script_files_read_at_most_32_mib_in_a_run() { let base = folder("total"); - write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + for i in 0..5 { + write(&base.join(format!("main/seven{i}.bin")), &vec![b'a'; 7 << 20]); + } let mut s = Session::new(); let main = base.join("main/main.jsx"); - write(&main, b"var f = new File('seven.bin'); for (var i = 0; i < 5; i++) { f.open('r'); vc.log(i); }"); + write(&main, b"for (var i = 0; i < 5; i++) { new File('seven' + i + '.bin').open('r'); vc.log(i); }"); let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})); assert!(e.is_err(), "the fifth open passes 32 MiB"); let report = s.script_report().unwrap(); @@ -279,6 +282,23 @@ fn script_files_read_at_most_32_mib_in_a_run() { let _ = std::fs::remove_dir_all(base); } +/// A file opened again once its objects closed counts only once toward the 32 MiB a run reads, and +/// a file open in two objects at once counts for each. +#[test] +fn script_file_opened_again_counts_once_toward_the_run_limit() { + let base = folder("reopencount"); + write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write(&main, b"var f = new File('seven.bin'); for (var i = 0; i < 8; i++) { f.open('r'); f.close(); } vc.log('again');"); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["again"])); + write(&main, b"for (var i = 0; i < 5; i++) { new File('seven.bin').open('r'); vc.log(i); }"); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "five objects hold five copies"); + assert_eq!(s.script_report().unwrap()["log"], json!([0, 1, 2, 3])); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_files_have_at_most_256_open() { let base = folder("open"); @@ -311,7 +331,9 @@ fn script_folder_getfiles_stays_inside_scope() { try { d.getFiles(function () { throw new Error('stop'); }); } catch (e) { vc.log(e.message); }\n\ vc.log([new Folder('nope').getFiles(), d.getFiles('*.jsx')[0] instanceof File]);", ); - assert_eq!(log, json!([["C.JSX", "a.jsx", "main.jsx"], ["sub"], [["b.txt"], 5, null, DENIED], "stop", [null, true]])); + // Where case does not matter to the file system, the mask matches without regard to case. + let jsx = if cfg!(any(windows, target_os = "macos")) { json!(["C.JSX", "a.jsx", "main.jsx"]) } else { json!(["a.jsx", "main.jsx"]) }; + assert_eq!(log, json!([jsx, ["sub"], [["b.txt"], 5, null, DENIED], "stop", [null, true]])); let many = base.join("main/many"); for i in 0..=crate::script::files::MAX_ENTRIES { write(&many.join(format!("{i:04}.txt")), b""); @@ -393,23 +415,28 @@ fn script_file_encoding_binary_ascii() { let _ = std::fs::remove_dir_all(base); } +/// A script's own folder is only read: writing there, and anywhere it was not given, is refused, +/// and with nobody to ask its file dialogs give `null`. Aliases and `execute` are not available. #[test] -fn script_file_writes_dialogs_and_execute_are_not_available() { +fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() { let base = folder("writes"); write(&base.join("main/keep.txt"), b"keep"); + let outside = base.join("outside.txt").to_string_lossy().into_owned(); let r = run( &base, - "var f = new File('keep.txt'); var n = new File('new.txt');\n\ - var out = [n.open('w'), n.error, f.open('a'), f.open('e'), f.open('x'), f.error, f.write('x'), f.remove(), f.copy('c.txt'), f.rename('r.txt')];\n\ - out.push(new Folder('made').create(), f.openDlg(), f.error, File.openDialog(), Folder.selectDialog(), f.execute(), f.error);\n\ - f.hidden = true; out.push(f.error, f.hidden); f.error = ''; out.push(f.error);\n\ - vc.log(out);", + &format!( + "var f = new File('keep.txt'); var n = new File('new.txt'); var o = new File({outside:?});\n\ + var out = [n.open('w'), n.error, f.open('a'), f.open('e'), f.open('x'), f.error, f.remove(), f.copy('c.txt'), f.rename('r.txt'), o.open('w')];\n\ + out.push(new Folder('made').create(), f.openDlg(), f.error, File.openDialog(), Folder.selectDialog(), f.execute(), f.error);\n\ + f.hidden = true; out.push(f.error, f.hidden, f.createAlias('l'), f.error); f.error = ''; out.push(f.error);\n\ + vc.log(out);" + ), ); assert_eq!( r["log"], json!([[ false, - "Script file writing is not available", + DENIED, false, false, false, @@ -420,20 +447,1222 @@ fn script_file_writes_dialogs_and_execute_are_not_available() { false, false, null, - "Script file dialogs are not available", + "Script file dialogs need a person to answer them", null, null, false, "Script files cannot be opened in another application", - "Script file writing is not available", + "Script file hidden setting cannot be changed", false, + false, + "Script files cannot make aliases", "" ]]) ); assert_eq!(r["hostCallCounts"]["fileExecutes"], 1); - assert!(r["hostCallCounts"]["fileCalls"].as_u64().unwrap() > 0); + assert_eq!(r["written"], json!([])); assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep"); assert!(!base.join("main/new.txt").exists() && !base.join("main/made").exists() && !base.join("main/c.txt").exists()); + assert!(!Path::new(&outside).exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn with_data(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the text `text` in `s`. +fn run_in(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +/// `Folder.userData` is the script's own folder, kept between runs, and `Folder.temp` the run's, +/// deleted when it ends. `write` joins its values, `writeln` adds the `lineFeed`'s line end, and a +/// byte order mark is written as the script writes it. +#[test] +fn script_files_write_in_the_temporary_and_data_folders() { + let base = folder("userdata"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var out = [], u = new File(Folder.userData.fsName + '/notes.txt');\n\ + out.push(u.open('w'), u.write('a', 1, true), u.writeln('b'), u.close());\n\ + u.lineFeed = 'Windows'; out.push(u.open('a'), u.writeln('c'), u.close());\n\ + u.open('r'); out.push(u.read()); u.close();\n\ + var t = new File(Folder.temp.fsName + '/t.txt'); out.push(t.open('w'), t.write('\\uFEFFx'), t.close(), t.length);\n\ + var m = new File(); out.push(m.open('w'), m.parent.fsName === Folder.temp.fsName);\n\ + vc.log(out); vc.log(u.fsName); vc.log(Folder.temp.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([true, true, true, true, true, true, true, "a1trueb\nc\r\n", true, true, true, 4, true, true])); + let notes = PathBuf::from(r["log"][1].as_str().unwrap()); + let temp = PathBuf::from(r["log"][2].as_str().unwrap()); + assert_eq!(std::fs::read(¬es).unwrap(), b"a1trueb\nc\r\n"); + assert!(notes.starts_with(std::fs::canonicalize(base.join("settings/Script Data")).unwrap()), "{notes:?}"); + assert!(!temp.exists(), "the run's temporary folder is deleted when it ends"); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(written.contains(¬es.to_string_lossy().as_ref()), "{written:?}"); + let again = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/notes.txt'); u.open('r'); vc.log(u.read());").unwrap(); + assert_eq!(again["log"], json!(["a1trueb\nc\r\n"]), "a script's data folder is kept between runs"); + let _ = std::fs::remove_dir_all(base); +} + +/// The open modes, the encodings that cannot hold a character, `copy` over a file, `remove` of a +/// folder only when it is empty, `rename` refusing a name in use, `create`, and setting `length` and +/// `readonly`. +#[test] +fn script_file_modes_encodings_and_changes() { + let base = folder("changes"); + let r = run( + &base, + "var d = Folder.temp.fsName, out = [];\n\ + var e = new File(d + '/missing.txt'); out.push(e.open('e'), e.error);\n\ + var a = new File(d + '/a.txt'); a.encoding = 'ASCII'; out.push(a.open('w'), a.write('caf\\u00e9'), a.error, a.write('cafe'), a.close(), a.length);\n\ + var b = new File(d + '/b.bin'); b.encoding = 'BINARY'; b.open('w'); b.write('\\u0141B'); b.close();\n\ + b.encoding = 'BINARY'; b.open('r'); out.push(b.read()); b.close();\n\ + out.push(a.copy(d + '/b.bin'), new File(d + '/b.bin').length);\n\ + var f = new Folder(d + '/x/y'); out.push(f.create(), f.exists);\n\ + var x = new Folder(d + '/x'); out.push(x.remove(), x.error, f.remove(), f.exists);\n\ + out.push(a.rename('b.bin'), a.error, a.rename('c.txt'), a.name, a.exists, new File(d + '/a.txt').exists);\n\ + a.length = 2; out.push(a.length); a.length = 6; out.push(a.length);\n\ + a.readonly = true; out.push(a.readonly); a.readonly = false; out.push(a.readonly);\n\ + out.push(a.remove(), a.exists);\n\ + vc.log(out);", + ); + assert_eq!( + r["log"], + json!([[ + false, + "Script file does not exist", + true, + false, + "Script file cannot encode the text", + true, + true, + 4, + "AB", + true, + 4, + true, + true, + false, + "Script folder is not empty", + true, + false, + false, + "Script file name is already in use", + true, + "c.txt", + true, + false, + 2, + 6, + true, + false, + true, + false + ]]) + ); + let _ = std::fs::remove_dir_all(base); +} + +/// Setting `length` while the file is open changes what the open file holds, so closing it keeps +/// the new length. +#[test] +fn script_file_length_changes_reach_an_open_file() { + let base = folder("openlength"); + let r = run( + &base, + "var o = new File(Folder.temp.fsName + '/l.txt'); o.open('w'); o.write('abc');\n\ + new File(o.fsName).length = 1; o.write('d'); o.close();\n\ + o.open('r'); vc.log([o.read(), o.length]); o.close();", + ); + assert_eq!(r["log"], json!([["ad", 2]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file is kept as it was when `open('w')` is given an encoding that is not one and when it is +/// copied onto itself, and the changes an open file holds stay to be written when writing them fails. +#[test] +fn script_file_writes_keep_what_they_cannot_change() { + let base = folder("keeps"); + let r = run( + &base, + "var d = Folder.temp.fsName, out = [];\n\ + var k = new File(d + '/k.txt'); k.open('w'); k.write('keep'); k.close();\n\ + k.encoding = 'nope'; out.push(k.open('w'), k.error);\n\ + k.encoding = 'UTF-8'; k.open('r'); out.push(k.read()); k.close();\n\ + out.push(k.copy(k.fsName), k.length);\n\ + var w = new File(d + '/w.txt'); w.open('w'); w.write('abc'); new File(w.fsName).readonly = true;\n\ + var q = new File(w.fsName); q.length = 1; out.push(q.error);\n\ + new File(w.fsName).readonly = false; out.push(w.close()); w.open('r'); out.push(w.read()); w.close();\n\ + vc.log(out);", + ); + assert_eq!(r["log"], json!([[false, "Script file cannot be decoded", "keep", true, 4, "Script file could not be written", true, "abc"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file whose `close` could not write it stays to be written when the run ends. +#[test] +fn script_file_close_that_cannot_write_keeps_the_changes() { + let base = folder("closefail"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/c.txt'); u.open('w'); u.write('kept');\n\ + new File(u.fsName).readonly = true; var out = [u.close(), u.error]; new File(u.fsName).readonly = false;\n\ + vc.log(out); vc.log(u.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([false, "Script file could not be written"])); + assert_eq!(std::fs::read(r["log"][1].as_str().unwrap()).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// `changePath` on an object whose changes could not be written gives false with `error` set, and +/// the object keeps its path. +#[test] +fn script_file_change_path_that_cannot_write_keeps_the_path() { + let base = folder("changepathfail"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/p.txt'); u.open('w'); u.write('kept'); var was = u.fsName;\n\ + new File(was).readonly = true; var out = [u.changePath(Folder.userData.fsName + '/q.txt'), u.error, u.fsName == was];\n\ + new File(was).readonly = false; vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([false, "Script file could not be written", true])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file opened again after a `close` that could not write it keeps what was written after it was +/// opened again, and the earlier changes do not replace it when the run ends. +#[test] +fn script_file_opened_again_after_a_failed_close_keeps_the_later_text() { + let base = folder("reopen"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/r.txt'); u.open('w'); u.write('old');\n\ + new File(u.fsName).readonly = true; var out = [u.close()]; new File(u.fsName).readonly = false;\n\ + out.push(u.open('w'), u.write('new'), u.close()); vc.log(out); vc.log(u.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([false, true, true, true])); + assert_eq!(std::fs::read(r["log"][1].as_str().unwrap()).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(base); +} + +/// A write that would pass the run's 32 MiB of writing ends the run, and its text is not written. +#[test] +fn script_file_write_past_the_run_limit_is_not_written() { + let base = folder("runlimit"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var t = 'x'; while (t.length < 4194304) t += t;\n\ + var f = new File(Folder.userData.fsName + '/f.bin'); f.encoding = 'UTF-16';\n\ + for (var k = 0; k < 4; k++) { f.open('w'); f.write(t); f.close(); }\n\ + var g = new File(Folder.userData.fsName + '/g.txt'); vc.log(g.fsName); g.open('w'); g.write('over');", + ); + assert!(r.is_err()); + let report = s.script_report().unwrap(); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + assert_eq!(std::fs::read(report["log"][0].as_str().unwrap()).unwrap(), b"", "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `remove` and `rename` of a file that is open elsewhere: a removed file is not written again when +/// the run ends, a renamed one is written under its new name, and an object whose own changes could +/// not be written does not remove or rename its file. +#[test] +fn script_file_remove_and_rename_of_an_open_file() { + let base = folder("openmove"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, out = [];\n\ + var a = new File(d + '/a.txt'); a.open('w'); a.write('a'); out.push(new File(a.fsName).remove());\n\ + var b = new File(d + '/b.txt'); b.open('w'); b.write('b'); var c = new File(b.fsName); out.push(c.rename('c.txt'), b.close());\n\ + var e = new File(d + '/e.txt'); e.open('w'); e.write('e'); new File(e.fsName).readonly = true;\n\ + out.push(e.remove(), e.error, e.exists); new File(e.fsName).readonly = false;\n\ + vc.log(out); vc.log(d);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([true, true, true, false, "Script file could not be written", true])); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + assert!(!d.join("a.txt").exists() && !d.join("b.txt").exists()); + assert_eq!(std::fs::read(d.join("c.txt")).unwrap(), b"b"); + assert_eq!(std::fs::read(d.join("e.txt")).unwrap(), b"e", "the run's end writes the changes the failed close kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` of a file that is open copies what the open file holds, and an object that has the target +/// open then holds the copy. +#[test] +fn script_file_copy_of_an_open_file_has_its_changes() { + let base = folder("copyopen"); + let r = run( + &base, + "var d = Folder.temp.fsName, f = new File(d + '/f.txt'); f.open('w'); f.write('new');\n\ + var out = [f.copy(d + '/g.txt')]; var g = new File(d + '/g.txt'); g.open('r'); out.push(g.read()); g.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, "new"]])); + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('copied'); s.close();\n\ + var t = new File(d + '/t.txt'); t.open('w'); t.write('old'); var out = [s.copy(t.fsName), t.close()];\n\ + t.open('r'); out.push(t.read()); t.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, true, "copied"]]), "an open target holds the copy"); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant that would make the grants file larger than it may be read is not kept, and the grants +/// file keeps the grants it had. +#[test] +fn script_file_grants_file_stays_within_its_size_limit() { + let base = folder("bigstore"); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + let store = base.join("settings/Script Grants.json"); + let grants = + |path: String| json!({"version": 1, "grants": [{"script": "x", "sha256": "y", "code": [], "path": path, "write": false, "folder": false}]}); + let empty = serde_json::to_vec_pretty(&grants(String::new())).unwrap().len(); + let full = serde_json::to_vec_pretty(&grants("p".repeat((4 << 20) - 64 - empty))).unwrap(); + write(&store, &full); + let mut s = with_data(&base); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + start_framed(&mut s, &base, "var f = File.saveDialog('p'); vc.log(f === null ? null : f.fsName);"); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + let _ = pump_to_picker(&mut s).unwrap(); + assert_eq!(std::fs::read(&store).unwrap(), full, "the grants file is left as it was"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` of a file over 8 MiB is refused, as opening one is. +#[test] +fn script_file_copy_is_held_to_the_file_limit() { + let base = folder("bigcopy"); + write(&base.join("main/big.bin"), &vec![0u8; 8 * 1024 * 1024 + 1]); + let r = run(&base, "var b = new File('big.bin'); vc.log([b.copy(Folder.temp.fsName + '/b.bin'), b.error]);"); + assert_eq!(r["log"], json!([[false, "Script file exceeds 8 MiB"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// The run's 32 MiB of writes counts what setting `length` adds to each object the file is open in, +/// as each holds its own bytes. +#[test] +fn script_file_length_counts_the_growth_of_every_open_object() { + let base = folder("lengthheld"); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write( + &main, + b"var p = Folder.temp.fsName + '/l.bin'; var w = new File(p); w.open('w'); w.close();\n\ + var all = []; for (var i = 0; i < 5; i++) { var f = new File(p); f.open('e'); all.push(f); }\n\ + vc.log('open'); new File(p).length = 7 * 1024 * 1024; vc.log('grown');", + ); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "five objects grow by 7 MiB each"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!(["open"])); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` onto another name of the same file, a hard link, keeps the file's bytes, and what the +/// source's open object holds is in the file when `copy` returns. +#[test] +fn script_file_copy_onto_a_hard_link_of_itself_keeps_the_file() { + let base = folder("copylink"); + let picked = base.join("picked"); + write(&picked.join("a.txt"), b"keep"); + std::fs::hard_link(picked.join("a.txt"), picked.join("b.txt")).unwrap(); + let mut s = Session::new(); + start_framed( + &mut s, + &base, + "var p = Folder.selectDialog('p'); var a = new File(p.fsName + '/a.txt'), b = new File(p.fsName + '/b.txt');\n\ + a.open('w'); a.write('new'); var out = [a.copy(b.fsName)]; b.open('r'); out.push(b.read()); b.close(); a.close(); vc.log(out);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, "new"]])); + assert_eq!(std::fs::read(picked.join("a.txt")).unwrap(), b"new"); + assert_eq!(std::fs::read(picked.join("b.txt")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(base); +} + +/// The run's 32 MiB of writes counts the copy each open object of `copy`'s target takes. +#[test] +fn script_file_copy_counts_the_bytes_each_open_object_of_the_target_takes() { + let base = folder("copyheld"); + write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write( + &main, + b"var t = Folder.temp.fsName + '/t.bin'; var w = new File(t); w.open('w'); w.close();\n\ + var all = []; for (var i = 0; i < 5; i++) { var f = new File(t); f.open('e'); all.push(f); }\n\ + vc.log('open'); vc.log(new File('seven.bin').copy(t));", + ); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "five objects take 7 MiB each"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!(["open"])); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `write` joins its values only for an open file, and stops joining once the text is longer than +/// any file a script writes: the values after that are not turned into text. +#[test] +fn script_file_write_stops_joining_past_the_file_limit() { + let base = folder("writejoin"); + let r = run( + &base, + "var seen = 0, late = { toString: function () { seen++; return 'x'; } };\n\ + var f = new File(Folder.temp.fsName + '/j.txt'); var closed = [f.write(late), seen];\n\ + var s = new Array((1 << 20) + 1).join('x'), a = []; for (var k = 0; k < 17; k++) a.push(s); a.push(late);\n\ + f.open('w'); var big = f.write.apply(f, a); vc.log([closed, big, f.error, seen, f.write('ok'), f.close(), f.length]);", + ); + assert_eq!(r["log"], json!([[[false, 0], false, "Script file exceeds 8 MiB", 0, true, true, 2]])); + let _ = std::fs::remove_dir_all(base); +} + +/// The report names at most 4,096 files a run wrote, each once, and says when it wrote more. +#[test] +fn script_reports_name_at_most_4096_written_files() { + let base = folder("manywritten"); + let r = run( + &base, + "var d = Folder.temp.fsName; for (var k = 0; k < 4100; k++) { var f = new File(d + '/' + k + '.txt'); f.open('w'); f.close(); f.open('w'); f.close(); }", + ); + let written = r["written"].as_array().unwrap(); + assert_eq!(written.len(), crate::script::MAX_WRITTEN, "{}", written.len()); + assert_eq!(written.iter().filter_map(Value::as_str).collect::>().len(), written.len()); + assert_eq!(r["writtenMore"], true); + let few = run(&base, "var f = new File(Folder.temp.fsName + '/one.txt'); f.open('w'); f.close();"); + assert_eq!((few["written"].as_array().map(Vec::len), few.get("writtenMore")), (Some(1), None)); + let _ = std::fs::remove_dir_all(base); +} + +/// A kept grant stays on the real path it was kept for: when a link to another folder takes the +/// granted folder's place, the next run is not granted the folder the link leads to. +#[cfg(unix)] +#[test] +fn script_file_grants_do_not_follow_a_link_put_in_the_granted_place() { + let base = folder("grantlink"); + let granted = base.join("picked/granted"); + write(&granted.join("s.txt"), b"mine"); + write(&base.join("away/s.txt"), b"secret"); + let text = format!( + "var t = new File({:?}), u = new File({:?});\n\ + if (t.open('r')) vc.log(['kept', t.read()]); else if (u.open('r')) vc.log(['away', u.read()]);\n\ + else vc.log(Folder.selectDialog('p') ? 'asked' : null);", + granted.join("s.txt").to_string_lossy(), + base.join("away/s.txt").to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![granted.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", "mine"]])); + std::fs::rename(&granted, base.join("picked/moved")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), &granted).unwrap(); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "the run asks again instead of reading where the link leads"); + s.script_pick(crate::script::files::PickAnswer::Deny); + let _ = pump_to_picker(&mut s); + let _ = std::fs::remove_dir_all(base); +} + +/// A folder granted in a file dialog cannot have a folder in it renamed when that folder holds the +/// settings folder. +#[test] +fn script_file_rename_does_not_move_the_settings_folder() { + let base = folder("moveup"); + let mut s = Session::new(); + s.attach_script_data(base.join("cfg/settings/Script Data")); + std::fs::create_dir_all(base.join("cfg/settings")).unwrap(); + start_framed(&mut s, &base, "var p = Folder.selectDialog('p'); var c = new Folder(p.fsName + '/cfg'); vc.log([c.rename('cfg2'), c.error]);"); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![base.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED]])); + assert!(base.join("cfg/settings").is_dir()); + let _ = std::fs::remove_dir_all(base); +} + +/// Where case does not matter, a folder named in another case is still the folder that holds the +/// settings folder, or the settings folder itself: it is not renamed or removed. +#[cfg(any(windows, target_os = "macos"))] +#[test] +fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() { + let base = folder("moveupcase"); + let mut s = Session::new(); + s.attach_script_data(base.join("cfg/settings/Script Data")); + std::fs::create_dir_all(base.join("cfg/settings")).unwrap(); + start_framed( + &mut s, + &base, + "var p = Folder.selectDialog('p'); var c = new Folder(p.fsName + '/CFG'), d = new Folder(p.fsName + '/cfg/SETTINGS');\n\ + vc.log([c.rename('cfg2'), c.error, d.rename('s2'), d.error, d.remove(), d.error]);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![base.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED, false, DENIED, false, DENIED]])); + assert!(base.join("cfg/settings").is_dir()); + let _ = std::fs::remove_dir_all(base); +} + +/// Where case matters, a rename to a name that differs in case alone does not replace the other file. +#[cfg(target_os = "linux")] +#[test] +fn script_file_rename_keeps_a_file_that_differs_in_case() { + let base = folder("casename"); + let r = run( + &base, + "var d = Folder.temp.fsName, a = new File(d + '/a.txt'), b = new File(d + '/A.txt');\n\ + a.open('w'); a.write('a'); a.close(); b.open('w'); b.write('B'); b.close();\n\ + var out = [a.rename('A.txt'), a.error]; b.open('r'); out.push(b.read()); b.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[false, "Script file name is already in use", "B"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A script's data folder that is a link is not used: the folder it leads to is not granted. +#[cfg(unix)] +#[test] +fn script_data_folder_that_is_a_link_is_not_granted() { + let base = folder("datalink"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap(); + let data = PathBuf::from(r["log"][0].as_str().unwrap()); + std::fs::remove_dir(&data).unwrap(); + std::fs::create_dir_all(base.join("away")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), &data).unwrap(); + let text = format!( + "var d = Folder.userData; var w = new File({:?}); vc.log([d === null, w.open('w'), w.error]);", + base.join("away/x.txt").to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!([[true, false, DENIED]])); + assert!(!base.join("away/x.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A data folder that is a link is not used: no script's `Folder.userData` is made in the folder it +/// leads to. +#[cfg(unix)] +#[test] +fn script_data_folders_in_a_data_folder_that_is_a_link_are_not_granted() { + let base = folder("datadirlink"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap(); + let key = PathBuf::from(r["log"][0].as_str().unwrap()).file_name().unwrap().to_owned(); + let data = base.join("settings/Script Data"); + std::fs::remove_dir_all(&data).unwrap(); + std::fs::create_dir_all(base.join("away")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), &data).unwrap(); + let text = format!( + "var d = Folder.userData; var w = new File({:?}); vc.log([d === null, w.open('w'), w.error]);", + base.join("away").join(&key).join("x.txt").to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!([[true, false, DENIED]])); + assert!(!base.join("away").join(&key).exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// An open file whose folder was replaced by a link before it was written is not written through +/// the link. +#[cfg(unix)] +#[test] +fn script_files_are_not_written_through_a_link_put_in_place_of_their_folder() { + let base = folder("parentlink"); + let mut s = with_data(&base); + std::fs::create_dir_all(base.join("away")).unwrap(); + // The run opens and changes `sub/f.txt` in its data folder and waits on a file dialog, while + // another program puts a link to `away` in place of `sub`. + start_framed( + &mut s, + &base, + "var d = Folder.userData.fsName, f = new File(d + '/sub/f.txt');\n\ + var before = [new Folder(d + '/sub').create(), f.open('w'), f.write('x')];\n\ + File.openDialog('p'); vc.log([before, f.close(), f.error]);", + ); + assert!(pump_to_picker(&mut s).is_none()); + let data = std::fs::read_dir(base.join("settings/Script Data")).unwrap().next().unwrap().unwrap().path(); + std::fs::rename(data.join("sub"), data.join("old")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), data.join("sub")).unwrap(); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + // The file stays unwritten, so the run's end fails the run as for any file it could not write. + let e = pump_to_picker(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("left open files that could not be written"), "{e}"); + assert!(!base.join("away/f.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix, `readonly` clears the write bits and clearing it gives the file the bits it had. +#[cfg(unix)] +#[test] +fn script_file_readonly_keeps_the_other_permissions() { + use std::os::unix::fs::PermissionsExt; + let base = folder("modes"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/m.txt'); u.open('w'); u.close(); vc.log(u.fsName);").unwrap(); + let path = PathBuf::from(r["log"][0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap(); + let text = format!( + "Folder.userData; var u = new File({:?}); u.readonly = true; var a = u.readonly; u.readonly = false; vc.log([a, u.readonly]);", + path.to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!([[true, false]])); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o640); + let _ = std::fs::remove_dir_all(base); +} + +/// Clearing `readonly` gives back every write bit that setting it cleared in the run, also after a +/// rename, and only the owner's write bit for a file that was read-only before the run. +#[cfg(unix)] +#[test] +fn script_file_readonly_gives_back_the_write_bits_it_cleared() { + use std::os::unix::fs::PermissionsExt; + let base = folder("modesback"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/m.txt'); u.open('w'); u.close(); vc.log(u.fsName);").unwrap(); + let path = PathBuf::from(r["log"][0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o662)).unwrap(); + let toggle = format!( + "Folder.userData; var u = new File({:?}); u.readonly = true; var a = u.readonly; var b = u.rename('n.txt');\n\ + u.readonly = false; vc.log([a, b, u.readonly]); u.rename('m.txt');", + path.to_string_lossy() + ); + let r = run_in(&mut s, &base, &toggle).unwrap(); + assert_eq!(r["log"], json!([[true, true, false]])); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o662); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444)).unwrap(); + let clear = format!("Folder.userData; var u = new File({:?}); u.readonly = false;", path.to_string_lossy()); + run_in(&mut s, &base, &clear).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644); + let _ = std::fs::remove_dir_all(base); +} + +/// Opening a file to append or edit reads it, so the automation read roots apply as well as the +/// write roots. +#[test] +fn script_file_append_and_edit_need_the_read_roots() { + let base = folder("appendroots"); + let mut s = with_data(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + let roots = AutomationRoots::new(&[&base.join("main")], &[&base]).unwrap(); + let r = confine(roots.as_ref(), || { + run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/w.txt'), out = [u.open('w'), u.write('kept'), u.close()];\n\ + out.push(u.open('a'), u.error, u.open('e'), u.error); vc.log(out);", + ) + }) + .unwrap(); + assert_eq!(r["log"], json!([[true, true, true, false, DENIED, false, DENIED]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A script run from a folder that holds the settings folder reads its own files there, but no file +/// in the settings folder. +#[test] +fn script_files_in_a_folder_above_the_settings_folder_do_not_reach_it() { + let base = folder("above"); + let mut s = Session::new(); + s.attach_script_data(base.join("main/settings/Script Data")); + write(&base.join("main/settings/Script Grants.json"), b"{\"version\": 1, \"grants\": []}"); + write(&base.join("main/own.txt"), b"own"); + let r = run_in( + &mut s, + &base, + "var a = new File('own.txt'), g = new File('settings/Script Grants.json');\n\ + var out = [a.open('r'), a.read()]; a.close(); out.push(g.open('r'), g.error, g.exists); vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([[true, "own", false, DENIED, false]])); + let _ = std::fs::remove_dir_all(base); +} + +/// The settings folder is kept out of every grant also before it has been made. +#[test] +fn script_file_grants_never_reach_a_settings_folder_not_made_yet() { + let base = folder("unmade"); + let mut s = with_data(&base); + assert!(!base.join("settings").exists()); + start_framed(&mut s, &base, "var o = new Folder(Folder.userData.parent.parent.fsName); var f = o.selectDlg('p'); vc.log([f, o.error]);"); + assert!(pump_to_picker(&mut s).is_none()); + let settings = base.join("settings").to_string_lossy().into_owned(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![settings], always: true })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[null, "Script file access to the app's own folders is not allowed"]])); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +/// Files left open are written when the run ends in the order they were opened, so of two objects +/// that hold the same file, the one opened last decides what it holds. +#[test] +fn script_files_left_open_are_written_in_the_order_they_were_opened() { + let base = folder("flushorder"); + let mut s = with_data(&base); + let text = "var p = Folder.userData.fsName + '/two.txt'; var a = new File(p), b = new File(p);\n\ + a.open('w'); b.open('w'); a.write('first'); b.write('second'); vc.log(p);"; + for _ in 0..16 { + let r = run_in(&mut s, &base, text).unwrap(); + let path = PathBuf::from(r["log"][0].as_str().unwrap_or_default()); + assert_eq!(std::fs::read(&path).unwrap(), b"second", "{r}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Removing a file leaves the other objects that have it open without the file: they take no more +/// writes, and closing them does not make it again. +#[test] +fn script_file_remove_detaches_the_other_open_objects() { + let base = folder("removeopen"); + let mut s = with_data(&base); + let text = "var p = Folder.userData.fsName + '/gone.txt'; var a = new File(p), b = new File(p);\n\ + a.open('w'); a.write('x'); a.close(); b.open('e');\n\ + var removed = a.remove(); var w = b.write('y'); var e = b.error; b.close();\n\ + vc.log([removed, w, e, new File(p).exists]);"; + let r = run_in(&mut s, &base, text).unwrap(); + assert_eq!(r["log"], json!([[true, false, "Script file is not open for writing", false]]), "{r}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A run that ends with a changed file open that cannot be written fails and names the file. +#[test] +fn script_files_left_open_that_cannot_be_written_fail_the_run() { + let base = folder("unwritten"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/ro.txt'); u.open('w'); u.write('x'); new File(u.fsName).readonly = true; vc.log(u.fsName);", + ); + let report = s.script_report().unwrap(); + let path = PathBuf::from(report["log"][0].as_str().unwrap_or_default()); + if let Ok(m) = std::fs::metadata(&path) { + let mut p = m.permissions(); + #[allow(clippy::permissions_set_readonly_false)] + p.set_readonly(false); + let _ = std::fs::set_permissions(&path, p); + } + assert!(r.is_err(), "{report}"); + let message = report["message"].as_str().unwrap(); + assert!(message.contains("the script left open files that could not be written") && message.contains("ro.txt"), "{report}"); + assert_eq!(std::fs::read(&path).unwrap(), b"", "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The automation write roots apply to the run's own folders too: outside them `Folder.temp` and +/// `Folder.userData` are `null` and are not made. +#[test] +fn script_files_write_only_inside_the_automation_write_roots() { + let base = folder("writeroots"); + std::fs::create_dir_all(base.join("out")).unwrap(); + let roots = AutomationRoots::new(&[&base], &[&base.join("out")]).unwrap(); + let mut s = with_data(&base); + let r = confine(roots.as_ref(), || run_in(&mut s, &base, "vc.log([Folder.temp === null, Folder.userData === null]);")).unwrap(); + assert_eq!(r["log"], json!([[true, true]])); + assert!(!base.join("settings/Script Data").exists(), "the data folder is not made"); + let _ = std::fs::remove_dir_all(base); +} + +/// The run's temporary folder is checked against the write roots by its own name: a write root named +/// `VectorCraft Script` in the temporary folder does not take the run's folder beside it. +#[test] +fn script_temporary_folder_is_checked_by_its_own_name() { + let base = folder("tempname"); + let named = std::env::temp_dir().join("VectorCraft Script"); + let made = std::fs::create_dir(&named).is_ok(); + let roots = AutomationRoots::new(&[&base], &[&named]).unwrap(); + let mut s = with_data(&base); + let r = confine(roots.as_ref(), || run_in(&mut s, &base, "vc.log(Folder.temp === null);")); + if made { + let _ = std::fs::remove_dir(&named); + } + assert_eq!(r.unwrap()["log"], json!([true])); + let _ = std::fs::remove_dir_all(base); +} + +/// The folders made above a script's data folder are inside the write roots too: with a write root +/// that names the data folder after the folders above it were removed, none of them is made again. +#[test] +fn script_data_folder_makes_no_folder_outside_the_write_roots() { + let base = folder("dataparent"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap(); + let data = PathBuf::from(r["log"][0].as_str().unwrap()); + let roots = AutomationRoots::new(&[&base], &[&data]).unwrap(); + std::fs::remove_dir_all(base.join("settings")).unwrap(); + let r = confine(roots.as_ref(), || run_in(&mut s, &base, "vc.log(Folder.userData === null);")).unwrap(); + assert_eq!(r["log"], json!([true])); + assert!(!base.join("settings").exists(), "no folder above the write root is made"); + let _ = std::fs::remove_dir_all(base); +} + +/// `create` makes no folder outside the places the script may write: when the folders above its data +/// folder were removed during the run, a folder in the data folder is not made, and neither are they. +#[test] +fn script_folder_create_makes_no_folder_outside_the_grants() { + let base = folder("createabove"); + let mut s = with_data(&base); + start_framed(&mut s, &base, "var d = Folder.userData.fsName; File.openDialog('p'); var f = new Folder(d + '/a'); vc.log([f.create(), f.error]);"); + assert!(pump_to_picker(&mut s).is_none()); + std::fs::remove_dir_all(base.join("settings")).unwrap(); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED]])); + assert!(!base.join("settings").exists(), "no folder above the data folder is made"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file a script wrote stays written after its run fails, and the report names it. +#[test] +fn script_files_written_before_a_failure_are_named() { + let base = folder("failwrite"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/left.txt'); u.open('w'); u.write('left'); throw new Error('late');"); + assert!(r.is_err()); + let report = s.script_report().unwrap(); + let written: Vec = report["written"].as_array().unwrap().iter().filter_map(Value::as_str).map(PathBuf::from).collect(); + assert_eq!(written.len(), 1, "{report}"); + assert_eq!(std::fs::read(&written[0]).unwrap(), b"left", "the open file is written when the run ends"); + let _ = std::fs::remove_dir_all(base); +} + +/// Pumps the run in the app until it ends or waits at a file dialog (`None`). +fn pump_to_picker(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_picker().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Starts `main/main.jsx` in `base` with the text `text`, in the app. +fn start_framed(s: &mut Session, base: &Path, text: &str) { + s.script_frames = true; + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); +} + +/// The filter of an open or save dialog gives the file types the dialog shows; an open dialog with +/// `multiSelect` takes every file picked and gives them as a list. +#[test] +fn script_file_dialogs_show_the_filters_file_types_and_open_several_files() { + use crate::script::files::dialog_filters; + let f = |types: &[(&str, &[&str])]| -> Vec<(String, Vec)> { + types.iter().map(|(n, e)| (n.to_string(), e.iter().map(|e| e.to_string()).collect())).collect() + }; + assert_eq!(dialog_filters("JavaScript files:*.jsx;All files:*.*"), f(&[("JavaScript files", &["jsx"]), ("All files", &["*"])])); + assert_eq!(dialog_filters("Images:*.png,*.JPG , Text:*.txt"), f(&[("Images", &["png", "JPG"]), ("Text", &["txt"])])); + assert_eq!(dialog_filters("*.svg;*.ai"), f(&[("*.svg;*.ai", &["svg", "ai"])])); + assert_eq!(dialog_filters("All files:*.*"), f(&[]), "every file"); + assert_eq!(dialog_filters("Odd:a*b.txt;Bad:*.a/b;Text:*.txt"), f(&[("Text", &["txt"])]), "patterns that are not *.ext are left out"); + assert_eq!(dialog_filters(""), f(&[])); + + let base = folder("pickfilter"); + for name in ["a.txt", "b.txt"] { + write(&base.join("picked").join(name), b"x"); + } + let mut s = with_data(&base); + start_framed(&mut s, &base, "var f = File.openDialog('Pick', 'Text:*.txt;All files:*.*', true); vc.log([f.length, f[0].name, f[1].name]);"); + assert!(pump_to_picker(&mut s).is_none()); + let picker = s.script_picker().unwrap(); + assert!(picker.multiple); + assert_eq!(picker.filters, f(&[("Text", &["txt"]), ("All files", &["*"])])); + let paths = ["a.txt", "b.txt"].iter().map(|n| base.join("picked").join(n).to_string_lossy().into_owned()).collect(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths, always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[2, "a.txt", "b.txt"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A dialog's `filter` that is a function is called with each file picked, and the files it gives a +/// false value for are left out: a list keeps the rest, and one file, or a list left empty, gives +/// `null`. The dialog shows every file. A save dialog takes the same filter. +#[test] +fn script_file_dialogs_leave_out_the_files_a_filter_function_refuses() { + let base = folder("pickfilterfn"); + for name in ["a.txt", "b.svg", "c.txt"] { + write(&base.join("picked").join(name), b"x"); + } + let paths = |names: &[&str]| -> Vec { names.iter().map(|n| base.join("picked").join(n).to_string_lossy().into_owned()).collect() }; + let text = "var seen = [];\n\ + function txt(f) { seen.push(f instanceof File ? f.name : null); return f.name.slice(-4) === '.txt'; }\n\ + var many = File.openDialog('Pick', txt, true);\n\ + vc.log([many.length, many[0].name, many[1].name]);\n\ + vc.log(File.openDialog('Pick one', txt));\n\ + vc.log(File.openDialog('Pick svg', txt, true));\n\ + var saved = File.saveDialog('Save', txt);\n\ + vc.log(saved && saved.name);\n\ + vc.log(new File('x.txt').saveDlg('Save svg', txt));\n\ + vc.log(seen);"; + let mut s = with_data(&base); + start_framed(&mut s, &base, text); + for picked in [&["a.txt", "b.svg", "c.txt"][..], &["b.svg"], &["b.svg"], &["c.txt"], &["b.svg"]] { + assert!(pump_to_picker(&mut s).is_none()); + assert_eq!(s.script_picker().unwrap().filters, Vec::<(String, Vec)>::new(), "every file is shown"); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: paths(picked), always: false })); + } + let r = pump_to_picker(&mut s).unwrap().unwrap(); + let seen = ["a.txt", "b.svg", "c.txt", "b.svg", "b.svg", "c.txt", "b.svg"]; + assert_eq!(r["log"], json!([[2, "a.txt", "c.txt"], null, null, "c.txt", null, seen])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file a person allows always is kept for that script with that text: a later run reads it +/// without asking, and a run of changed text asks again. A file allowed once is not kept. +#[test] +fn script_file_dialog_grants_are_kept_for_the_same_script_text() { + let base = folder("grants"); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + let text = format!( + "var target = new File({:?});\n\ + if (target.open('r')) {{ vc.log(['kept', target.read()]); target.close(); }}\n\ + else {{ vc.log(['asked', target.error]); var f = File.saveDialog('Save it'); if (f) {{ f.open('w'); f.write('hi'); vc.log(f.close()); }} else vc.log(null); }}", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + let picker = s.script_picker().unwrap(); + assert_eq!((picker.kind, picker.prompt.as_str(), picker.can_always), (crate::script::files::PickerKind::Save, "Save it", true)); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["asked", DENIED], true])); + assert_eq!(std::fs::read(&out).unwrap(), b"hi"); + let grants = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(grants["grants"].as_array().unwrap().len(), 1, "{grants}"); + assert_eq!(grants["grants"][0]["write"], true); + + start_framed(&mut s, &base, &text); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["kept", "hi"]]), "the same script text keeps its grant"); + + start_framed(&mut s, &base, &format!("{text}\n// changed")); + assert!(pump_to_picker(&mut s).is_none(), "changed text has no grant, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["asked", DENIED], null])); + + let once = "var g = File.openDialog('Read it'); vc.log(g.fsName === null ? null : g.open('r') && g.read());"; + start_framed(&mut s, &base, once); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["hi"])); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1, "a file allowed once is not kept"); + + // A run that waits at a dialog keeps the grants it started with, so they are not revoked under it. + start_framed(&mut s, &base, once); + assert!(pump_to_picker(&mut s).is_none()); + let busy = s.execute("script.grants.revoke", &json!({"all": true})); + assert!(matches!(busy, Err(crate::EngineError::Busy)), "{busy:?}"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert!(pump_to_picker(&mut s).is_some(), "the run ends"); + + let removed = s.execute("script.grants.revoke", &json!({"path": out.to_string_lossy()})).unwrap(); + assert_eq!(removed["removed"], 1); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + assert!(s.execute("script.grants.revoke", &json!({})).is_err()); + assert!(!base.join("settings/Script Grants.json.part").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant is kept for the script's text with the files it includes: a changed included file asks +/// again. +#[test] +fn script_file_grants_are_kept_for_the_included_files_too() { + let base = folder("grantinclude"); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + write(&out, b"hi"); + write(&base.join("main/lib.jsxinc"), b"var lib = 1;\n"); + let text = format!( + "#include \"lib.jsxinc\"\nvar t = new File({:?});\nif (t.open('r')) vc.log('kept'); else vc.log(File.openDialog('p') ? 'asked' : null);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["kept"])); + write(&base.join("main/lib.jsxinc"), b"var lib = 2;\n"); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "a changed included file has no grant, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(base); +} + +/// A kept grant is in force only while the run evaluates code the run that kept it evaluated: a +/// file `$.evalFile` runs, or a string given to `eval` or `Function`, that differs withdraws it +/// before that code runs. +#[test] +fn script_file_grants_are_kept_for_the_code_the_script_evaluates() { + let base = folder("granteval"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + write(&base.join("main/lib.jsxinc"), b"var lib = 1;"); + write(&base.join("main/code.txt"), b"new File(p).open('r')"); + let text = format!( + "var p = {:?};\n$.evalFile('lib.jsxinc');\n\ + var c = new File('code.txt'); c.open('r'); var src = c.read(); c.close();\n\ + var one = Function('return 1')();\n\ + var before = new File(p).open('r');\n\ + var during = eval(src) && one === 1;\n\ + if (before) vc.log(['kept', during]); else vc.log(['asked', !!File.openDialog('p')]);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + let picked = || crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true }; + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(picked())); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", true]]), "the same code keeps the grant"); + write(&base.join("main/code.txt"), b"new File(p).open('r') && true"); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", false]]), "changed eval code runs without the grant"); + write(&base.join("main/code.txt"), b"new File(p).open('r')"); + write(&base.join("main/lib.jsxinc"), b"var lib = 2;"); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "a changed $.evalFile file has no grant, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", false]])); + write(&base.join("main/lib.jsxinc"), b"var lib = 1;"); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", true]])); + let grants = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(grants["grants"][0]["code"].as_array().map(Vec::len), Some(3), "{grants}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file's grant covers that path only: a folder the script makes in the file's place, in the run +/// that was allowed the file and in later runs that keep its grant, is not read or written inside. +#[test] +fn script_file_grants_do_not_reach_into_a_folder_in_the_files_place() { + let base = folder("grantfileplace"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = "var p = File.saveDialog('p').fsName;\n\ + var gone = new File(p).remove(); var made = new Folder(p).create();\n\ + var w = new File(p + '/x.txt'); vc.log([gone, made, w.open('w'), w.error]);"; + let mut s = with_data(&base); + start_framed(&mut s, &base, text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[true, true, false, DENIED]])); + assert!(out.is_dir() && !out.join("x.txt").exists()); + let grants = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(grants["grants"][0]["folder"], false, "{grants}"); + + let later = format!("var w = new File({:?}); vc.log([w.open('w'), w.error]);", out.join("y.txt").to_string_lossy()); + let main = base.join("main/main.jsx"); + write(&main, later.as_bytes()); + let real = std::fs::canonicalize(&main).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(later.as_bytes()); + let out_real = crate::cmd::findfiles::plain(std::fs::canonicalize(&out).unwrap()); + let kept = json!({"version": 1, "grants": [{"script": crate::cmd::findfiles::plain(real).to_string_lossy(), "sha256": hash, "code": [], "path": out_real.to_string_lossy(), "write": true, "folder": false}]}); + write(&base.join("settings/Script Grants.json"), kept.to_string().as_bytes()); + start_framed(&mut s, &base, &later); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[false, DENIED]]), "a kept file grant does not reach inside either"); + assert!(!out.join("y.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// The code a run evaluates after a person allowed it a file always is kept with the grant when +/// the run ends, so the next run of the same script that evaluates it keeps the grant. +#[test] +fn script_file_grants_keep_the_code_evaluated_after_the_dialog() { + let base = folder("grantlater"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = format!( + "var t = new File({:?}); var kept = t.open('r');\n\ + if (!kept) File.openDialog('p');\n\ + vc.log([kept, eval('new File(t.fsName).open(\"r\")')]);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[false, true]])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[true, true]])); + let _ = std::fs::remove_dir_all(base); +} + +/// Code another script left in a named engine withdraws a script's kept grants in that engine. +#[test] +fn script_file_grants_are_withdrawn_by_code_another_script_left_in_the_engine() { + let base = folder("grantengine"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = format!( + "#targetengine shared\nvar t = new File({:?});\nif (t.open('r')) vc.log('kept'); else vc.log(File.openDialog('p') ? 'asked' : null);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["kept"]), "the engine holds only this script's code"); + let other = base.join("main/other.jsx"); + write(&other, b"#targetengine shared\nvar otherWasHere = 1;"); + s.script_frames = false; + s.execute("script.run", &json!({"path": other.to_string_lossy()})).unwrap(); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "another script's code is in the engine, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(base); +} + +/// Code a script given as text left in a named engine withdraws a script's kept grants in that +/// engine, as a file script's code does. +#[test] +fn script_file_grants_are_withdrawn_by_code_a_text_script_left_in_the_engine() { + let base = folder("grantenginetext"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = format!( + "#targetengine shared\nvar t = new File({:?});\nif (t.open('r')) vc.log('kept'); else vc.log(File.openDialog('p') ? 'asked' : null);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + s.script_frames = false; + s.execute("script.run", &json!({"source": "#targetengine shared\nvar textWasHere = 1;"})).unwrap(); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "a text script's code is in the engine, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file opened for writing under a kept grant that new code withdraws takes no more writes, and +/// changes that cannot be written then fail the run when it ends. +#[test] +fn script_files_open_under_a_withdrawn_grant_keep_their_unwritten_changes() { + let base = folder("grantwithdrawn"); + let dir = base.join("picked"); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("out.txt"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('w')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ f.write('a'); new File(f.fsName).readonly = true; eval('1'); vc.log(['wrote', f.write('b'), f.error]); }}", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![dir.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + let r = pump_to_picker(&mut s).unwrap(); + let report = s.script_report().unwrap(); + if let Ok(m) = std::fs::metadata(&out) { + let mut p = m.permissions(); + #[allow(clippy::permissions_set_readonly_false)] + p.set_readonly(false); + let _ = std::fs::set_permissions(&out, p); + } + assert!(r.is_err(), "{report}"); + assert_eq!(report["log"], json!([["wrote", false, "Script file is not open for writing"]]), "{report}"); + let message = report["message"].as_str().unwrap(); + assert!(message.contains("the script left open files that could not be written") && message.contains("out.txt"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The folder that holds the settings is kept out of every grant: a pick there gives `null` with the +/// error, a grant written into the grants file for it is not taken, and the script cannot write the +/// grants file through its data folder. +#[test] +fn script_file_grants_never_reach_the_settings_folder() { + let base = folder("protected"); + let mut s = with_data(&base); + std::fs::create_dir_all(base.join("settings/Scripts")).unwrap(); + let inside = base.join("settings/Scripts/x.txt"); + write(&inside, b"secret"); + let text = format!( + "var o = new File('x.txt'); var f = o.saveDlg('p'); vc.log([f, o.error]);\n\ + var g = new File(Folder.userData.parent.parent.fsName + '/Script Grants.json'); vc.log([g.open('w'), g.error]);\n\ + var h = new File({:?}); vc.log([h.open('r'), h.error]);", + inside.to_string_lossy() + ); + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + let real = std::fs::canonicalize(&main).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(text.as_bytes()); + let settings = crate::cmd::findfiles::plain(std::fs::canonicalize(base.join("settings")).unwrap()); + let forged = json!({"version": 1, "grants": [{"script": crate::cmd::findfiles::plain(real).to_string_lossy(), "sha256": hash, "code": [], "path": settings.to_string_lossy(), "write": true, "folder": true}]}); + write(&base.join("settings/Script Grants.json"), forged.to_string().as_bytes()); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![inside.to_string_lossy().into_owned()], always: true })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + let protected = "Script file access to the app's own folders is not allowed"; + assert_eq!(r["log"], json!([[null, protected], [false, DENIED], [false, DENIED]])); + assert_eq!(std::fs::read(&inside).unwrap(), b"secret"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file dialog inside a built-in's callback throws in the app, where it cannot wait. +#[test] +fn script_file_dialog_in_a_callback_throws() { + let base = folder("callback"); + let mut s = Session::new(); + start_framed(&mut s, &base, "[1].forEach(function () { File.openDialog(); });"); + let r = pump_to_picker(&mut s).unwrap(); + assert!(r.is_err()); + let report = s.script_report().unwrap(); + assert!(report["message"].as_str().unwrap().contains("File.openDialog: a file dialog cannot open inside a callback"), "{report}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index d272fea167..0a4037a0d8 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -245,10 +245,46 @@ fn files_are_checked_before_they_are_read() { let _ = std::fs::remove_dir_all(&dir); } +/// A new empty folder for test `name`. +fn fresh_folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder +/// `dir` there once. +fn start_allowed(s: &mut Session, dir: &std::path::Path, source: &str) { + s.script_frames = true; + assert_eq!(run(s, &format!("Folder.selectDialog('Folder');\n{source}")).unwrap()["running"], true); + for _ in 0..10_000 { + if s.script_picker().is_some() { + let paths = vec![dir.to_string_lossy().into_owned()]; + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths, always: false })); + return; + } + assert!(s.script_pump().is_none(), "the run waits at its folder dialog"); + } + panic!("the run did not open its folder dialog"); +} + +/// Runs `source` in the app as [`start_allowed`] starts it, to its end. +fn run_allowed(s: &mut Session, dir: &std::path::Path, source: &str) -> Result { + start_allowed(s, dir, source); + let r = loop { + if let Some(r) = s.script_pump() { + break r; + } + }; + s.script_frames = false; + r +} + #[test] fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { - let path = std::env::temp_dir().join(format!("vc-script-batch-{}.svg", std::process::id())); - let _ = std::fs::remove_file(&path); + let dir = fresh_folder("batch"); + let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); let mut s = two_docs(); let source = format!( @@ -257,24 +293,90 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { {{command: 'document.export', params: {{path: {p:?}, format: 'svg'}}}},\ {{command: 'no.such', params: {{}}}}]}}); }} catch (e) {{ vc.log(e.name); }}" ); - let r = run(&mut s, &source).unwrap(); + let r = run_allowed(&mut s, &dir, &source).unwrap(); assert_eq!(r["log"], json!(["Error"]), "{r}"); assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay"); assert!(path.exists()); assert_eq!(r["written"], json!([p]), "{r}"); - let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir_all(&dir); } #[test] fn an_export_that_fails_names_no_file() { - let path = std::env::temp_dir().join(format!("vc-script-no-folder-{}", std::process::id())).join("out.svg"); + let dir = fresh_folder("no-folder"); + let path = dir.join("missing").join("out.svg"); let p = path.to_string_lossy().into_owned(); let mut s = two_docs(); let source = format!("try {{ vc.run('document.export', {{path: {p:?}, format: 'svg'}}); }} catch (e) {{ vc.log(e.name); }}"); - let r = run(&mut s, &source).unwrap(); + let r = run_allowed(&mut s, &dir, &source).unwrap(); assert_eq!(r["log"], json!(["Error"]), "{r}"); assert!(!path.exists()); assert_eq!(r["written"], json!([]), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The commands a script runs read and write only where its `File` and `Folder` objects may (its +/// temporary folder and what a person allowed it, here), and the files of the open documents. +#[test] +fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { + let dir = fresh_folder("gate"); + let (inside, outside) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let call = |id: &str, path: &std::path::Path| { + let p = path.to_string_lossy().into_owned(); + let format = if id == "document.export" { ", format: 'svg'" } else { "" }; + format!( + "try {{ vc.run('{id}', {{path: {p:?}{format}}}); vc.log('ok'); }} catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) + }; + let mut s = two_docs(); + let r = run(&mut s, &call("document.export", &outside.join("a.svg"))).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "a script given as text writes nowhere: {r}"); + assert!(!outside.join("a.svg").exists()); + let source = format!("{}{}", call("document.export", &inside.join("b.svg")), call("document.export", &outside.join("c.svg"))); + let r = run_allowed(&mut s, &inside, &source).unwrap(); + assert_eq!(r["log"], json!(["ok", "denied"]), "{r}"); + assert!(inside.join("b.svg").exists() && !outside.join("c.svg").exists()); + let r = run(&mut s, "var t = Folder.temp.fsName + '/t.svg'; vc.run('document.export', {path: t, format: 'svg'}); vc.log(new File(t).exists);") + .unwrap(); + assert_eq!(r["log"], json!([true]), "the run's temporary folder: {r}"); + let own = outside.join("own.svg"); + s.execute("document.save", &json!({"path": own.to_string_lossy()})).unwrap(); + std::fs::copy(&own, outside.join("copy.svg")).unwrap(); + let source = format!( + "vc.run('shape.rectangle', {{x: 1, y: 1, width: 1, height: 1}});\n{}{}{}{}", + call("document.save", &own), + call("document.open", &own), + call("document.open", &outside.join("copy.svg")), + call("document.save", &outside.join("other.svg")) + ); + let r = run(&mut s, &source).unwrap(); + assert_eq!(r["log"], json!(["ok", "ok", "denied", "denied"]), "an open document's own file, and no other: {r}"); + assert!(!outside.join("other.svg").exists()); + std::fs::remove_file(&own).unwrap(); + let r = run(&mut s, &call("document.save", &own)).unwrap(); + assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}"); + assert!(own.exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A command a script runs does not save into the app's own libraries; the same command run +/// outside a script does. +#[test] +fn a_scripts_commands_do_not_save_into_the_apps_libraries() { + let dir = fresh_folder("gate-library"); + let user = dir.join("user"); + let mut s = two_docs(); + s.swatch_libraries.set_user_dir(Some(user.to_string_lossy().into_owned())); + let source = "try { vc.run('swatch.library.save', {user: true, name: 'Mine'}); vc.log('ok'); } \ + catch (e) { vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }"; + let r = run(&mut s, source).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "{r}"); + assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder"); + s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap(); + assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -341,17 +443,18 @@ fn a_command_whose_result_cannot_cross_is_put_back() { #[test] fn an_abandoned_run_reports_the_files_it_wrote() { - let path = std::env::temp_dir().join(format!("vc-script-abandon-{}.svg", std::process::id())); - let _ = std::fs::remove_file(&path); + let dir = fresh_folder("abandon"); + let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); let mut s = two_docs(); - paused(&mut s, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}")); - assert!(path.exists(), "the first slice exported"); + start_allowed(&mut s, &dir, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}")); + assert!(s.script_pump().is_none()); + assert!(path.exists(), "the slice after the dialog exported"); assert!(s.script_abandon()); let report = s.script_report().unwrap(); assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}"); assert!(s.script_failure_text().unwrap().contains(&p)); - let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -881,19 +984,19 @@ fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { #[test] fn a_file_saved_before_a_failure_stays_written_and_is_named() { - let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id())); - let _ = std::fs::remove_file(&path); + let dir = fresh_folder("save"); + let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); let mut s = two_docs(); let before = state(&s); let source = format!("vc.run('file.saveAs', {{path: {p:?}}}); vc.run('shape.rectangle', {{x:1,y:1,width:1,height:1}}); throw new Error('later');"); - let e = run(&mut s, &source).unwrap_err().to_string(); + let e = run_allowed(&mut s, &dir, &source).unwrap_err().to_string(); assert!(path.exists()); assert!(e.contains(&p), "{e}"); assert_eq!(s.script_report().unwrap()["written"], json!([p])); assert_eq!(state(&s), before, "the document does not keep the new path"); - let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir_all(&dir); } /// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope @@ -918,16 +1021,13 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() { } }; let mut s = two_docs(); - s.script_frames = true; let confined_target = outside.join("confined.svg"); - let started = crate::file_access::confine(Some(&roots), || run(&mut s, &export(&confined_target))).unwrap(); - assert_eq!(started["running"], true); + crate::file_access::confine(Some(&roots), || start_allowed(&mut s, &dir, &export(&confined_target))); let r = crate::file_access::unconfined(|| finish(&mut s)).unwrap(); assert_eq!(r["log"], json!(["Error"]), "a confined caller's run stays confined: {r}"); assert!(!confined_target.exists()); let user_target = outside.join("user.svg"); - let started = crate::file_access::unconfined(|| run(&mut s, &export(&user_target))).unwrap(); - assert_eq!(started["running"], true); + crate::file_access::unconfined(|| start_allowed(&mut s, &dir, &export(&user_target))); let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}"); assert!(user_target.exists()); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 301b1235a4..92db4e6502 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -478,6 +478,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe units.extend(MID.encode_utf16()); units.extend_from_slice(&body.flat()); units.extend(TAIL.encode_utf16()); + interp.observe_code(&units); interp.source_units = interp.source_units.saturating_add(units.len()); let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len())); let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() }; @@ -557,6 +558,7 @@ fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult> { Ok((this_run && matches!(h, Value::Number(n) if n >= 0.0)).then_some(h)) } -/// Closes the object's open file, if it has one. -fn close_open(i: &mut Interp, o: ObjId) -> JsResult<()> { +/// Closes the object's open file, if it has one, which writes what the script wrote to it. → false +/// after setting `error` when that could not be written. +fn close_open(i: &mut Interp, o: ObjId) -> JsResult { + let mut written = true; if let Some(h) = is_open(i, o)? { - host(i, "close", &[h])?; + let r = host(i, "close", &[h])?; + written = outcome(i, o, &r)?; } - set_slot(i, o, HANDLE, Value::Number(-1.0)) + set_slot(i, o, HANDLE, Value::Number(-1.0))?; + Ok(written) } fn date(i: &mut Interp, ms: Value) -> JsResult { @@ -375,7 +385,10 @@ fn get_relative_uri(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsR fn change_path(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, _) = this_path(i, &this, "changePath")?; - close_open(i, o)?; + // An object whose changes could not be written keeps its path; `error` says why. + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } let p = parse(i, &arg(args, 0))?; let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; set_slot(i, o, PATH, fs)?; @@ -409,30 +422,282 @@ fn to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult { - let (o, _) = this_path(i, &this, "write")?; - let m = message(i, "noWrites")?; +/// Whether the host's answer `r` is not `{error}`; when it is, the object's `error` is set to it. +fn outcome(i: &mut Interp, o: ObjId, r: &Value) -> JsResult { + let error = i.rooted(std::slice::from_ref(r), |i| field(i, r, "error"))?; + if matches!(error, Value::String(_)) { + set_slot(i, o, ERROR, error)?; + return Ok(false); + } + Ok(true) +} + +/// Calls the host function `name` with the object's path and `args`. → whether it did the work. +fn path_call(i: &mut Interp, this: &Value, what: &str, name: &str, args: &[Value]) -> JsResult { + let (o, path) = this_path(i, this, what)?; + let mut all = vec![path]; + all.extend_from_slice(args); + let r = i.rooted(&all, |i| host(i, name, &all))?; + Ok(Value::Bool(outcome(i, o, &r)?)) +} + +/// `createAlias`: not available, so it sets `error` and returns `false`. +fn create_alias(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "createAlias")?; + let m = message(i, "noAlias")?; set_slot(i, o, ERROR, m)?; Ok(Value::Bool(false)) } -/// A setter that writes: it sets `error` and changes nothing. -fn no_writes_setter(i: &mut Interp, this: Value, args: &[Value], construct: bool) -> JsResult { - no_writes(i, this, args, construct)?; +/// Setting `hidden`: not available, so it sets `error` and changes nothing. +fn set_hidden(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "hidden")?; + let m = message(i, "noHidden")?; + set_slot(i, o, ERROR, m)?; Ok(Value::Undefined) } -/// A dialog method: it sets `error` and returns `null`. -fn no_picker(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - let (o, _) = this_path(i, &this, "dialog")?; - let m = message(i, "noPicker")?; - set_slot(i, o, ERROR, m)?; - Ok(Value::Null) +/// `remove()`: the file, or the folder when it is empty, deleted at once. +fn remove(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "remove")?; + // A file whose changes could not be written is not removed; `error` says why. + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } + path_call(i, &this, "remove", "remove", &[]) } -fn null_static(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { - Ok(Value::Null) +/// `rename(name)`: the object's file or folder named `name`, in the same folder; the object takes +/// the new path. +fn rename(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, path) = this_path(i, &this, "rename")?; + let name = Value::String(i.to_str(&arg(args, 0))?); + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } + let r = i.rooted(&[path.clone(), name.clone()], |i| host(i, "rename", &[path.clone(), name.clone()]))?; + if !outcome(i, o, &r)? { + return Ok(Value::Bool(false)); + } + let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?; + set_slot(i, o, PATH, fs)?; + Ok(Value::Bool(true)) +} + +/// `copy(target)`: the file copied to `target`, a path or a `File`, replacing a file there. +fn copy(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "copy")?; + let p = parse(i, &arg(args, 0))?; + let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; + i.rooted(std::slice::from_ref(&fs), |i| path_call(i, &this, "copy", "copy", std::slice::from_ref(&fs))) +} + +/// `Folder.prototype.create()`: the folder, with the folders above it that are missing. +fn create(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + path_call(i, &this, "create", "create", &[]) +} + +/// Setting `length`: the file cut, or filled with zero bytes, to that many bytes. +fn set_length(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "length")?; + let n = i.to_number(&arg(args, 0))?; + if !n.is_finite() || n < 0.0 { + return Err(i.throw(ErrorType::Range, "File.length: the length must be a finite number, 0 or more")); + } + path_call(i, &this, "length", "setLength", &[Value::Number(n.floor())])?; + Ok(Value::Undefined) +} + +/// Setting `readonly`. +fn set_readonly(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "readonly")?; + let on = arg(args, 0).truthy(); + path_call(i, &this, "readonly", "setReadonly", &[Value::Bool(on)])?; + Ok(Value::Undefined) +} + +/// The line end the object's `lineFeed` names: CRLF for `Windows`, CR for `Macintosh` and LF for +/// anything else, without regard to case. +fn line_end(i: &Interp, o: ObjId) -> JsResult<&'static str> { + Ok(match slot(i, o, LINE_FEED)? { + Value::String(s) => match s.to_rust_string().to_ascii_lowercase().as_str() { + "windows" => "\r\n", + "macintosh" => "\r", + _ => "\n", + }, + _ => "\n", + }) +} + +/// `write(...values)` and, with `line`, `writeln(...values)`: the values as `String(value)` gives +/// them, written at the position of the object's open file. The values are joined only for an open +/// file, and only while the text stays within twice the host's `maxWrite` UTF-16 code units: each +/// character takes at least one byte and at most two code units, so a longer text cannot fit in a +/// file, and the write sets `error` to the host's `tooLarge` and returns `false`. +fn write_values(i: &mut Interp, this: &Value, args: &[Value], what: &str, line: bool) -> JsResult { + let (o, _) = this_path(i, this, what)?; + let Some(h) = opened(i, o)? else { return Ok(Value::Bool(false)) }; + let c = classes(i)?; + let max = match i.get_value(&Value::Object(c.host), &key("maxWrite"))? { + Value::Number(n) if n.is_finite() && n >= 0.0 => (n as usize).saturating_mul(2), + _ => usize::MAX, + }; + let mut text = String::new(); + let mut units = 0usize; + for a in args { + i.use_fuel()?; + let s = i.to_str(a)?; + units = units.saturating_add(s.len()); + if units > max { + let m = message(i, "tooLarge")?; + set_slot(i, o, ERROR, m)?; + return Ok(Value::Bool(false)); + } + text.push_str(&s.to_rust_string()); + } + if line { + text.push_str(line_end(i, o)?); + } + i.reserve_heap(string_bytes(text.len()))?; + let text = Value::str(&text); + let r = i.rooted(&[h.clone(), text.clone()], |i| host(i, "write", &[h.clone(), text.clone()]))?; + Ok(Value::Bool(outcome(i, o, &r)?)) +} + +fn write(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + write_values(i, &this, args, "write", false) +} + +fn writeln(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + write_values(i, &this, args, "writeln", true) +} + +// ---- file dialogs ---- + +/// The file dialogs, made from script code so the run can wait at the host's `pick` until the +/// person answers: `ask` gives `pick`'s arguments and `wrap` turns its answer into objects. A +/// `filter` that is a function is called with each file picked, and the files it gives a false +/// value for are left out; when none is left, the dialog gives `null`. +const DIALOGS: &str = "(function (ask, pick, wrap) { + var isArray = Array.isArray; + function kept(files, filter) { + if (files === null || typeof filter !== 'function') return files; + if (!isArray(files)) return filter(files) ? files : null; + var out = []; + for (var k = 0; k < files.length; k++) if (filter(files[k])) out[out.length] = files[k]; + return out.length ? out : null; + } + function dialog(kind, self, prompt, multi, filter) { var a = ask(kind, self, prompt, multi, filter); return kept(wrap(kind, self, pick(a[0], a[1], a[2], a[3], a[4])), filter); } + return [ + function openDialog(prompt, filter, multiSelect) { return dialog('open', null, prompt, multiSelect, filter); }, + function saveDialog(prompt, filter) { return dialog('save', null, prompt, false, filter); }, + function openDlg(prompt, filter, multiSelect) { return dialog('open', this, prompt, multiSelect, filter); }, + function saveDlg(prompt, filter) { return dialog('save', this, prompt, false, filter); }, + function selectDialog(prompt) { return dialog('folder', null, prompt, false, null); }, + function selectDlg(prompt) { return dialog('folder', this, prompt, false, null); } + ]; +})"; + +/// `ask(kind, self, prompt, multi, filter)`: `[kind, prompt, multi, start, filter]`, the arguments +/// of the host's `pick`, where `start` is the path of `self` (a `File` or `Folder`, or `null` for the +/// class's own dialog) and `filter` the file types, a string, or `""` for any other value. `self` +/// must be a `File` or `Folder` when it is not `null`. +fn ask(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let kind = arg(args, 0); + let start = match arg(args, 1) { + Value::Null => Value::str(""), + s => this_path(i, &s, "dialog")?.1, + }; + let prompt = match arg(args, 2) { + Value::Undefined | Value::Null => Value::str(""), + p => Value::String(i.to_str(&p)?), + }; + let multi = Value::Bool(arg(args, 3).truthy()); + let filter = match arg(args, 4) { + f @ Value::String(_) => f, + _ => Value::str(""), + }; + i.rooted(&[kind.clone(), start.clone(), prompt.clone(), filter.clone()], |i| { + i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES)?; + let proto = i.intrinsics.array_proto; + let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(proto))); + i.rooted(&[Value::Object(out)], |i| { + for (at, v) in [kind.clone(), prompt.clone(), multi.clone(), start.clone(), filter.clone()].into_iter().enumerate() { + put_at(i, out, at as f64, v)?; + } + Ok(Value::Object(out)) + }) + }) +} + +/// `wrap(kind, self, answer)`: the `File` (a `Folder` for a folder dialog) for each path `pick` +/// gave, an array of them for a list, `null` for `null`, and `null` after setting `self`'s `error` +/// for `{error}`. +fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let c = classes(i)?; + let proto = if matches!(arg(args, 0), Value::String(s) if s.to_rust_string() == "folder") { c.folder_proto } else { c.file_proto }; + let answer = arg(args, 2); + match &answer { + Value::String(_) => return instance(i, proto, answer.clone()), + Value::Object(_) => {} + _ => return Ok(Value::Null), + } + let error = i.rooted(std::slice::from_ref(&answer), |i| field(i, &answer, "error"))?; + if matches!(error, Value::String(_)) { + if let Some(o) = arg(args, 1).as_object() + && matches!(slot(i, o, PATH)?, Value::String(_)) + { + set_slot(i, o, ERROR, error)?; + } + return Ok(Value::Null); + } + i.rooted(std::slice::from_ref(&answer), |i| { + let length = i.get_value(&answer, &key("length"))?; + let n = i.to_number(&length)?; + i.reserve_heap(OBJECT_BYTES)?; + let array_proto = i.intrinsics.array_proto; + let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(array_proto))); + i.rooted(&[Value::Object(out)], |i| { + let mut at = 0.0; + while at < n { + i.use_fuel()?; + let fs = i.get_value(&answer, &crate::value::number_to_str(at).flat())?; + let item = i.rooted(std::slice::from_ref(&fs), |i| instance(i, proto, fs.clone()))?; + put_at(i, out, at, item)?; + at += 1.0; + } + Ok(Value::Object(out)) + }) + }) +} + +/// Defines the file dialogs on `File`, `Folder` and their prototypes. +fn dialogs(i: &mut Interp, file: ObjId, file_proto: ObjId, folder: ObjId, folder_proto: ObjId) -> JsResult<()> { + let units = i.encode_source(DIALOGS).map_err(|e| i.compile_error_to_abrupt(e))?; + let code = i.compile_source(&units, false, CodeKind::Eval).map_err(|e| i.compile_error_to_abrupt(e))?; + let make = i.run_global(code, true)?; + let c = classes(i)?; + let pick = i.rooted(std::slice::from_ref(&make), |i| i.get_value(&Value::Object(c.host), &key("pick")))?; + let ask = native(i, "ask", ask, 5, NativeKind::Plain, false)?; + let made = i.rooted(&[make.clone(), pick.clone(), Value::Object(ask)], |i| { + let wrap = native(i, "wrap", wrap, 3, NativeKind::Plain, false)?; + i.call(&make, &Value::Undefined, &[Value::Object(ask), pick.clone(), Value::Object(wrap)]) + })?; + let on = [ + (file, "openDialog"), + (file, "saveDialog"), + (file_proto, "openDlg"), + (file_proto, "saveDlg"), + (folder, "selectDialog"), + (folder_proto, "selectDlg"), + ]; + i.rooted(std::slice::from_ref(&made), |i| { + for (at, (target, name)) in on.into_iter().enumerate() { + let f = i.get_value(&made, &crate::value::number_to_str(at as f64).flat())?; + data(i, target, name, f, HIDDEN)?; + } + Ok(()) + }) } fn text_static(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { @@ -530,19 +795,18 @@ fn open(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult Value::Undefined => "r".to_string(), m => i.to_str(&m)?.to_rust_string().to_lowercase(), }; - let refusal = match mode.as_str() { - "r" => None, - "w" | "e" | "a" => Some("noWrites"), - _ => Some("badMode"), - }; - if let Some(name) = refusal { - let m = message(i, name)?; + if !matches!(mode.as_str(), "r" | "w" | "e" | "a") { + let m = message(i, "badMode")?; set_slot(i, o, ERROR, m)?; return Ok(Value::Bool(false)); } - close_open(i, o)?; + // The object's earlier changes are written first; when they cannot be, it does not open again. + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } let encoding = slot(i, o, ENCODING)?; - let r = host(i, "open", &[path, encoding])?; + let mode = Value::str(&mode); + let r = host(i, "open", &[path, encoding, mode])?; let (error, id) = i.rooted(std::slice::from_ref(&r), |i| Ok((field(i, &r, "error")?, field(i, &r, "id")?)))?; if matches!(error, Value::String(_)) { set_slot(i, o, ERROR, error)?; @@ -559,8 +823,7 @@ fn close(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { if opened(i, o)?.is_none() { return Ok(Value::Bool(false)); } - close_open(i, o)?; - Ok(Value::Bool(true)) + Ok(Value::Bool(close_open(i, o)?)) } fn read(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -669,7 +932,7 @@ fn set_current(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult`: a new `Folder` for the host's location `place`, or `null`. fn place(i: &mut Interp, place: &str) -> JsResult { - let all = host(i, "locations", &[])?; + let all = host(i, "locations", &[Value::str(place)])?; let fs = i.rooted(std::slice::from_ref(&all), |i| field(i, &all, place))?; if !matches!(fs, Value::String(_)) { return Ok(Value::Null); @@ -735,8 +998,8 @@ fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { method(i, proto, "changePath", change_path, 1)?; method(i, proto, "resolve", resolve, 0)?; method(i, proto, "execute", execute, 0)?; - method(i, proto, "remove", no_writes, 0)?; - method(i, proto, "rename", no_writes, 1)?; + method(i, proto, "remove", remove, 0)?; + method(i, proto, "rename", rename, 1)?; method(i, ctor, "encode", encode, 1)?; method(i, ctor, "decode", decode, 1)?; method(i, ctor, "isEncodingAvailable", encoding_available, 1)?; @@ -744,10 +1007,10 @@ fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { data(i, ctor, "fs", system, HIDDEN) } -fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { - accessor(i, proto, "length", length, Some(no_writes_setter))?; - accessor(i, proto, "hidden", hidden, Some(no_writes_setter))?; - accessor(i, proto, "readonly", readonly, Some(no_writes_setter))?; +fn file_members(i: &mut Interp, proto: ObjId) -> JsResult<()> { + accessor(i, proto, "length", length, Some(set_length))?; + accessor(i, proto, "hidden", hidden, Some(set_hidden))?; + accessor(i, proto, "readonly", readonly, Some(set_readonly))?; accessor(i, proto, "creator", four_question_marks, None)?; accessor(i, proto, "type", four_question_marks, None)?; accessor(i, proto, "eof", eof, None)?; @@ -760,21 +1023,15 @@ fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { method(i, proto, "readch", read_char, 0)?; method(i, proto, "seek", seek, 2)?; method(i, proto, "tell", tell, 0)?; - method(i, proto, "write", no_writes, 1)?; - method(i, proto, "writeln", no_writes, 1)?; - method(i, proto, "copy", no_writes, 1)?; - method(i, proto, "createAlias", no_writes, 1)?; - method(i, proto, "openDlg", no_picker, 0)?; - method(i, proto, "saveDlg", no_picker, 0)?; - method(i, ctor, "openDialog", null_static, 0)?; - method(i, ctor, "saveDialog", null_static, 0) + method(i, proto, "write", write, 1)?; + method(i, proto, "writeln", writeln, 1)?; + method(i, proto, "copy", copy, 1)?; + method(i, proto, "createAlias", create_alias, 1) } fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { method(i, proto, "getFiles", get_files, 1)?; - method(i, proto, "create", no_writes, 0)?; - method(i, proto, "selectDlg", no_picker, 0)?; - method(i, ctor, "selectDialog", null_static, 0)?; + method(i, proto, "create", create, 0)?; accessor(i, ctor, "current", get_current, Some(set_current))?; for (place, get) in PLACES.into_iter().zip(PLACE_GETTERS) { accessor(i, ctor, place, get, None)?; @@ -814,8 +1071,9 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul constructor(i, "Folder", folder, folder_proto)?; common(i, file, file_proto)?; common(i, folder, folder_proto)?; - file_members(i, file, file_proto)?; - folder_members(i, folder, folder_proto) + file_members(i, file_proto)?; + folder_members(i, folder, folder_proto)?; + dialogs(i, file, file_proto, folder, folder_proto) }) } @@ -847,7 +1105,7 @@ mod tests { ("parent", Data::String("/".into())), ]) }; - let messages = ["notOpen", "noWrites", "noPicker", "badMode"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); + let messages = ["notOpen", "badMode", "noAlias", "noHidden"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); let stat = move |a: Vec| -> Result { let dir = text(&a, 0) == "/d"; Ok(obj(vec![("exists", Data::Bool(dir)), ("dir", Data::Bool(dir))])) diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index fbb5e4fc90..375312f497 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -412,7 +412,12 @@ impl Interp { Ok(units) => self.prepare_source(units.len().saturating_sub(floor)), Err(_) => Ok(()), }; - rest.map(|()| units.and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval))) + rest.map(|()| { + units.and_then(|units| { + self.observe_code(&units); + self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval) + }) + }) }); let code = code.and_then(|c| c); self.source_tag = tag; diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index de252c6c64..afd300c807 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -638,6 +638,24 @@ fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unkn assert_eq!(r.error_source(), 0, "a syntax error is in the script"); } +#[test] +fn the_code_observer_sees_every_source_evaluated_at_run_time() { + let mut r = realm(10_000_000); + let seen = Rc::new(RefCell::new(Vec::::new())); + let s = seen.clone(); + r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units))); + let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("load".into(), load)]).unwrap(); + let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap(); + assert_eq!(out, JsValue::Number(49.0)); + let want = ["1 + 1", "2", "(function anonymous(a\n) {\nreturn a\n})", "40 + 2"]; + assert_eq!(*seen.borrow(), want, "the script's own text is not observed"); + seen.borrow_mut().clear(); + r.run("eval(7); Function.prototype.toString.call(f)").unwrap(); + assert!(seen.borrow().is_empty(), "eval of a value that is not a string compiles nothing"); +} + #[test] fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() { let mut r = realm(10_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 22a365b615..2cbc5ae9cf 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -162,6 +162,9 @@ pub(crate) struct Frame { /// Where the exception being thrown was raised: the code and the instruction. type ThrowSite = (Rc, usize); +/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. +pub(crate) type CodeObserver = Rc; + pub(crate) struct Interp { pub(crate) heap: Heap, pub(crate) stack: Vec, @@ -230,6 +233,9 @@ pub(crate) struct Interp { pub(crate) source_tag: u32, /// The sources [`crate::HostItem::Evaluator`] functions have given in this realm. pub(crate) evaluated: u32, + /// Called with the source text given to `eval`, `Function` and evaluator functions, before it + /// is compiled ([`crate::Realm::observe_code`]). + pub(crate) code_observer: Option, /// The tag of the source the last run's error was raised in. pub(crate) error_tag: u32, /// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is @@ -468,6 +474,7 @@ impl Interp { data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, evaluated: 0, + code_observer: None, error_tag: crate::realm::UNKNOWN_SOURCE, thrown_mark: None, finally_marks: Vec::new(), @@ -2422,6 +2429,13 @@ impl Interp { crate::to_utf16(text, &self.remaining_source_options()).map_err(CompileError::Syntax) } + /// Gives `units`, source a script evaluates at run time, to the realm's code observer. + pub(crate) fn observe_code(&self, units: &[u16]) { + if let Some(f) = &self.code_observer { + f(units); + } + } + /// Parses and compiles source for eval code or a script, counting it against the source /// limit. pub(crate) fn compile_source(&mut self, units: &[u16], strict: bool, kind: CodeKind) -> Result, CompileError> { @@ -2460,6 +2474,7 @@ impl Interp { self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?; self.prepare_source(s.len())?; let units = self.flat_reserved(s)?; + self.observe_code(&units); let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?; self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let frame = self.frame()?; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 077f3b19b6..fbef8911c2 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -457,10 +457,12 @@ impl Realm { /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, - /// `encode`, `decode`, `encodingAvailable`, `current` and `locations`, with the values `system` - /// and `lineFeed` and the messages `text.notOpen`, `text.noWrites`, `text.noPicker` and - /// `text.badMode`. Each object keeps its path, its `error` text, its open file's id, its - /// encoding and its line feed in properties that are not enumerable. + /// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `pick` (the file + /// dialogs, where a run may wait), `encode`, `decode`, `encodingAvailable`, `current` and + /// `locations`, with the values `system` and `lineFeed` and the messages `text.notOpen`, + /// `text.badMode`, `text.noAlias` and `text.noHidden`. Each object keeps its path, its `error` + /// text, its open file's id, its encoding and its line feed in properties that are not + /// enumerable. pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { match crate::file_classes::install(&mut self.interp, items) { Ok(()) => Ok(()), @@ -532,6 +534,14 @@ impl Realm { self.interp.date_host.offset = std::rc::Rc::new(offset); } + /// Calls `observe` with the text of each source the realm's scripts evaluate at run time, before + /// it is compiled: a string given to `eval` (direct or indirect), the parameters and body + /// `Function` joins, and a source an evaluator host function + /// ([`crate::HostItem::Evaluator`]) gives. Replaces an earlier observer. + pub fn observe_code(&mut self, observe: impl Fn(&[u16]) + 'static) { + self.interp.code_observer = Some(std::rc::Rc::new(observe)); + } + /// Collects garbage now and returns the heap's estimated size in bytes afterwards. pub fn collect_garbage(&mut self) -> usize { self.interp.collect_garbage(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 67e67ac444..193e35b8dd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -177,6 +177,8 @@ impl VectorcraftApp { automation_roots: None, synthetic_frame: false, pending_plugin_install: None, + script_picked: Vec::new(), + script_picked_left_out: false, pen_end: Default::default(), host_iteration: 0, #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 197f8faaaa..8140dca6d6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -422,6 +422,7 @@ registry! { ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, + ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, @@ -671,6 +672,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::NOTICE_KIND { script_run::notice_cancel(app, &d); } + if d.kind == script_run::PICKER_KIND { + script_run::picker_cancel(app, &d); + } // Toolbar-only Flare options start no preview and must not cancel a gesture // that was already active before opening them. The generic parameter dialog has a spec // without a preview, yet previews some commands (Grid Repeat Options) when asked to. diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 8f5e3b1093..f8baa7b7de 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -13,10 +13,22 @@ //! `stop`. OK, Enter or `ui.dialog.confirm` without an `answer` gives the default button's answer. //! Escape or `ui.dialog.cancel` gives Cancel for a prompt, No for a confirm and Stop for an alert. //! Stop ends the run and puts back everything it did. +//! +//! A script's file dialog (kind `scriptFiles`: `File.openDialog`, `File.saveDialog`, +//! `Folder.selectDialog` and the objects' `openDlg`, `saveDlg` and `selectDlg`) has the fields +//! `kind` (open, save or folder), `prompt` and `canAlways`, and takes `answer`: `once`, `always` +//! (only with `canAlways`), `deny` or `stop`. Only the person at the keyboard answers `once` or +//! `always`: from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input they are refused, and the +//! dialog stays open; `deny` and `stop` are taken from automation too. The paths it allows are the +//! ones Choose… picked in the host's file dialog, at most 2,048; `ui.dialog.set` cannot set them, +//! and the dialog's own fields change neither what it allows nor what it says it allows. Escape, +//! `ui.dialog.cancel`, Enter, and OK or `ui.dialog.confirm` without an `answer` give Deny. +//! `selectDlg` opens the host's folder picker in its own folder. use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; +use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, ScriptDialog}; use super::{DialogAction, DialogSpec}; @@ -32,6 +44,19 @@ pub const GROWTH_KIND: &str = "scriptGrowth"; pub const CLOSE_KIND: &str = "scriptClose"; /// The dialog kind of a script's `alert`, `confirm` and `prompt`. pub const NOTICE_KIND: &str = "scriptDialog"; +/// The dialog kind of a script's file dialogs. +pub const PICKER_KIND: &str = "scriptFiles"; + +pub(super) const PICKER_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Script File Access").into(), + body_with_actions: Some(picker_body), + confirm: picker_confirm, + ok: None, + inputs: |_| &["answer"], + min_width: 420.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; pub(super) const NOTICE_SPEC: DialogSpec = DialogSpec { heading: notice_heading, @@ -171,7 +196,7 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { - let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND); + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND); if app.ui.dialog.is_some() { return; } @@ -192,6 +217,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { if !app.session.script_running() { app.ui.dialog = None; } else if app.session.script_dialog().is_none() + && app.session.script_picker().is_none() && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); @@ -327,6 +353,192 @@ fn give(app: &mut VectorcraftApp, d: &Dialog, answer: &str) -> Result = match p.kind { + PickerKind::Open if several => crate::picks::open_files(app, &pick), + PickerKind::Open => crate::picks::open(app, &pick).into_iter().collect(), + PickerKind::Save => crate::picks::save(app, &pick).into_iter().collect(), + // `selectDlg` starts in its folder; `Folder.selectDialog` gives none. + PickerKind::Folder => match p.start.clone() { + Some(start) => crate::picks::folder_at(app, &start).into_iter().collect(), + None => crate::picks::folder(app).into_iter().collect(), + }, + }; + if !chosen.is_empty() { + let mut paths = if several { std::mem::take(&mut app.script_picked) } else { Vec::new() }; + let mut seen: std::collections::HashSet = paths.iter().cloned().collect(); + for path in chosen { + if seen.contains(&path) { + continue; + } + if paths.len() >= MAX_ENTRIES { + app.script_picked_left_out = true; + break; + } + seen.insert(path.clone()); + paths.push(path); + } + app.script_picked = paths; + } + Ok(()) + }); + // Picking a path doesn't fail. + let _ = r; +} + +/// The dialog's prompt and the access it describes come from the request the run waits at, not +/// from the dialog's fields, so `ui.dialog.set` cannot change what the person reads. +fn picker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let t = Tokens::get(ui.ctx()); + let Some((kind, prompt)) = app.session.script_picker().map(|p| (p.kind, shown_text(&p.prompt, true))) else { return DialogAction::None }; + if !prompt.is_empty() { + egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| ui.label(&prompt)); + ui.add_space(8.0); + } + ui.label(picker_request(kind)); + ui.add_space(8.0); + let paths = app.script_picked.clone(); + ui.horizontal(|ui| { + if widgets::secondary_button(ui, tl!("Choose…")).clicked() { + choose(app, d); + } + ui.add_space(8.0); + if let [path] = paths.as_slice() { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + if paths.len() > 1 { + ui.add_space(4.0); + egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, |ui| { + for path in &paths { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + } + if app.script_picked_left_out { + ui.add_space(4.0); + ui.colored_label(t.error, crate::i18n::msg(PICKED_LEFT_OUT)); + } + ui.add_space(16.0); + let chosen = !app.script_picked.is_empty(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let mut answer = None; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + if widgets::primary_button_enabled(ui, tl!("Allow Once"), chosen).clicked() { + answer = Some("once"); + } + ui.add_space(8.0); + if can_always { + if ui.add_enabled_ui(chosen, |ui| widgets::secondary_button(ui, tl!("Always Allow This Script"))).inner.clicked() { + answer = Some("always"); + } + ui.add_space(8.0); + } + if widgets::secondary_button(ui, tl!("Deny")).clicked() { + answer = Some("deny"); + } + // The row runs right to left: Stop goes at its left end. + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if widgets::secondary_button(ui, tl!("Stop")).clicked() { + answer = Some("stop"); + } + }); + }); + // Enter gives the dialog's default answer, Deny, as `ui.dialog.confirm` without an answer does, + // unless it goes to the button that has the keyboard focus (Choose…). + let unfocused = ui.ctx().memory(|m| m.focused().is_none()); + if answer.is_none() && unfocused && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + answer = Some("deny"); + } + let Some(answer) = answer else { return DialogAction::None }; + d.fields.insert("answer".into(), json!(answer)); + DialogAction::Confirm +} + +/// What the file dialog of `kind` asks the person to allow. +fn picker_request(kind: PickerKind) -> &'static str { + match kind { + PickerKind::Open => tl!("The script asks to read a file you choose."), + PickerKind::Save => tl!("The script asks to read and write a file you choose."), + PickerKind::Folder => tl!("The script asks to read and write a folder you choose, with everything in it."), + } +} + +/// The note the file dialog shows when the person picked more files than a script is given. +const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; + +/// Gives the running script the file dialog's `answer`, or Deny. +fn picker_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let answer = d.fields.get("answer").and_then(Value::as_str).unwrap_or("deny"); + give_pick(app, answer) +} + +/// Escape or Cancel: Deny. +pub(super) fn picker_cancel(app: &mut VectorcraftApp, _: &Dialog) { + let _ = give_pick(app, "deny"); +} + +/// Gives the running script `answer` with the paths Choose… picked. Only the person at the keyboard +/// allows access: Allow Once and Always Allow are refused, and the dialog stays open, while +/// automation sends the answer (a control or MCP request, or synthetic input) or opened the host's +/// file dialog; Deny and Stop are taken from anyone. +fn give_pick(app: &mut VectorcraftApp, answer: &str) -> Result { + let paths = app.script_picked.clone(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let given = match answer { + "stop" => None, + "deny" => Some(PickAnswer::Deny), + "once" | "always" if app.automation_asked() => return Err("Only the person at the keyboard can allow a script's file access".into()), + "once" | "always" if paths.is_empty() => return Err("choose a file or folder first, or deny".into()), + "always" if !can_always => return Err("this script's file access can be allowed only once".into()), + "once" => Some(PickAnswer::Allow { paths, always: false }), + "always" => Some(PickAnswer::Allow { paths, always: true }), + _ => return Err("`answer` for a script's file dialog must be one of: once, always, deny, stop".into()), + }; + app.script_picked.clear(); + app.script_picked_left_out = false; + match given { + None => { + app.session.script_request_stop(); + } + Some(a) => { + app.session.script_pick(a); + } + } + if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PICKER_KIND) { + app.ui.dialog = None; + } + Ok(Value::Null) +} + fn answers_for(kind: &str) -> &'static str { match kind { "confirm" => "yes, no, stop", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3828d9ba2d..f69fbaaf2d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4094,6 +4094,13 @@ axis Both И двете Show External Script Warning Показвай предупреждение за външни скриптове A Script Is Running Изпълнява се скрипт Script Alert Известие от скрипт + Script File Access Достъп на скрипт до файлове + The script asks to read a file you choose. Скриптът иска да прочете файл, който изберете. + The script asks to read and write a file you choose. Скриптът иска да чете и записва файл, който изберете. + The script asks to read and write a folder you choose, with everything in it. Скриптът иска да чете и записва папка, която изберете, с цялото ѝ съдържание. + Allow Once Разреши веднъж + Always Allow This Script Винаги разрешавай този скрипт + Deny Откажи A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. Do not show this warning again Не показвай повече това предупреждение Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 81fee3a079..7dae2382aa 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4459,6 +4459,13 @@ imageTrace Outline Obris Show External Script Warning Prikaži upozorenje za vanjske skripte A Script Is Running Skripta se izvršava Script Alert Upozorenje skripte + Script File Access Pristup skripte datotekama + The script asks to read a file you choose. Skripta traži da pročita datoteku koju odaberete. + The script asks to read and write a file you choose. Skripta traži da čita i piše datoteku koju odaberete. + The script asks to read and write a folder you choose, with everything in it. Skripta traži da čita i piše folder koji odaberete, sa svim što je u njemu. + Allow Once Dozvoli jednom + Always Allow This Script Uvijek dozvoli ovu skriptu + Deny Odbij A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. Do not show this warning again Ne prikazuj više ovo upozorenje Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..03f88d8386 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5390,6 +5390,13 @@ digits Malayalam Malaiàlam Show External Script Warning Mostra l'avís dels scripts externs A Script Is Running S'està executant un script Script Alert Avís de l'script + Script File Access Accés de l’script als fitxers + The script asks to read a file you choose. L’script demana llegir un fitxer que trieu. + The script asks to read and write a file you choose. L’script demana llegir i escriure un fitxer que trieu. + The script asks to read and write a folder you choose, with everything in it. L’script demana llegir i escriure una carpeta que trieu, amb tot el que conté. + Allow Once Permet un cop + Always Allow This Script Permet sempre aquest script + Deny Denega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. Do not show this warning again No tornis a mostrar aquest avís Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir. @@ -5418,8 +5425,6 @@ digits Malayalam Malaiàlam @msg Script file could not be read No s'ha pogut llegir el fitxer de l'script @msg Script folder has more than 2,048 entries La carpeta de l'script té més de 2.048 entrades @msg Script file open mode must be r, w, e or a El mode d'obertura del fitxer de l'script ha de ser r, w, e o a -@msg Script file writing is not available L'escriptura de fitxers de l'script no està disponible -@msg Script file dialogs are not available Els quadres de diàleg de fitxers de l'script no estan disponibles @msg Script files cannot be opened in another application Els fitxers de l'script no es poden obrir en una altra aplicació @msg Script file access is unavailable on the web L'accés als fitxers de l'script no està disponible al web @msg Script has 256 files open L'script té 256 fitxers oberts @@ -5490,6 +5495,27 @@ digits Malayalam Malaiàlam @msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name} @msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script +@msg Script file access denied: {path} S’ha denegat l’accés de l’script als fitxers: {path} +@msg Script file access to the app's own folders is not allowed Els scripts no poden accedir a les carpetes pròpies de l’aplicació +@msg Script file cannot encode the text El fitxer de l’script no pot codificar el text +@msg Script file could not be written No s’ha pogut escriure el fitxer de l’script +@msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui +@msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi +@msg Script file name is already in use El nom del fitxer de l’script ja està en ús +@msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta +@msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer +@msg Script file permission could not be saved No s’ha pogut desar el permís de fitxers de l’script +@msg Script folder is not empty La carpeta de l’script no és buida +@msg Script files cannot make aliases Els fitxers de l’script no poden crear àlies +@msg Script file hidden setting cannot be changed No es pot canviar l’opció d’ocult del fitxer de l’script +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un diàleg de fitxers no es pot obrir dins d’una crida de retorn d’una funció integrada, d’un getter, d’una conversió o d’un fitxer que executa $.evalFile; crideu-lo des del codi propi de l’script +@msg the script wrote more file data than one run may write (32 MiB) l’script ha escrit més dades de fitxers de les que pot escriure una execució (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per al diàleg de fitxers d’un script ha de ser un d’aquests: once, always, deny, stop +@msg choose a file or folder first, or deny trieu primer un fitxer o una carpeta, o denegueu +@msg the script file permissions could not be saved: {e} no s’han pogut desar els permisos de fitxers dels scripts: {e} +@msg this script's file access can be allowed only once l’accés als fitxers d’aquest script només es pot permetre una vegada +@msg Only the person at the keyboard can allow a script's file access Només la persona al teclat pot permetre l’accés als fitxers d’un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script rep com a màxim 2.048 fitxers: els fitxers triats després d’aquests s’han deixat fora @msg Corners edits the corners of a path Cantonades edita les cantonades d’un traçat @msg could not decode image: {0} no s’ha pogut descodificar la imatge: {0} @msg Couldn't copy to the system clipboard: {e} No s’ha pogut copiar al porta-retalls del sistema: {e} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..f57201ed46 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4521,6 +4521,13 @@ imageTrace Outline Obrys Show External Script Warning Zobrazit upozornění u externích skriptů A Script Is Running Běží skript Script Alert Upozornění skriptu + Script File Access Přístup skriptu k souborům + The script asks to read a file you choose. Skript žádá o čtení souboru, který vyberete. + The script asks to read and write a file you choose. Skript žádá o čtení a zápis souboru, který vyberete. + The script asks to read and write a folder you choose, with everything in it. Skript žádá o čtení a zápis složky, kterou vyberete, se vším, co obsahuje. + Allow Once Povolit jednou + Always Allow This Script Vždy povolit tento skript + Deny Zamítnout A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. Do not show this warning again Toto upozornění již nezobrazovat Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. @@ -4549,8 +4556,6 @@ imageTrace Outline Obrys @msg Script file could not be read Soubor skriptu se nepodařilo přečíst @msg Script folder has more than 2,048 entries Složka skriptu má více než 2 048 položek @msg Script file open mode must be r, w, e or a Režim otevření souboru skriptu musí být r, w, e nebo a -@msg Script file writing is not available Zápis souborů skriptu není k dispozici -@msg Script file dialogs are not available Dialogy souborů skriptu nejsou k dispozici @msg Script files cannot be opened in another application Soubory skriptu nelze otevřít v jiné aplikaci @msg Script file access is unavailable on the web Přístup k souborům skriptu není na webu k dispozici @msg Script has 256 files open Skript má otevřeno 256 souborů @@ -4621,6 +4626,27 @@ imageTrace Outline Obrys @msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje @msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována +@msg Script file access denied: {path} Přístup skriptu k souborům byl odepřen: {path} +@msg Script file access to the app's own folders is not allowed Skript nemá povolen přístup k vlastním složkám aplikace +@msg Script file cannot encode the text Soubor skriptu nemůže zakódovat text +@msg Script file could not be written Soubor skriptu nelze zapsat +@msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví +@msg Script file is not open for writing Soubor skriptu není otevřený pro zápis +@msg Script file name is already in use Název souboru skriptu se už používá +@msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky +@msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru +@msg Script file permission could not be saved Oprávnění skriptu k souborům nelze uložit +@msg Script folder is not empty Složka skriptu není prázdná +@msg Script files cannot make aliases Soubory skriptu nemohou vytvářet aliasy +@msg Script file hidden setting cannot be changed Nastavení skrytí souboru skriptu nelze změnit +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dialog souboru nelze otevřít uvnitř zpětného volání vestavěné funkce, getteru, převodu ani souboru, který spouští $.evalFile; volejte jej z vlastního kódu skriptu +@msg the script wrote more file data than one run may write (32 MiB) skript zapsal více dat souborů, než smí zapsat jeden běh (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pro dialog souboru skriptu musí být jedna z hodnot: once, always, deny, stop +@msg choose a file or folder first, or deny nejprve vyberte soubor nebo složku, nebo odmítněte +@msg the script file permissions could not be saved: {e} oprávnění skriptů k souborům nelze uložit: {e} +@msg this script's file access can be allowed only once přístup tohoto skriptu k souborům lze povolit jen jednou +@msg Only the person at the keyboard can allow a script's file access Přístup skriptu k souborům může povolit jen člověk u klávesnice +@msg A script is given at most 2,048 files: the files picked after them were left out Skript dostane nejvýše 2 048 souborů: soubory vybrané po nich byly vynechány @msg Corners edits the corners of a path Rohy upravuje rohy cesty @msg Couldn't copy to the system clipboard: {e} Nelze kopírovat do systémové schránky: {e} @msg Couldn't open {name}: {e} {name} nelze otevřít: {e} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7011e23bf..3fb08554b0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4213,6 +4213,13 @@ imageTrace Outline Kontur Show External Script Warning Vis advarsel om eksterne scripts A Script Is Running Et script kører Script Alert Scriptadvarsel + Script File Access Scriptadgang til filer + The script asks to read a file you choose. Scriptet beder om at læse en fil, du vælger. + The script asks to read and write a file you choose. Scriptet beder om at læse og skrive en fil, du vælger. + The script asks to read and write a folder you choose, with everything in it. Scriptet beder om at læse og skrive en mappe, du vælger, med alt indhold. + Allow Once Tillad én gang + Always Allow This Script Tillad altid dette script + Deny Afvis A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. Do not show this warning again Vis ikke denne advarsel igen Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..de0e4eb16b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4135,6 +4135,13 @@ theme Appearance Erscheinungsbild Show External Script Warning Warnung bei externen Skripten anzeigen A Script Is Running Ein Skript wird ausgeführt Script Alert Skriptmeldung + Script File Access Dateizugriff des Skripts + The script asks to read a file you choose. Das Skript möchte eine Datei lesen, die Sie auswählen. + The script asks to read and write a file you choose. Das Skript möchte eine Datei lesen und schreiben, die Sie auswählen. + The script asks to read and write a folder you choose, with everything in it. Das Skript möchte einen Ordner, den Sie auswählen, mit seinem gesamten Inhalt lesen und schreiben. + Allow Once Einmal erlauben + Always Allow This Script Dieses Skript immer erlauben + Deny Ablehnen A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. Do not show this warning again Diese Warnung nicht mehr anzeigen Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. @@ -4163,8 +4170,6 @@ theme Appearance Erscheinungsbild @msg Script file could not be read Die Skriptdatei konnte nicht gelesen werden @msg Script folder has more than 2,048 entries Der Skriptordner hat mehr als 2.048 Einträge @msg Script file open mode must be r, w, e or a Der Öffnungsmodus der Skriptdatei muss r, w, e oder a sein -@msg Script file writing is not available Das Schreiben von Skriptdateien ist nicht verfügbar -@msg Script file dialogs are not available Dateidialoge für Skripte sind nicht verfügbar @msg Script files cannot be opened in another application Skriptdateien können nicht in einer anderen Anwendung geöffnet werden @msg Script file access is unavailable on the web Der Zugriff auf Skriptdateien ist im Web nicht verfügbar @msg Script has 256 files open Das Skript hat 256 Dateien geöffnet @@ -4235,6 +4240,27 @@ theme Appearance Erscheinungsbild @msg there is no script engine named {name} es gibt keine Skript-Engine namens {name} @msg Running a script Skript wird ausgeführt @msg Copied the script report Skriptbericht kopiert +@msg Script file access denied: {path} Dateizugriff des Skripts verweigert: {path} +@msg Script file access to the app's own folders is not allowed Skripte dürfen nicht auf die eigenen Ordner der App zugreifen +@msg Script file cannot encode the text Skriptdatei kann den Text nicht kodieren +@msg Script file could not be written Skriptdatei konnte nicht geschrieben werden +@msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet +@msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet +@msg Script file name is already in use Name der Skriptdatei wird bereits verwendet +@msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein +@msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird +@msg Script file permission could not be saved Dateiberechtigung des Skripts konnte nicht gespeichert werden +@msg Script folder is not empty Skriptordner ist nicht leer +@msg Script files cannot make aliases Skriptdateien können keine Aliasse erstellen +@msg Script file hidden setting cannot be changed Ausgeblendet-Einstellung der Skriptdatei kann nicht geändert werden +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ein Dateidialog kann nicht in einem Callback einer eingebauten Funktion, eines Getters, einer Umwandlung oder einer Datei geöffnet werden, die $.evalFile ausführt; rufen Sie ihn aus dem eigenen Code des Skripts auf +@msg the script wrote more file data than one run may write (32 MiB) das Skript hat mehr Dateidaten geschrieben, als ein Lauf schreiben darf (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` für den Dateidialog eines Skripts muss einer der folgenden Werte sein: once, always, deny, stop +@msg choose a file or folder first, or deny wählen Sie zuerst eine Datei oder einen Ordner aus oder lehnen Sie ab +@msg the script file permissions could not be saved: {e} die Dateiberechtigungen der Skripte konnten nicht gespeichert werden: {e} +@msg this script's file access can be allowed only once der Dateizugriff dieses Skripts kann nur einmal erlaubt werden +@msg Only the person at the keyboard can allow a script's file access Nur die Person an der Tastatur kann den Dateizugriff eines Skripts erlauben +@msg A script is given at most 2,048 files: the files picked after them were left out Ein Skript erhält höchstens 2.048 Dateien: Die danach ausgewählten Dateien wurden weggelassen @msg Corners edits the corners of a path „Ecken“ bearbeitet die Ecken eines Pfads @msg Couldn't copy to the system clipboard: {e} In die Systemzwischenablage konnte nicht kopiert werden: {e} @msg Couldn't open {name}: {e} {name} konnte nicht geöffnet werden: {e} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..b4229beada 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2309,6 +2309,13 @@ axis Both Και τα δύο Show External Script Warning Εμφάνιση προειδοποίησης για εξωτερικά σενάρια A Script Is Running Εκτελείται ένα σενάριο Script Alert Ειδοποίηση σεναρίου + Script File Access Πρόσβαση σεναρίου σε αρχεία + The script asks to read a file you choose. Το σενάριο ζητά να διαβάσει ένα αρχείο που θα επιλέξετε. + The script asks to read and write a file you choose. Το σενάριο ζητά να διαβάσει και να γράψει ένα αρχείο που θα επιλέξετε. + The script asks to read and write a folder you choose, with everything in it. Το σενάριο ζητά να διαβάσει και να γράψει έναν φάκελο που θα επιλέξετε, με όλο το περιεχόμενό του. + Allow Once Να επιτραπεί μία φορά + Always Allow This Script Να επιτρέπεται πάντα αυτό το σενάριο + Deny Άρνηση A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. @@ -2337,8 +2344,6 @@ axis Both Και τα δύο @msg Script file could not be read Δεν ήταν δυνατή η ανάγνωση του αρχείου σεναρίου @msg Script folder has more than 2,048 entries Ο φάκελος σεναρίου έχει περισσότερες από 2.048 καταχωρίσεις @msg Script file open mode must be r, w, e or a Ο τρόπος ανοίγματος του αρχείου σεναρίου πρέπει να είναι r, w, e ή a -@msg Script file writing is not available Η εγγραφή αρχείων σεναρίου δεν είναι διαθέσιμη -@msg Script file dialogs are not available Τα παράθυρα διαλόγου αρχείων σεναρίου δεν είναι διαθέσιμα @msg Script files cannot be opened in another application Τα αρχεία σεναρίου δεν μπορούν να ανοίξουν σε άλλη εφαρμογή @msg Script file access is unavailable on the web Η πρόσβαση σε αρχεία σεναρίου δεν είναι διαθέσιμη στο web @msg Script has 256 files open Το σενάριο έχει 256 ανοιχτά αρχεία @@ -2409,6 +2414,27 @@ axis Both Και τα δύο @msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name} @msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε +@msg Script file access denied: {path} Η πρόσβαση του σεναρίου σε αρχεία απορρίφθηκε: {path} +@msg Script file access to the app's own folders is not allowed Δεν επιτρέπεται η πρόσβαση σεναρίων στους φακέλους της ίδιας της εφαρμογής +@msg Script file cannot encode the text Το αρχείο του σεναρίου δεν μπορεί να κωδικοποιήσει το κείμενο +@msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου +@msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει +@msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή +@msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη +@msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο +@msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο +@msg Script file permission could not be saved Δεν ήταν δυνατή η αποθήκευση της άδειας αρχείων του σεναρίου +@msg Script folder is not empty Ο φάκελος του σεναρίου δεν είναι κενός +@msg Script files cannot make aliases Τα αρχεία του σεναρίου δεν μπορούν να δημιουργήσουν ψευδώνυμα +@msg Script file hidden setting cannot be changed Η ρύθμιση απόκρυψης του αρχείου του σεναρίου δεν μπορεί να αλλάξει +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ένα παράθυρο διαλόγου αρχείων δεν μπορεί να ανοίξει μέσα σε callback ενσωματωμένης συνάρτησης, getter, μετατροπής ή αρχείου που εκτελεί το $.evalFile· καλέστε το από τον κώδικα του ίδιου του σεναρίου +@msg the script wrote more file data than one run may write (32 MiB) το σενάριο έγραψε περισσότερα δεδομένα αρχείων από όσα επιτρέπεται να γράψει μία εκτέλεση (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop το `answer` για το παράθυρο διαλόγου αρχείων ενός σεναρίου πρέπει να είναι ένα από: once, always, deny, stop +@msg choose a file or folder first, or deny επιλέξτε πρώτα ένα αρχείο ή έναν φάκελο, ή απορρίψτε +@msg the script file permissions could not be saved: {e} δεν ήταν δυνατή η αποθήκευση των αδειών αρχείων των σεναρίων: {e} +@msg this script's file access can be allowed only once η πρόσβαση αυτού του σεναρίου σε αρχεία μπορεί να επιτραπεί μόνο μία φορά +@msg Only the person at the keyboard can allow a script's file access Μόνο το άτομο στο πληκτρολόγιο μπορεί να επιτρέψει την πρόσβαση ενός σεναρίου σε αρχεία +@msg A script is given at most 2,048 files: the files picked after them were left out Ένα σενάριο λαμβάνει το πολύ 2.048 αρχεία: τα αρχεία που επιλέχθηκαν μετά από αυτά παραλείφθηκαν @msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής @msg Couldn't copy to the system clipboard: {e} Δεν ήταν δυνατή η αντιγραφή στο πρόχειρο συστήματος: {e} @msg Couldn't open {name}: {e} Δεν ήταν δυνατό το άνοιγμα του {name}: {e} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..37af97bec8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4211,6 +4211,13 @@ axis Both Ambos Show External Script Warning Mostrar advertencia de scripts externos A Script Is Running Se está ejecutando un script Script Alert Aviso del script + Script File Access Acceso del script a archivos + The script asks to read a file you choose. El script pide leer un archivo que usted elija. + The script asks to read and write a file you choose. El script pide leer y escribir un archivo que usted elija. + The script asks to read and write a folder you choose, with everything in it. El script pide leer y escribir una carpeta que usted elija, con todo su contenido. + Allow Once Permitir una vez + Always Allow This Script Permitir siempre este script + Deny Denegar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. Do not show this warning again No volver a mostrar esta advertencia Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. @@ -4239,8 +4246,6 @@ axis Both Ambos @msg Script file could not be read No se pudo leer el archivo de script @msg Script folder has more than 2,048 entries La carpeta de script tiene más de 2048 entradas @msg Script file open mode must be r, w, e or a El modo de apertura del archivo de script debe ser r, w, e o a -@msg Script file writing is not available La escritura de archivos de script no está disponible -@msg Script file dialogs are not available Los cuadros de diálogo de archivos de script no están disponibles @msg Script files cannot be opened in another application Los archivos de script no se pueden abrir en otra aplicación @msg Script file access is unavailable on the web El acceso a archivos de script no está disponible en la web @msg Script has 256 files open El script tiene 256 archivos abiertos @@ -4311,6 +4316,27 @@ axis Both Ambos @msg there is no script engine named {name} no hay ningún motor de scripts llamado {name} @msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script +@msg Script file access denied: {path} Acceso del script a archivos denegado: {path} +@msg Script file access to the app's own folders is not allowed El script no puede acceder a las carpetas propias de la aplicación +@msg Script file cannot encode the text El archivo del script no puede codificar el texto +@msg Script file could not be written No se pudo escribir el archivo del script +@msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda +@msg Script file is not open for writing El archivo del script no está abierto para escritura +@msg Script file name is already in use El nombre del archivo del script ya está en uso +@msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta +@msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo +@msg Script file permission could not be saved No se pudo guardar el permiso de archivos del script +@msg Script folder is not empty La carpeta del script no está vacía +@msg Script files cannot make aliases Los archivos del script no pueden crear alias +@msg Script file hidden setting cannot be changed No se puede cambiar el ajuste de oculto del archivo del script +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un cuadro de diálogo de archivo no se puede abrir dentro de una devolución de llamada de una función integrada, un getter, una conversión o un archivo que ejecuta $.evalFile; llámelo desde el propio código del script +@msg the script wrote more file data than one run may write (32 MiB) el script escribió más datos de archivo de los que puede escribir una ejecución (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para el cuadro de diálogo de archivo de un script debe ser uno de: once, always, deny, stop +@msg choose a file or folder first, or deny elija primero un archivo o una carpeta, o deniegue +@msg the script file permissions could not be saved: {e} no se pudieron guardar los permisos de archivos de los scripts: {e} +@msg this script's file access can be allowed only once el acceso a archivos de este script solo se puede permitir una vez +@msg Only the person at the keyboard can allow a script's file access Solo la persona que está en el teclado puede permitir el acceso a archivos de un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script recibe como máximo 2.048 archivos: los archivos elegidos después de ellos se omitieron @msg Corners edits the corners of a path Esquinas edita las esquinas de un trazado @msg Couldn't copy to the system clipboard: {e} No se pudo copiar al portapapeles del sistema: {e} @msg Couldn't open {name}: {e} No se pudo abrir {name}: {e} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..029229411c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4435,6 +4435,13 @@ imageTrace Outline Ääriviiva Show External Script Warning Näytä ulkoisten komentosarjojen varoitus A Script Is Running Komentosarja on käynnissä Script Alert Komentosarjan ilmoitus + Script File Access Komentosarjan tiedostojen käyttö + The script asks to read a file you choose. Komentosarja pyytää lupaa lukea valitsemasi tiedoston. + The script asks to read and write a file you choose. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi tiedoston. + The script asks to read and write a folder you choose, with everything in it. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi kansion ja kaiken sen sisällön. + Allow Once Salli kerran + Always Allow This Script Salli tämä komentosarja aina + Deny Estä A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. Do not show this warning again Älä näytä tätä varoitusta uudelleen Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. @@ -4463,8 +4470,6 @@ imageTrace Outline Ääriviiva @msg Script file could not be read Komentosarjatiedostoa ei voitu lukea @msg Script folder has more than 2,048 entries Komentosarjakansiossa on yli 2 048 kohdetta @msg Script file open mode must be r, w, e or a Komentosarjatiedoston avaustilan on oltava r, w, e tai a -@msg Script file writing is not available Komentosarjatiedostojen kirjoittaminen ei ole käytettävissä -@msg Script file dialogs are not available Komentosarjojen tiedostovalintaikkunat eivät ole käytettävissä @msg Script files cannot be opened in another application Komentosarjatiedostoja ei voi avata toisessa sovelluksessa @msg Script file access is unavailable on the web Komentosarjatiedostojen käyttö ei ole mahdollista verkossa @msg Script has 256 files open Komentosarjalla on 256 tiedostoa auki @@ -4535,6 +4540,27 @@ imageTrace Outline Ääriviiva @msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole @msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin +@msg Script file access denied: {path} Komentosarjan tiedostojen käyttö estettiin: {path} +@msg Script file access to the app's own folders is not allowed Komentosarjat eivät saa käyttää sovelluksen omia kansioita +@msg Script file cannot encode the text Komentosarjan tiedosto ei voi koodata tekstiä +@msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa +@msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö +@msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten +@msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä +@msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota +@msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle +@msg Script file permission could not be saved Komentosarjan tiedostolupaa ei voitu tallentaa +@msg Script folder is not empty Komentosarjan kansio ei ole tyhjä +@msg Script files cannot make aliases Komentosarjan tiedostot eivät voi luoda aliaksia +@msg Script file hidden setting cannot be changed Komentosarjan tiedoston piilotusasetusta ei voi muuttaa +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: tiedostovalintaikkunaa ei voi avata sisäänrakennetun funktion, getterin, muunnoksen tai $.evalFile-funktion suorittaman tiedoston takaisinkutsussa; kutsu sitä komentosarjan omasta koodista +@msg the script wrote more file data than one run may write (32 MiB) komentosarja kirjoitti enemmän tiedostodataa kuin yksi suoritus saa kirjoittaa (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop komentosarjan tiedostovalintaikkunan `answer`-arvon on oltava jokin seuraavista: once, always, deny, stop +@msg choose a file or folder first, or deny valitse ensin tiedosto tai kansio tai estä +@msg the script file permissions could not be saved: {e} komentosarjojen tiedostolupia ei voitu tallentaa: {e} +@msg this script's file access can be allowed only once tämän komentosarjan tiedostojen käytön voi sallia vain kerran +@msg Only the person at the keyboard can allow a script's file access Vain näppäimistön ääressä oleva ihminen voi sallia komentosarjan tiedostojen käytön +@msg A script is given at most 2,048 files: the files picked after them were left out Komentosarja saa enintään 2 048 tiedostoa: niiden jälkeen valitut tiedostot jätettiin pois @msg Corners edits the corners of a path Kulmat-toiminto muokkaa polun kulmia @msg Couldn't copy to the system clipboard: {e} Järjestelmän leikepöydälle ei voitu kopioida: {e} @msg Couldn't open {name}: {e} Tiedostoa {name} ei voitu avata: {e} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..d942ad6638 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4200,6 +4200,13 @@ axis Both Les deux Show External Script Warning Afficher l’avertissement des scripts externes A Script Is Running Un script est en cours d’exécution Script Alert Alerte de script + Script File Access Accès du script aux fichiers + The script asks to read a file you choose. Le script demande à lire un fichier que vous choisissez. + The script asks to read and write a file you choose. Le script demande à lire et écrire un fichier que vous choisissez. + The script asks to read and write a folder you choose, with everything in it. Le script demande à lire et écrire un dossier que vous choisissez, avec tout son contenu. + Allow Once Autoriser une fois + Always Allow This Script Toujours autoriser ce script + Deny Refuser A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. Do not show this warning again Ne plus afficher cet avertissement Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau. @@ -4228,8 +4235,6 @@ axis Both Les deux @msg Script file could not be read Le fichier de script n’a pas pu être lu @msg Script folder has more than 2,048 entries Le dossier de script contient plus de 2 048 entrées @msg Script file open mode must be r, w, e or a Le mode d’ouverture du fichier de script doit être r, w, e ou a -@msg Script file writing is not available L’écriture de fichiers de script n’est pas disponible -@msg Script file dialogs are not available Les boîtes de dialogue de fichiers de script ne sont pas disponibles @msg Script files cannot be opened in another application Les fichiers de script ne peuvent pas être ouverts dans une autre application @msg Script file access is unavailable on the web L’accès aux fichiers de script n’est pas disponible sur le web @msg Script has 256 files open Le script a 256 fichiers ouverts @@ -4300,6 +4305,27 @@ axis Both Les deux @msg there is no script engine named {name} il n'y a aucun moteur de script nommé {name} @msg Running a script Exécution d’un script @msg Copied the script report Rapport du script copié +@msg Script file access denied: {path} Accès du script aux fichiers refusé : {path} +@msg Script file access to the app's own folders is not allowed L’accès du script aux dossiers propres à l’application n’est pas autorisé +@msg Script file cannot encode the text Le fichier du script ne peut pas encoder le texte +@msg Script file could not be written Le fichier du script n’a pas pu être écrit +@msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre +@msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture +@msg Script file name is already in use Le nom du fichier du script est déjà utilisé +@msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier +@msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier +@msg Script file permission could not be saved L’autorisation d’accès aux fichiers du script n’a pas pu être enregistrée +@msg Script folder is not empty Le dossier du script n’est pas vide +@msg Script files cannot make aliases Les fichiers du script ne peuvent pas créer d’alias +@msg Script file hidden setting cannot be changed Le réglage masqué du fichier du script ne peut pas être modifié +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name} : une boîte de dialogue de fichiers ne peut pas s’ouvrir dans un rappel d’une fonction intégrée, d’un accesseur, d’une conversion ou d’un fichier exécuté par $.evalFile ; appelez-la depuis le propre code du script +@msg the script wrote more file data than one run may write (32 MiB) le script a écrit plus de données de fichiers qu’une exécution ne peut en écrire (32 Mio) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop +@msg choose a file or folder first, or deny choisissez d’abord un fichier ou un dossier, ou refusez +@msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} +@msg this script's file access can be allowed only once l’accès aux fichiers de ce script ne peut être autorisé qu’une fois +@msg Only the person at the keyboard can allow a script's file access Seule la personne au clavier peut autoriser l’accès aux fichiers d’un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté @msg Corners edits the corners of a path Angles modifie les angles d’un tracé @msg Couldn't copy to the system clipboard: {e} Impossible de copier dans le presse-papiers du système : {e} @msg Couldn't open {name}: {e} Impossible d’ouvrir {name} : {e} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..43be9c9051 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6494,6 +6494,13 @@ antiAlias Sharp शार्प Show External Script Warning बाहरी स्क्रिप्ट की चेतावनी दिखाएँ A Script Is Running एक स्क्रिप्ट चल रही है Script Alert स्क्रिप्ट सूचना + Script File Access स्क्रिप्ट की फ़ाइल पहुँच + The script asks to read a file you choose. स्क्रिप्ट आपकी चुनी हुई फ़ाइल पढ़ने की अनुमति माँगती है। + The script asks to read and write a file you choose. स्क्रिप्ट आपकी चुनी हुई फ़ाइल पढ़ने और लिखने की अनुमति माँगती है। + The script asks to read and write a folder you choose, with everything in it. स्क्रिप्ट आपका चुना हुआ फ़ोल्डर और उसकी सारी सामग्री पढ़ने और लिखने की अनुमति माँगती है। + Allow Once एक बार अनुमति दें + Always Allow This Script इस स्क्रिप्ट को हमेशा अनुमति दें + Deny अस्वीकार करें A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। Do not show this warning again यह चेतावनी फिर न दिखाएँ Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। @@ -6522,8 +6529,6 @@ antiAlias Sharp शार्प @msg Script file could not be read स्क्रिप्ट फ़ाइल पढ़ी नहीं जा सकी @msg Script folder has more than 2,048 entries स्क्रिप्ट फ़ोल्डर में 2,048 से अधिक प्रविष्टियाँ हैं @msg Script file open mode must be r, w, e or a स्क्रिप्ट फ़ाइल खोलने का मोड r, w, e या a होना चाहिए -@msg Script file writing is not available स्क्रिप्ट फ़ाइल लिखना उपलब्ध नहीं है -@msg Script file dialogs are not available स्क्रिप्ट फ़ाइल संवाद उपलब्ध नहीं हैं @msg Script files cannot be opened in another application स्क्रिप्ट फ़ाइलें किसी अन्य ऐप्लिकेशन में नहीं खोली जा सकतीं @msg Script file access is unavailable on the web वेब पर स्क्रिप्ट फ़ाइल पहुँच उपलब्ध नहीं है @msg Script has 256 files open स्क्रिप्ट ने 256 फ़ाइलें खोल रखी हैं @@ -6594,6 +6599,27 @@ antiAlias Sharp शार्प @msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है @msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट +@msg Script file access denied: {path} स्क्रिप्ट की फ़ाइल पहुँच अस्वीकार की गई: {path} +@msg Script file access to the app's own folders is not allowed स्क्रिप्ट को ऐप के अपने फ़ोल्डरों तक पहुँचने की अनुमति नहीं है +@msg Script file cannot encode the text स्क्रिप्ट फ़ाइल टेक्स्ट को एन्कोड नहीं कर सकती +@msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी +@msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है +@msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है +@msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है +@msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए +@msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है +@msg Script file permission could not be saved स्क्रिप्ट की फ़ाइल अनुमति सहेजी नहीं जा सकी +@msg Script folder is not empty स्क्रिप्ट फ़ोल्डर खाली नहीं है +@msg Script files cannot make aliases स्क्रिप्ट फ़ाइलें उपनाम नहीं बना सकतीं +@msg Script file hidden setting cannot be changed स्क्रिप्ट फ़ाइल की छिपी सेटिंग बदली नहीं जा सकती +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: फ़ाइल डायलॉग किसी बिल्ट-इन फ़ंक्शन, getter, रूपांतरण या $.evalFile द्वारा चलाई गई फ़ाइल के callback के भीतर नहीं खुल सकता; इसे स्क्रिप्ट के अपने कोड से कॉल करें +@msg the script wrote more file data than one run may write (32 MiB) स्क्रिप्ट ने एक रन में लिखे जा सकने वाले फ़ाइल डेटा से अधिक लिखा (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop +@msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें +@msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सहेजी नहीं जा सकीं: {e} +@msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है +@msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है +@msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं @msg copy needs path: the file to copy into the document's folder copy: प्रतिलिपि की जरूरत है पाथ: फ़ाइल को डॉक्यूमेंट के फ़ोल्डर में कॉपी करने के लिए @msg copy takes images only: relink placed documents where their files are copy: प्रतिलिपि केवल इमेज को लेती है: डॉक्यूमेंट्स को फिर से लिंक करें जहां उनकी फ़ाइलें हैं @msg copying a file isn't available on the web एक फ़ाइल की प्रतिलिपि वेब पर उपलब्ध नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..b3c0827878 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5015,6 +5015,13 @@ imageTrace Outline Körvonal Show External Script Warning Figyelmeztetés külső parancsfájlok előtt A Script Is Running Egy parancsfájl fut Script Alert Parancsfájl-értesítés + Script File Access Parancsfájl fájlhozzáférése + The script asks to read a file you choose. A parancsfájl egy Ön által választott fájl olvasását kéri. + The script asks to read and write a file you choose. A parancsfájl egy Ön által választott fájl olvasását és írását kéri. + The script asks to read and write a folder you choose, with everything in it. A parancsfájl egy Ön által választott mappa és teljes tartalma olvasását és írását kéri. + Allow Once Engedélyezés egyszer + Always Allow This Script A parancsfájl engedélyezése mindig + Deny Elutasítás A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra. @@ -5043,8 +5050,6 @@ imageTrace Outline Körvonal @msg Script file could not be read A parancsfájlt nem sikerült beolvasni @msg Script folder has more than 2,048 entries A parancsfájlmappában 2048-nál több bejegyzés van @msg Script file open mode must be r, w, e or a A parancsfájl megnyitási módja r, w, e vagy a lehet -@msg Script file writing is not available A parancsfájlok írása nem érhető el -@msg Script file dialogs are not available A parancsfájlok fájlpárbeszédpanelei nem érhetők el @msg Script files cannot be opened in another application A parancsfájlok nem nyithatók meg másik alkalmazásban @msg Script file access is unavailable on the web A parancsfájlok elérése a weben nem érhető el @msg Script has 256 files open A parancsfájlnak 256 megnyitott fájlja van @@ -5115,6 +5120,27 @@ imageTrace Outline Körvonal @msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor @msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva +@msg Script file access denied: {path} A parancsfájl fájlhozzáférése megtagadva: {path} +@msg Script file access to the app's own folders is not allowed A parancsfájlok nem férhetnek hozzá az alkalmazás saját mappáihoz +@msg Script file cannot encode the text A parancsfájl fájlja nem tudja kódolni a szöveget +@msg Script file could not be written A parancsfájl fájlját nem sikerült írni +@msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia +@msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva +@msg Script file name is already in use A parancsfájl fájljának neve már használatban van +@msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen +@msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg +@msg Script file permission could not be saved A parancsfájl fájlengedélyét nem sikerült menteni +@msg Script folder is not empty A parancsfájl mappája nem üres +@msg Script files cannot make aliases A parancsfájl fájljai nem hozhatnak létre álneveket +@msg Script file hidden setting cannot be changed A parancsfájl fájljának rejtett beállítása nem módosítható +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: fájlpárbeszédpanel nem nyílhat meg beépített függvény, getter, átalakítás vagy a $.evalFile által futtatott fájl visszahívásán belül; hívja meg a parancsfájl saját kódjából +@msg the script wrote more file data than one run may write (32 MiB) a parancsfájl több fájladatot írt, mint amennyit egy futás írhat (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop a parancsfájl fájlpárbeszédpaneléhez tartozó `answer` értéke a következők egyike kell legyen: once, always, deny, stop +@msg choose a file or folder first, or deny először válasszon fájlt vagy mappát, vagy utasítsa el +@msg the script file permissions could not be saved: {e} a parancsfájlok fájlengedélyeit nem sikerült menteni: {e} +@msg this script's file access can be allowed only once ennek a parancsfájlnak a fájlhozzáférése csak egyszer engedélyezhető +@msg Only the person at the keyboard can allow a script's file access Parancsfájl fájlhozzáférését csak a billentyűzetnél ülő személy engedélyezheti +@msg A script is given at most 2,048 files: the files picked after them were left out Egy parancsfájl legfeljebb 2 048 fájlt kap: az ezek után kiválasztott fájlok kimaradtak @msg Corners edits the corners of a path a Sarkok parancs egy útvonal sarkait szerkeszti @msg could not decode image: {0} a kép nem dekódolható: {0} @msg Couldn't copy to the system clipboard: {e} Nem sikerült a rendszer vágólapjára másolni: {e} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e0ba31ecd5..b9b0d3e474 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4213,6 +4213,13 @@ imageTrace Outline Kontur Show External Script Warning Tampilkan Peringatan Skrip Eksternal A Script Is Running Skrip Sedang Berjalan Script Alert Peringatan Skrip + Script File Access Akses Berkas Skrip + The script asks to read a file you choose. Skrip meminta izin untuk membaca berkas yang Anda pilih. + The script asks to read and write a file you choose. Skrip meminta izin untuk membaca dan menulis berkas yang Anda pilih. + The script asks to read and write a folder you choose, with everything in it. Skrip meminta izin untuk membaca dan menulis folder yang Anda pilih, beserta seluruh isinya. + Allow Once Izinkan Sekali + Always Allow This Script Selalu Izinkan Skrip Ini + Deny Tolak A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. Do not show this warning again Jangan tampilkan peringatan ini lagi Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..0958a77ece 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4262,6 +4262,13 @@ axis Both Entrambi Show External Script Warning Mostra avviso per gli script esterni A Script Is Running È in esecuzione uno script Script Alert Avviso dello script + Script File Access Accesso dello script ai file + The script asks to read a file you choose. Lo script chiede di leggere un file che scegli. + The script asks to read and write a file you choose. Lo script chiede di leggere e scrivere un file che scegli. + The script asks to read and write a folder you choose, with everything in it. Lo script chiede di leggere e scrivere una cartella che scegli, con tutto il suo contenuto. + Allow Once Consenti una volta + Always Allow This Script Consenti sempre questo script + Deny Nega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. Do not show this warning again Non mostrare più questo avviso Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. @@ -4290,8 +4297,6 @@ axis Both Entrambi @msg Script file could not be read Impossibile leggere il file di script @msg Script folder has more than 2,048 entries La cartella di script contiene più di 2.048 voci @msg Script file open mode must be r, w, e or a La modalità di apertura del file di script deve essere r, w, e oppure a -@msg Script file writing is not available La scrittura dei file di script non è disponibile -@msg Script file dialogs are not available Le finestre di dialogo dei file di script non sono disponibili @msg Script files cannot be opened in another application I file di script non possono essere aperti in un'altra applicazione @msg Script file access is unavailable on the web L'accesso ai file di script non è disponibile sul web @msg Script has 256 files open Lo script ha 256 file aperti @@ -4362,6 +4367,27 @@ axis Both Entrambi @msg there is no script engine named {name} non esiste un motore di script chiamato {name} @msg Running a script Esecuzione di uno script @msg Copied the script report Rapporto dello script copiato +@msg Script file access denied: {path} Accesso dello script ai file negato: {path} +@msg Script file access to the app's own folders is not allowed L'accesso dello script alle cartelle dell'app non è consentito +@msg Script file cannot encode the text Il file dello script non può codificare il testo +@msg Script file could not be written Impossibile scrivere il file dello script +@msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda +@msg Script file is not open for writing Il file dello script non è aperto in scrittura +@msg Script file name is already in use Il nome del file dello script è già in uso +@msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella +@msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file +@msg Script file permission could not be saved Impossibile salvare il permesso sui file dello script +@msg Script folder is not empty La cartella dello script non è vuota +@msg Script files cannot make aliases I file dello script non possono creare alias +@msg Script file hidden setting cannot be changed L'impostazione nascosto del file dello script non può essere modificata +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: una finestra di dialogo dei file non può aprirsi in un callback di una funzione integrata, di un getter, di una conversione o di un file eseguito da $.evalFile; chiamala dal codice dello script stesso +@msg the script wrote more file data than one run may write (32 MiB) lo script ha scritto più dati di file di quanti ne possa scrivere un'esecuzione (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per la finestra di dialogo dei file di uno script deve essere uno tra: once, always, deny, stop +@msg choose a file or folder first, or deny scegli prima un file o una cartella, oppure nega +@msg the script file permissions could not be saved: {e} impossibile salvare i permessi sui file degli script: {e} +@msg this script's file access can be allowed only once l'accesso ai file di questo script può essere consentito solo una volta +@msg Only the person at the keyboard can allow a script's file access Solo la persona alla tastiera può consentire l’accesso ai file di uno script +@msg A script is given at most 2,048 files: the files picked after them were left out Uno script riceve al massimo 2.048 file: i file scelti dopo questi sono stati esclusi @msg Corners edits the corners of a path Angoli modifica gli angoli di un tracciato @msg Couldn't copy to the system clipboard: {e} Impossibile copiare negli appunti di sistema: {e} @msg Couldn't open {name}: {e} Impossibile aprire {name}: {e} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..c42b5453fb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5016,6 +5016,13 @@ swatch Bright Violet ビビッドバイオレット Show External Script Warning 外部スクリプトの警告を表示 A Script Is Running スクリプトの実行中 Script Alert スクリプトの通知 + Script File Access スクリプトのファイルアクセス + The script asks to read a file you choose. スクリプトが、選択したファイルの読み取りを求めています。 + The script asks to read and write a file you choose. スクリプトが、選択したファイルの読み書きを求めています。 + The script asks to read and write a folder you choose, with everything in it. スクリプトが、選択したフォルダーとその中身すべての読み書きを求めています。 + Allow Once 今回のみ許可 + Always Allow This Script このスクリプトを常に許可 + Deny 拒否 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 Do not show this warning again 今後この警告を表示しない Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 @@ -5044,8 +5051,6 @@ swatch Bright Violet ビビッドバイオレット @msg Script file could not be read スクリプトファイルを読み込めませんでした @msg Script folder has more than 2,048 entries スクリプトフォルダーの項目が 2,048 を超えています @msg Script file open mode must be r, w, e or a スクリプトファイルを開くモードは r、w、e、a のいずれかにしてください -@msg Script file writing is not available スクリプトファイルの書き込みは利用できません -@msg Script file dialogs are not available スクリプトファイルのダイアログは利用できません @msg Script files cannot be opened in another application スクリプトファイルを別のアプリケーションで開くことはできません @msg Script file access is unavailable on the web Web ではスクリプトファイルにアクセスできません @msg Script has 256 files open スクリプトが 256 個のファイルを開いています @@ -5116,6 +5121,27 @@ swatch Bright Violet ビビッドバイオレット @msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません @msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました +@msg Script file access denied: {path} スクリプトのファイルアクセスが拒否されました: {path} +@msg Script file access to the app's own folders is not allowed スクリプトからアプリ自身のフォルダーへのアクセスは許可されていません +@msg Script file cannot encode the text スクリプトのファイルでテキストをエンコードできません +@msg Script file could not be written スクリプトのファイルを書き込めませんでした +@msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です +@msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません +@msg Script file name is already in use スクリプトのファイル名はすでに使用されています +@msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください +@msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです +@msg Script file permission could not be saved スクリプトのファイルの許可を保存できませんでした +@msg Script folder is not empty スクリプトのフォルダーが空ではありません +@msg Script files cannot make aliases スクリプトのファイルではエイリアスを作成できません +@msg Script file hidden setting cannot be changed スクリプトのファイルの非表示設定は変更できません +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 組み込み関数、ゲッター、変換、または $.evalFile が実行するファイルのコールバック内ではファイルダイアログを開けません。スクリプト自身のコードから呼び出してください +@msg the script wrote more file data than one run may write (32 MiB) スクリプトが 1 回の実行で書き込める量を超えるファイルデータを書き込みました (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop スクリプトのファイルダイアログの `answer` は once、always、deny、stop のいずれかにしてください +@msg choose a file or folder first, or deny 先にファイルまたはフォルダーを選択するか、拒否してください +@msg the script file permissions could not be saved: {e} スクリプトのファイル許可を保存できませんでした: {e} +@msg this script's file access can be allowed only once このスクリプトのファイルアクセスは 1 回だけ許可できます +@msg Only the person at the keyboard can allow a script's file access スクリプトのファイルアクセスを許可できるのはキーボードの前にいる人だけです +@msg A script is given at most 2,048 files: the files picked after them were left out スクリプトに渡せるファイルは 2,048 個までのため、それ以降に選んだファイルは除外されました @msg Exported {path} {path} を書き出しました @msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください @msg unknown highlight `{h}` `{h}` は不明なハイライトの指定です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..f9a20f812c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5415,6 +5415,13 @@ imageTrace Outline კონტური Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება A Script Is Running სკრიპტი მუშაობს Script Alert სკრიპტის შეტყობინება + Script File Access სკრიპტის წვდომა ფაილებზე + The script asks to read a file you choose. სკრიპტი ითხოვს თქვენ მიერ არჩეული ფაილის წაკითხვას. + The script asks to read and write a file you choose. სკრიპტი ითხოვს თქვენ მიერ არჩეული ფაილის წაკითხვასა და ჩაწერას. + The script asks to read and write a folder you choose, with everything in it. სკრიპტი ითხოვს თქვენ მიერ არჩეული საქაღალდისა და მთელი მისი შიგთავსის წაკითხვასა და ჩაწერას. + Allow Once ერთხელ დაშვება + Always Allow This Script ამ სკრიპტის ყოველთვის დაშვება + Deny უარყოფა A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. Do not show this warning again აღარ აჩვენო ეს გაფრთხილება Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. @@ -5443,8 +5450,6 @@ imageTrace Outline კონტური @msg Script file could not be read სკრიპტის ფაილის წაკითხვა ვერ მოხერხდა @msg Script folder has more than 2,048 entries სკრიპტის საქაღალდეში 2048-ზე მეტი ჩანაწერია @msg Script file open mode must be r, w, e or a სკრიპტის ფაილის გახსნის რეჟიმი უნდა იყოს r, w, e ან a -@msg Script file writing is not available სკრიპტის ფაილების ჩაწერა მიუწვდომელია -@msg Script file dialogs are not available სკრიპტის ფაილის დიალოგები მიუწვდომელია @msg Script files cannot be opened in another application სკრიპტის ფაილების სხვა აპლიკაციაში გახსნა შეუძლებელია @msg Script file access is unavailable on the web ვებში სკრიპტის ფაილებზე წვდომა მიუწვდომელია @msg Script has 256 files open სკრიპტს 256 ფაილი აქვს გახსნილი @@ -5515,6 +5520,27 @@ imageTrace Outline კონტური @msg there is no script engine named {name} სკრიპტის ძრავა სახელით {name} არ არსებობს @msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში +@msg Script file access denied: {path} სკრიპტის წვდომა ფაილებზე უარყოფილია: {path} +@msg Script file access to the app's own folders is not allowed სკრიპტს არ აქვს აპის საკუთარ საქაღალდეებზე წვდომის უფლება +@msg Script file cannot encode the text სკრიპტის ფაილი ვერ აკოდირებს ტექსტს +@msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა +@msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს +@msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის +@msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება +@msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე +@msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის +@msg Script file permission could not be saved სკრიპტის ფაილების ნებართვის შენახვა ვერ მოხერხდა +@msg Script folder is not empty სკრიპტის საქაღალდე ცარიელი არ არის +@msg Script files cannot make aliases სკრიპტის ფაილებს არ შეუძლიათ ფსევდონიმების შექმნა +@msg Script file hidden setting cannot be changed სკრიპტის ფაილის დამალვის პარამეტრის შეცვლა შეუძლებელია +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ფაილის დიალოგი ვერ გაიხსნება ჩაშენებული ფუნქციის, getter-ის, გარდაქმნის ან $.evalFile-ის მიერ გაშვებული ფაილის callback-ში; გამოიძახეთ ის სკრიპტის საკუთარი კოდიდან +@msg the script wrote more file data than one run may write (32 MiB) სკრიპტმა ჩაწერა იმაზე მეტი ფაილის მონაცემი, ვიდრე ერთ გაშვებას შეუძლია ჩაწეროს (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop სკრიპტის ფაილის დიალოგისთვის `answer` უნდა იყოს ერთ-ერთი: once, always, deny, stop +@msg choose a file or folder first, or deny ჯერ აირჩიეთ ფაილი ან საქაღალდე, ან უარყავით +@msg the script file permissions could not be saved: {e} სკრიპტების ფაილების ნებართვების შენახვა ვერ მოხერხდა: {e} +@msg this script's file access can be allowed only once ამ სკრიპტის წვდომა ფაილებზე მხოლოდ ერთხელ შეიძლება დაიშვას +@msg Only the person at the keyboard can allow a script's file access სკრიპტის წვდომას ფაილებზე მხოლოდ კლავიატურასთან მყოფი ადამიანი უშვებს +@msg A script is given at most 2,048 files: the files picked after them were left out სკრიპტი იღებს მაქსიმუმ 2 048 ფაილს: მათ შემდეგ არჩეული ფაილები გამოტოვებულია @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ტრაექტორიის წანაცვლება: წანაცვლების შემდეგ მონიშნული ტრაექტორიებიდან არაფერი რჩება (შიგნით წანაცვლება ფიგურებზე დიდია) @msg {path}: not a file {path}: ფაილი არ არის Load EPS into Clipboard EPS-ის ბუფერში ჩატვირთვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..3d6d38ff44 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4943,6 +4943,13 @@ theme Appearance 외관 Show External Script Warning 외부 스크립트 경고 표시 A Script Is Running 스크립트 실행 중 Script Alert 스크립트 알림 + Script File Access 스크립트 파일 접근 + The script asks to read a file you choose. 스크립트가 선택한 파일을 읽도록 요청합니다. + The script asks to read and write a file you choose. 스크립트가 선택한 파일을 읽고 쓰도록 요청합니다. + The script asks to read and write a folder you choose, with everything in it. 스크립트가 선택한 폴더와 그 안의 모든 항목을 읽고 쓰도록 요청합니다. + Allow Once 한 번 허용 + Always Allow This Script 이 스크립트 항상 허용 + Deny 거부 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. Do not show this warning again 이 경고를 다시 표시하지 않음 Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. @@ -4971,8 +4978,6 @@ theme Appearance 외관 @msg Script file could not be read 스크립트 파일을 읽을 수 없습니다 @msg Script folder has more than 2,048 entries 스크립트 폴더의 항목이 2,048개를 초과합니다 @msg Script file open mode must be r, w, e or a 스크립트 파일 열기 모드는 r, w, e 또는 a여야 합니다 -@msg Script file writing is not available 스크립트 파일 쓰기를 사용할 수 없습니다 -@msg Script file dialogs are not available 스크립트 파일 대화 상자를 사용할 수 없습니다 @msg Script files cannot be opened in another application 스크립트 파일을 다른 응용 프로그램에서 열 수 없습니다 @msg Script file access is unavailable on the web 웹에서는 스크립트 파일에 접근할 수 없습니다 @msg Script has 256 files open 스크립트가 파일 256개를 열고 있습니다 @@ -5043,6 +5048,27 @@ theme Appearance 외관 @msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다 @msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 +@msg Script file access denied: {path} 스크립트 파일 접근이 거부되었습니다: {path} +@msg Script file access to the app's own folders is not allowed 스크립트는 앱 자체 폴더에 접근할 수 없습니다 +@msg Script file cannot encode the text 스크립트 파일이 텍스트를 인코딩할 수 없습니다 +@msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 +@msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 +@msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 +@msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 +@msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 +@msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 +@msg Script file permission could not be saved 스크립트 파일 권한을 저장할 수 없습니다 +@msg Script folder is not empty 스크립트 폴더가 비어 있지 않습니다 +@msg Script files cannot make aliases 스크립트 파일은 별칭을 만들 수 없습니다 +@msg Script file hidden setting cannot be changed 스크립트 파일의 숨김 설정을 변경할 수 없습니다 +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 기본 제공 함수, getter, 변환 또는 $.evalFile이 실행하는 파일의 콜백 안에서는 파일 대화 상자를 열 수 없습니다. 스크립트 자체 코드에서 호출하세요 +@msg the script wrote more file data than one run may write (32 MiB) 스크립트가 한 번의 실행에서 쓸 수 있는 것보다 많은 파일 데이터를 썼습니다(32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 스크립트 파일 대화 상자의 `answer`는 once, always, deny, stop 중 하나여야 합니다 +@msg choose a file or folder first, or deny 먼저 파일이나 폴더를 선택하거나 거부하세요 +@msg the script file permissions could not be saved: {e} 스크립트 파일 권한을 저장할 수 없습니다: {e} +@msg this script's file access can be allowed only once 이 스크립트의 파일 접근은 한 번만 허용할 수 있습니다 +@msg Only the person at the keyboard can allow a script's file access 스크립트의 파일 접근은 키보드 앞에 있는 사람만 허용할 수 있습니다 +@msg A script is given at most 2,048 files: the files picked after them were left out 스크립트에는 파일이 최대 2,048개까지 전달됩니다: 그 뒤에 고른 파일은 제외되었습니다 @msg Exported {path} {path}을(를) 내보냈습니다 @msg no CSS to copy: select objects with CSS of their own 복사할 CSS가 없습니다: 자체 CSS가 있는 개체를 선택하세요 @msg unknown highlight `{h}` 알 수 없는 강조 `{h}` diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b3388fa82a..6dea6dca40 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4227,6 +4227,13 @@ imageTrace Outline Contour Show External Script Warning Waarschuwing voor externe scripts tonen A Script Is Running Er wordt een script uitgevoerd Script Alert Scriptmelding + Script File Access Bestandstoegang van script + The script asks to read a file you choose. Het script vraagt een bestand te lezen dat u kiest. + The script asks to read and write a file you choose. Het script vraagt een bestand te lezen en te schrijven dat u kiest. + The script asks to read and write a folder you choose, with everything in it. Het script vraagt een map die u kiest te lezen en te schrijven, met alles wat erin staat. + Allow Once Eenmaal toestaan + Always Allow This Script Dit script altijd toestaan + Deny Weigeren A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. Do not show this warning again Deze waarschuwing niet meer tonen Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..d9fca7852c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4344,6 +4344,13 @@ imageTrace Outline Kontur Show External Script Warning Pokazuj ostrzeżenie o skryptach zewnętrznych A Script Is Running Skrypt jest uruchomiony Script Alert Komunikat skryptu + Script File Access Dostęp skryptu do plików + The script asks to read a file you choose. Skrypt prosi o odczyt wybranego przez Ciebie pliku. + The script asks to read and write a file you choose. Skrypt prosi o odczyt i zapis wybranego przez Ciebie pliku. + The script asks to read and write a folder you choose, with everything in it. Skrypt prosi o odczyt i zapis wybranego przez Ciebie folderu wraz z całą jego zawartością. + Allow Once Zezwól raz + Always Allow This Script Zawsze zezwalaj temu skryptowi + Deny Odmów A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. Do not show this warning again Nie pokazuj więcej tego ostrzeżenia Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. @@ -4372,8 +4379,6 @@ imageTrace Outline Kontur @msg Script file could not be read Nie udało się odczytać pliku skryptu @msg Script folder has more than 2,048 entries Folder skryptu ma więcej niż 2048 pozycji @msg Script file open mode must be r, w, e or a Tryb otwarcia pliku skryptu musi być r, w, e lub a -@msg Script file writing is not available Zapisywanie plików skryptu jest niedostępne -@msg Script file dialogs are not available Okna dialogowe plików skryptu są niedostępne @msg Script files cannot be opened in another application Plików skryptu nie można otworzyć w innej aplikacji @msg Script file access is unavailable on the web Dostęp do plików skryptu jest niedostępny w przeglądarce @msg Script has 256 files open Skrypt ma otwartych 256 plików @@ -4444,6 +4449,27 @@ imageTrace Outline Kontur @msg there is no script engine named {name} nie ma silnika skryptów o nazwie {name} @msg Running a script Uruchamianie skryptu @msg Copied the script report Skopiowano raport skryptu +@msg Script file access denied: {path} Odmówiono skryptowi dostępu do plików: {path} +@msg Script file access to the app's own folders is not allowed Skrypt nie ma dostępu do własnych folderów aplikacji +@msg Script file cannot encode the text Plik skryptu nie może zakodować tekstu +@msg Script file could not be written Nie można zapisać pliku skryptu +@msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie +@msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu +@msg Script file name is already in use Nazwa pliku skryptu jest już używana +@msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu +@msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku +@msg Script file permission could not be saved Nie można zapisać uprawnienia skryptu do plików +@msg Script folder is not empty Folder skryptu nie jest pusty +@msg Script files cannot make aliases Pliki skryptu nie mogą tworzyć aliasów +@msg Script file hidden setting cannot be changed Nie można zmienić ustawienia ukrycia pliku skryptu +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: okna dialogowego plików nie można otworzyć w wywołaniu zwrotnym funkcji wbudowanej, gettera, konwersji ani pliku uruchamianego przez $.evalFile; wywołaj je z własnego kodu skryptu +@msg the script wrote more file data than one run may write (32 MiB) skrypt zapisał więcej danych plików, niż może zapisać jedno uruchomienie (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` dla okna dialogowego plików skryptu musi być jedną z wartości: once, always, deny, stop +@msg choose a file or folder first, or deny najpierw wybierz plik lub folder albo odmów +@msg the script file permissions could not be saved: {e} nie można zapisać uprawnień skryptów do plików: {e} +@msg this script's file access can be allowed only once na dostęp tego skryptu do plików można zezwolić tylko raz +@msg Only the person at the keyboard can allow a script's file access Na dostęp skryptu do plików może zezwolić tylko osoba przy klawiaturze +@msg A script is given at most 2,048 files: the files picked after them were left out Skrypt otrzymuje najwyżej 2 048 plików: pliki wybrane po nich zostały pominięte @msg Corners edits the corners of a path Narożniki edytuje narożniki ścieżki @msg Couldn't copy to the system clipboard: {e} Nie udało się skopiować do schowka systemowego: {e} @msg Couldn't open {name}: {e} Nie udało się otworzyć {name}: {e} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..030c073639 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5225,6 +5225,13 @@ axis Both Ambos Show External Script Warning Mostrar aviso de scripts externos A Script Is Running Um script está em execução Script Alert Alerta do script + Script File Access Acesso do script a arquivos + The script asks to read a file you choose. O script pede para ler um arquivo que você escolher. + The script asks to read and write a file you choose. O script pede para ler e gravar um arquivo que você escolher. + The script asks to read and write a folder you choose, with everything in it. O script pede para ler e gravar uma pasta que você escolher, com todo o seu conteúdo. + Allow Once Permitir uma vez + Always Allow This Script Sempre permitir este script + Deny Negar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. Do not show this warning again Não mostrar este aviso novamente Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. @@ -5253,8 +5260,6 @@ axis Both Ambos @msg Script file could not be read Não foi possível ler o arquivo de script @msg Script folder has more than 2,048 entries A pasta de script tem mais de 2.048 entradas @msg Script file open mode must be r, w, e or a O modo de abertura do arquivo de script deve ser r, w, e ou a -@msg Script file writing is not available A gravação de arquivos de script não está disponível -@msg Script file dialogs are not available As caixas de diálogo de arquivos de script não estão disponíveis @msg Script files cannot be opened in another application Arquivos de script não podem ser abertos em outro aplicativo @msg Script file access is unavailable on the web O acesso a arquivos de script não está disponível na web @msg Script has 256 files open O script tem 256 arquivos abertos @@ -5325,6 +5330,27 @@ axis Both Ambos @msg there is no script engine named {name} não há nenhum mecanismo de script chamado {name} @msg Running a script Executando um script @msg Copied the script report Relatório do script copiado +@msg Script file access denied: {path} Acesso do script a arquivos negado: {path} +@msg Script file access to the app's own folders is not allowed O script não pode acessar as pastas do próprio aplicativo +@msg Script file cannot encode the text O arquivo do script não consegue codificar o texto +@msg Script file could not be written Não foi possível gravar o arquivo do script +@msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las +@msg Script file is not open for writing O arquivo do script não está aberto para gravação +@msg Script file name is already in use O nome do arquivo do script já está em uso +@msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta +@msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo +@msg Script file permission could not be saved Não foi possível salvar a permissão de arquivos do script +@msg Script folder is not empty A pasta do script não está vazia +@msg Script files cannot make aliases Os arquivos do script não podem criar aliases +@msg Script file hidden setting cannot be changed A configuração de oculto do arquivo do script não pode ser alterada +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: uma caixa de diálogo de arquivo não pode abrir dentro de um callback de uma função integrada, de um getter, de uma conversão ou de um arquivo que $.evalFile executa; chame-a a partir do próprio código do script +@msg the script wrote more file data than one run may write (32 MiB) o script gravou mais dados de arquivo do que uma execução pode gravar (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para a caixa de diálogo de arquivo de um script deve ser um destes: once, always, deny, stop +@msg choose a file or folder first, or deny escolha primeiro um arquivo ou uma pasta, ou negue +@msg the script file permissions could not be saved: {e} não foi possível salvar as permissões de arquivos dos scripts: {e} +@msg this script's file access can be allowed only once o acesso a arquivos deste script só pode ser permitido uma vez +@msg Only the person at the keyboard can allow a script's file access Somente a pessoa ao teclado pode permitir o acesso a arquivos de um script +@msg A script is given at most 2,048 files: the files picked after them were left out Um script recebe no máximo 2.048 arquivos: os arquivos escolhidos depois deles foram deixados de fora @msg This shortcut file is in a form VectorCraft can't read. Este arquivo de atalhos está em um formato que o VectorCraft não consegue ler. @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve ser "vertical", "horizontal" ou um ângulo em graus, não `{v}` @msg give corners of the path: anchors where its sides meet at an angle informe os cantos do caminho: pontos de ancoragem onde os lados se encontram em ângulo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..c18c366da1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4248,6 +4248,13 @@ axis Both Оба Show External Script Warning Показывать предупреждение о внешних скриптах A Script Is Running Выполняется скрипт Script Alert Сообщение скрипта + Script File Access Доступ скрипта к файлам + The script asks to read a file you choose. Скрипт запрашивает чтение выбранного вами файла. + The script asks to read and write a file you choose. Скрипт запрашивает чтение и запись выбранного вами файла. + The script asks to read and write a folder you choose, with everything in it. Скрипт запрашивает чтение и запись выбранной вами папки со всем её содержимым. + Allow Once Разрешить один раз + Always Allow This Script Всегда разрешать этот скрипт + Deny Запретить A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. Do not show this warning again Больше не показывать это предупреждение Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. @@ -4276,8 +4283,6 @@ axis Both Оба @msg Script file could not be read Не удалось прочитать файл скрипта @msg Script folder has more than 2,048 entries В папке скрипта больше 2048 элементов @msg Script file open mode must be r, w, e or a Режим открытия файла скрипта должен быть r, w, e или a -@msg Script file writing is not available Запись файлов скрипта недоступна -@msg Script file dialogs are not available Диалоговые окна файлов скрипта недоступны @msg Script files cannot be opened in another application Файлы скрипта нельзя открыть в другом приложении @msg Script file access is unavailable on the web Доступ к файлам скрипта в веб-версии недоступен @msg Script has 256 files open У скрипта открыто 256 файлов @@ -4348,6 +4353,27 @@ axis Both Оба @msg there is no script engine named {name} движка скриптов с именем {name} нет @msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован +@msg Script file access denied: {path} Доступ скрипта к файлам запрещён: {path} +@msg Script file access to the app's own folders is not allowed Скрипту не разрешён доступ к собственным папкам приложения +@msg Script file cannot encode the text Файл скрипта не может закодировать текст +@msg Script file could not be written Не удалось записать файл скрипта +@msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек +@msg Script file is not open for writing Файл скрипта не открыт для записи +@msg Script file name is already in use Имя файла скрипта уже используется +@msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки +@msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла +@msg Script file permission could not be saved Не удалось сохранить разрешение скрипта на файлы +@msg Script folder is not empty Папка скрипта не пуста +@msg Script files cannot make aliases Файлы скрипта не могут создавать псевдонимы +@msg Script file hidden setting cannot be changed Нельзя изменить параметр скрытости файла скрипта +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: файловый диалог нельзя открыть внутри обратного вызова встроенной функции, геттера, преобразования или файла, который выполняет $.evalFile; вызовите его из собственного кода скрипта +@msg the script wrote more file data than one run may write (32 MiB) скрипт записал больше данных файлов, чем может записать один запуск (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового диалога скрипта должен быть одним из: once, always, deny, stop +@msg choose a file or folder first, or deny сначала выберите файл или папку либо откажите +@msg the script file permissions could not be saved: {e} не удалось сохранить разрешения скриптов на файлы: {e} +@msg this script's file access can be allowed only once доступ этого скрипта к файлам можно разрешить только один раз +@msg Only the person at the keyboard can allow a script's file access Разрешить скрипту доступ к файлам может только человек за клавиатурой +@msg A script is given at most 2,048 files: the files picked after them were left out Скрипт получает не больше 2 048 файлов: файлы, выбранные после них, пропущены @msg Corners edits the corners of a path «Углы» редактирует углы контура @msg Couldn't copy to the system clipboard: {e} Не удалось скопировать в системный буфер обмена: {e} @msg Couldn't open {name}: {e} Не удалось открыть {name}: {e} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..0331bdbd36 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4121,6 +4121,13 @@ axis Both Båda Show External Script Warning Visa varning för externa skript A Script Is Running Ett skript körs Script Alert Skriptmeddelande + Script File Access Skriptets filåtkomst + The script asks to read a file you choose. Skriptet ber om att läsa en fil som du väljer. + The script asks to read and write a file you choose. Skriptet ber om att läsa och skriva en fil som du väljer. + The script asks to read and write a folder you choose, with everything in it. Skriptet ber om att läsa och skriva en mapp som du väljer, med allt innehåll. + Allow Once Tillåt en gång + Always Allow This Script Tillåt alltid det här skriptet + Deny Neka A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. Do not show this warning again Visa inte den här varningen igen Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. @@ -4149,8 +4156,6 @@ axis Both Båda @msg Script file could not be read Skriptfilen kunde inte läsas @msg Script folder has more than 2,048 entries Skriptmappen har fler än 2 048 poster @msg Script file open mode must be r, w, e or a Skriptfilens öppningsläge måste vara r, w, e eller a -@msg Script file writing is not available Skrivning av skriptfiler är inte tillgänglig -@msg Script file dialogs are not available Fildialogrutor för skript är inte tillgängliga @msg Script files cannot be opened in another application Skriptfiler kan inte öppnas i ett annat program @msg Script file access is unavailable on the web Åtkomst till skriptfiler är inte tillgänglig på webben @msg Script has 256 files open Skriptet har 256 filer öppna @@ -4221,6 +4226,27 @@ axis Both Båda @msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name} @msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten +@msg Script file access denied: {path} Skriptets filåtkomst nekades: {path} +@msg Script file access to the app's own folders is not allowed Skript får inte komma åt appens egna mappar +@msg Script file cannot encode the text Skriptets fil kan inte koda texten +@msg Script file could not be written Skriptets fil kunde inte skrivas +@msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem +@msg Script file is not open for writing Skriptets fil är inte öppen för skrivning +@msg Script file name is already in use Namnet på skriptets fil används redan +@msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp +@msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil +@msg Script file permission could not be saved Skriptets filbehörighet kunde inte sparas +@msg Script folder is not empty Skriptets mapp är inte tom +@msg Script files cannot make aliases Skriptets filer kan inte skapa alias +@msg Script file hidden setting cannot be changed Inställningen för dold för skriptets fil kan inte ändras +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en fildialog kan inte öppnas i ett återanrop från en inbyggd funktion, en getter, en konvertering eller en fil som $.evalFile kör; anropa den från skriptets egen kod +@msg the script wrote more file data than one run may write (32 MiB) skriptet skrev mer fildata än en körning får skriva (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` för ett skripts fildialog måste vara ett av: once, always, deny, stop +@msg choose a file or folder first, or deny välj först en fil eller mapp, eller neka +@msg the script file permissions could not be saved: {e} skriptens filbehörigheter kunde inte sparas: {e} +@msg this script's file access can be allowed only once det här skriptets filåtkomst kan bara tillåtas en gång +@msg Only the person at the keyboard can allow a script's file access Bara personen vid tangentbordet kan tillåta ett skripts filåtkomst +@msg A script is given at most 2,048 files: the files picked after them were left out Ett skript får högst 2 048 filer: filerna som valdes efter dem utelämnades @msg Corners edits the corners of a path Hörn redigerar hörnen på en bana @msg Couldn't copy to the system clipboard: {e} Kunde inte kopiera till systemets urklipp: {e} @msg Couldn't open {name}: {e} Kunde inte öppna {name}: {e} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 66caa1c3a4..b1e61e080e 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1739,6 +1739,68 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() { } } +/// The errors a script's `File` and `Folder` objects and file dialogs give, and those of the +/// commands that answer the dialogs and keep their permissions, have a translated row in every +/// complete-message language. Each one in the first list is still a message the source gives; the +/// second list holds the note the file dialog shows when it left out picked files, and texts a +/// script reads only from a File or Folder object's `error`. +#[test] +fn script_file_messages_translate_in_every_complete_message_language() { + const SCANNED: &[&str] = &[ + "Script file access denied", + "Script file access denied: {path}", + "Script file access is unavailable on the web", + "Script file access to the app's own folders is not allowed", + "Script file cannot be decoded", + "Script file cannot encode the text", + "Script file could not be read", + "Script file could not be written", + "Script file dialogs need a person to answer them", + "Script file does not exist", + "Script file exceeds 8 MiB", + "Script file is not a regular file", + "Script file is not open", + "Script file is not open for writing", + "Script file name is already in use", + "Script file name must be a name without a folder", + "Script file path exceeds 32,767 characters", + "Script file permission can be kept only for a script run from a file", + "Script file permission could not be saved", + "Script files cannot be opened in another application", + "Script folder has more than 2,048 entries", + "Script folder mask takes too many steps to match", + "{name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code", + "the script opened more file data than one run may open (32 MiB)", + "the script wrote more file data than one run may write (32 MiB)", + "`answer` for a script's file dialog must be one of: once, always, deny, stop", + "choose a file or folder first, or deny", + "the script file permissions could not be saved: {e}", + "this script's file access can be allowed only once", + "Only the person at the keyboard can allow a script's file access", + ]; + const ERROR_ONLY: &[&str] = &[ + "A script is given at most 2,048 files: the files picked after them were left out", + "Script file open mode must be r, w, e or a", + "Script has 256 files open", + "Script folder is not empty", + "Script files cannot make aliases", + "Script file hidden setting cannot be changed", + ]; + let messages = message_literals(); + let gone: Vec<&&str> = SCANNED.iter().filter(|m| !messages.contains(**m)).collect(); + assert!(gone.is_empty(), "no longer messages in the source: {gone:?}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + for m in SCANNED.iter().chain(ERROR_ONLY) { + let row = entries.iter().find(|(ctx, src, _)| ctx == "@msg" && src == m); + assert!(row.is_some_and(|(_, src, tr)| tr != src), "{code}: no translated row for {m:?}"); + } + } + let de = Lang::from_code("de").expect("de registered"); + assert_eq!(message(de, "Script file access denied: C:/x/a.txt"), "Dateizugriff des Skripts verweigert: C:/x/a.txt"); +} + #[test] fn package_status_message_templates_parse() { let c = Catalog::parse(concat!( @@ -2532,8 +2594,8 @@ fn script_errors_are_translated() { "Script file could not be read", "Script folder has more than 2,048 entries", "Script file open mode must be r, w, e or a", - "Script file writing is not available", - "Script file dialogs are not available", + "Script file is not open for writing", + "Script file dialogs need a person to answer them", "Script files cannot be opened in another application", "Script file access is unavailable on the web", "Script has 256 files open", diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..f4df32faee 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4001,6 +4001,13 @@ axis Both Her İkisi Show External Script Warning Harici Betik Uyarısını Göster A Script Is Running Bir Betik Çalışıyor Script Alert Betik Uyarısı + Script File Access Betik Dosya Erişimi + The script asks to read a file you choose. Betik, seçtiğiniz bir dosyayı okumak için izin istiyor. + The script asks to read and write a file you choose. Betik, seçtiğiniz bir dosyayı okumak ve yazmak için izin istiyor. + The script asks to read and write a folder you choose, with everything in it. Betik, seçtiğiniz bir klasörü içindeki her şeyle birlikte okumak ve yazmak için izin istiyor. + Allow Once Bir Kez İzin Ver + Always Allow This Script Bu Betiğe Her Zaman İzin Ver + Deny Reddet A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. Do not show this warning again Bu uyarıyı bir daha gösterme Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın. @@ -4029,8 +4036,6 @@ axis Both Her İkisi @msg Script file could not be read Betik dosyası okunamadı @msg Script folder has more than 2,048 entries Betik klasöründe 2.048'den fazla öğe var @msg Script file open mode must be r, w, e or a Betik dosyası açma modu r, w, e veya a olmalıdır -@msg Script file writing is not available Betik dosyası yazma kullanılamıyor -@msg Script file dialogs are not available Betik dosyası iletişim kutuları kullanılamıyor @msg Script files cannot be opened in another application Betik dosyaları başka bir uygulamada açılamaz @msg Script file access is unavailable on the web Betik dosyası erişimi web'de kullanılamıyor @msg Script has 256 files open Betiğin 256 açık dosyası var @@ -4101,6 +4106,27 @@ axis Both Her İkisi @msg there is no script engine named {name} {name} adlı bir betik motoru yok @msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı +@msg Script file access denied: {path} Betiğin dosya erişimi reddedildi: {path} +@msg Script file access to the app's own folders is not allowed Betiklerin uygulamanın kendi klasörlerine erişmesine izin verilmez +@msg Script file cannot encode the text Betiğin dosyası metni kodlayamıyor +@msg Script file could not be written Betiğin dosyası yazılamadı +@msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir +@msg Script file is not open for writing Betiğin dosyası yazmak için açık değil +@msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor +@msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır +@msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir +@msg Script file permission could not be saved Betiğin dosya izni kaydedilemedi +@msg Script folder is not empty Betiğin klasörü boş değil +@msg Script files cannot make aliases Betiğin dosyaları takma ad oluşturamaz +@msg Script file hidden setting cannot be changed Betiğin dosyasının gizli ayarı değiştirilemez +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dosya iletişim kutusu yerleşik bir işlevin, bir getter'ın, bir dönüştürmenin veya $.evalFile'ın çalıştırdığı bir dosyanın geri çağrısı içinde açılamaz; onu betiğin kendi kodundan çağırın +@msg the script wrote more file data than one run may write (32 MiB) betik, bir çalıştırmanın yazabileceğinden fazla dosya verisi yazdı (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop bir betiğin dosya iletişim kutusu için `answer` şunlardan biri olmalıdır: once, always, deny, stop +@msg choose a file or folder first, or deny önce bir dosya veya klasör seçin ya da reddedin +@msg the script file permissions could not be saved: {e} betiklerin dosya izinleri kaydedilemedi: {e} +@msg this script's file access can be allowed only once bu betiğin dosya erişimine yalnızca bir kez izin verilebilir +@msg Only the person at the keyboard can allow a script's file access Bir betiğin dosya erişimine yalnızca klavye başındaki kişi izin verebilir +@msg A script is given at most 2,048 files: the files picked after them were left out Bir betiğe en fazla 2.048 dosya verilir: bunlardan sonra seçilen dosyalar dışarıda bırakıldı @msg Corners edits the corners of a path Köşeler bir yolun köşelerini düzenler @msg Couldn't copy to the system clipboard: {e} Sistem panosuna kopyalanamadı: {e} @msg Couldn't open {name}: {e} {name} açılamadı: {e} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..219a79d05e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4246,6 +4246,13 @@ axis Both Обидві Show External Script Warning Показувати попередження про зовнішні скрипти A Script Is Running Виконується скрипт Script Alert Повідомлення скрипту + Script File Access Доступ скрипту до файлів + The script asks to read a file you choose. Скрипт просить дозволу прочитати вибраний вами файл. + The script asks to read and write a file you choose. Скрипт просить дозволу читати й записувати вибраний вами файл. + The script asks to read and write a folder you choose, with everything in it. Скрипт просить дозволу читати й записувати вибрану вами папку з усім її вмістом. + Allow Once Дозволити один раз + Always Allow This Script Завжди дозволяти цей скрипт + Deny Заборонити A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. Do not show this warning again Більше не показувати це попередження Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. @@ -4274,8 +4281,6 @@ axis Both Обидві @msg Script file could not be read Не вдалося прочитати файл скрипта @msg Script folder has more than 2,048 entries Тека скрипта має понад 2048 елементів @msg Script file open mode must be r, w, e or a Режим відкриття файлу скрипта має бути r, w, e або a -@msg Script file writing is not available Запис файлів скрипта недоступний -@msg Script file dialogs are not available Діалогові вікна файлів скрипта недоступні @msg Script files cannot be opened in another application Файли скрипта не можна відкрити в іншому застосунку @msg Script file access is unavailable on the web Доступ до файлів скрипта у вебверсії недоступний @msg Script has 256 files open Скрипт має 256 відкритих файлів @@ -4346,6 +4351,27 @@ axis Both Обидві @msg there is no script engine named {name} рушія скриптів з назвою {name} немає @msg Running a script Виконується скрипт @msg Copied the script report Звіт про сценарій скопійовано +@msg Script file access denied: {path} Доступ скрипту до файлів заборонено: {path} +@msg Script file access to the app's own folders is not allowed Скрипту не дозволено доступ до власних папок застосунку +@msg Script file cannot encode the text Файл скрипту не може закодувати текст +@msg Script file could not be written Не вдалося записати файл скрипту +@msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина +@msg Script file is not open for writing Файл скрипту не відкрито для запису +@msg Script file name is already in use Ім’я файлу скрипту вже використовується +@msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки +@msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу +@msg Script file permission could not be saved Не вдалося зберегти дозвіл скрипту на файли +@msg Script folder is not empty Папка скрипту не порожня +@msg Script files cannot make aliases Файли скрипту не можуть створювати псевдоніми +@msg Script file hidden setting cannot be changed Не можна змінити параметр прихованості файлу скрипту +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: файловий діалог не можна відкрити всередині зворотного виклику вбудованої функції, гетера, перетворення або файлу, який виконує $.evalFile; викличте його з власного коду скрипту +@msg the script wrote more file data than one run may write (32 MiB) скрипт записав більше даних файлів, ніж може записати один запуск (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового діалогу скрипту має бути одним із: once, always, deny, stop +@msg choose a file or folder first, or deny спершу виберіть файл або папку чи відмовте +@msg the script file permissions could not be saved: {e} не вдалося зберегти дозволи скриптів на файли: {e} +@msg this script's file access can be allowed only once доступ цього скрипту до файлів можна дозволити лише один раз +@msg Only the person at the keyboard can allow a script's file access Дозволити скрипту доступ до файлів може лише людина за клавіатурою +@msg A script is given at most 2,048 files: the files picked after them were left out Скрипт отримує щонайбільше 2 048 файлів: файли, вибрані після них, пропущено @msg Corners edits the corners of a path «Кути» редагує кути контуру @msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e} @msg Couldn't open {name}: {e} Не вдалося відкрити {name}: {e} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..d9e307c7f4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4672,6 +4672,13 @@ theme Appearance Giao diện Show External Script Warning Hiện cảnh báo tập lệnh bên ngoài A Script Is Running Một tập lệnh đang chạy Script Alert Thông báo của tập lệnh + Script File Access Quyền truy cập tệp của tập lệnh + The script asks to read a file you choose. Tập lệnh yêu cầu đọc một tệp bạn chọn. + The script asks to read and write a file you choose. Tập lệnh yêu cầu đọc và ghi một tệp bạn chọn. + The script asks to read and write a folder you choose, with everything in it. Tập lệnh yêu cầu đọc và ghi một thư mục bạn chọn, cùng mọi thứ bên trong. + Allow Once Cho phép một lần + Always Allow This Script Luôn cho phép tập lệnh này + Deny Từ chối A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. Do not show this warning again Không hiện lại cảnh báo này Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại. @@ -4700,8 +4707,6 @@ theme Appearance Giao diện @msg Script file could not be read Không thể đọc tệp tập lệnh @msg Script folder has more than 2,048 entries Thư mục tập lệnh có hơn 2.048 mục @msg Script file open mode must be r, w, e or a Chế độ mở tệp tập lệnh phải là r, w, e hoặc a -@msg Script file writing is not available Không thể ghi tệp tập lệnh -@msg Script file dialogs are not available Không có hộp thoại tệp cho tập lệnh @msg Script files cannot be opened in another application Không thể mở tệp tập lệnh trong ứng dụng khác @msg Script file access is unavailable on the web Không thể truy cập tệp tập lệnh trên web @msg Script has 256 files open Tập lệnh đang mở 256 tệp @@ -4772,6 +4777,27 @@ theme Appearance Giao diện @msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name} @msg Running a script Đang chạy tập lệnh @msg Copied the script report Đã sao chép báo cáo script +@msg Script file access denied: {path} Quyền truy cập tệp của tập lệnh bị từ chối: {path} +@msg Script file access to the app's own folders is not allowed Tập lệnh không được phép truy cập các thư mục riêng của ứng dụng +@msg Script file cannot encode the text Tệp của tập lệnh không thể mã hóa văn bản +@msg Script file could not be written Không thể ghi tệp của tập lệnh +@msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời +@msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi +@msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng +@msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục +@msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp +@msg Script file permission could not be saved Không thể lưu quyền truy cập tệp của tập lệnh +@msg Script folder is not empty Thư mục của tập lệnh không trống +@msg Script files cannot make aliases Tệp của tập lệnh không thể tạo bí danh +@msg Script file hidden setting cannot be changed Không thể thay đổi cài đặt ẩn của tệp tập lệnh +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: không thể mở hộp thoại tệp bên trong callback của hàm dựng sẵn, getter, phép chuyển đổi hoặc tệp mà $.evalFile chạy; hãy gọi nó từ mã riêng của tập lệnh +@msg the script wrote more file data than one run may write (32 MiB) tập lệnh đã ghi nhiều dữ liệu tệp hơn mức một lần chạy được phép ghi (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` cho hộp thoại tệp của tập lệnh phải là một trong: once, always, deny, stop +@msg choose a file or folder first, or deny hãy chọn một tệp hoặc thư mục trước, hoặc từ chối +@msg the script file permissions could not be saved: {e} không thể lưu quyền truy cập tệp của các tập lệnh: {e} +@msg this script's file access can be allowed only once quyền truy cập tệp của tập lệnh này chỉ có thể được cho phép một lần +@msg Only the person at the keyboard can allow a script's file access Chỉ người ngồi tại bàn phím mới có thể cho phép tập lệnh truy cập tệp +@msg A script is given at most 2,048 files: the files picked after them were left out Một tập lệnh nhận tối đa 2.048 tệp: các tệp được chọn sau đó đã bị bỏ qua @msg Corners edits the corners of a path Corners chỉnh sửa các góc của đường dẫn @msg could not decode image: {0} không thể giải mã ảnh: {0} @msg Couldn't copy to the system clipboard: {e} Không thể sao chép vào khay nhớ tạm hệ thống: {e} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..4f7d745e25 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4704,6 +4704,13 @@ imageTrace Outline 轮廓 Show External Script Warning 显示外部脚本警告 A Script Is Running 脚本正在运行 Script Alert 脚本提示 + Script File Access 脚本文件访问 + The script asks to read a file you choose. 脚本请求读取您选择的文件。 + The script asks to read and write a file you choose. 脚本请求读写您选择的文件。 + The script asks to read and write a folder you choose, with everything in it. 脚本请求读写您选择的文件夹及其中的所有内容。 + Allow Once 允许一次 + Always Allow This Script 始终允许此脚本 + Deny 拒绝 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 Do not show this warning again 不再显示此警告 Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 @@ -4732,8 +4739,6 @@ imageTrace Outline 轮廓 @msg Script file could not be read 无法读取脚本文件 @msg Script folder has more than 2,048 entries 脚本文件夹的条目超过 2,048 个 @msg Script file open mode must be r, w, e or a 脚本文件的打开模式必须是 r、w、e 或 a -@msg Script file writing is not available 脚本文件写入不可用 -@msg Script file dialogs are not available 脚本文件对话框不可用 @msg Script files cannot be opened in another application 脚本文件无法在其他应用程序中打开 @msg Script file access is unavailable on the web 网页版无法访问脚本文件 @msg Script has 256 files open 脚本已打开 256 个文件 @@ -4804,6 +4809,27 @@ imageTrace Outline 轮廓 @msg there is no script engine named {name} 没有名为 {name} 的脚本引擎 @msg Running a script 正在运行脚本 @msg Copied the script report 已复制脚本报告 +@msg Script file access denied: {path} 脚本的文件访问被拒绝:{path} +@msg Script file access to the app's own folders is not allowed 不允许脚本访问应用自身的文件夹 +@msg Script file cannot encode the text 脚本的文件无法编码该文本 +@msg Script file could not be written 无法写入脚本的文件 +@msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 +@msg Script file is not open for writing 脚本的文件未以写入方式打开 +@msg Script file name is already in use 脚本的文件名已被使用 +@msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 +@msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 +@msg Script file permission could not be saved 无法保存脚本的文件权限 +@msg Script folder is not empty 脚本的文件夹不为空 +@msg Script files cannot make aliases 脚本的文件无法创建别名 +@msg Script file hidden setting cannot be changed 无法更改脚本文件的隐藏设置 +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:文件对话框不能在内置函数、getter、转换或 $.evalFile 运行的文件的回调中打开;请从脚本自身的代码中调用 +@msg the script wrote more file data than one run may write (32 MiB) 脚本写入的文件数据超过了一次运行可写入的上限 (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 脚本文件对话框的 `answer` 必须是以下之一:once、always、deny、stop +@msg choose a file or folder first, or deny 请先选择文件或文件夹,或拒绝 +@msg the script file permissions could not be saved: {e} 无法保存脚本的文件权限:{e} +@msg this script's file access can be allowed only once 此脚本的文件访问只能允许一次 +@msg Only the person at the keyboard can allow a script's file access 只有键盘前的人才能允许脚本访问文件 +@msg A script is given at most 2,048 files: the files picked after them were left out 脚本最多获得 2,048 个文件:之后选择的文件已被略去 @msg Exported {path} 已导出 {path} @msg no CSS to copy: select objects with CSS of their own 没有可复制的 CSS:请选择带有自身 CSS 的对象 @msg unknown highlight `{h}` 未知的高亮显示 `{h}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..a1d90936f3 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2471,6 +2471,13 @@ file-filter Templates 範本 Show External Script Warning 顯示外部指令碼警告 A Script Is Running 指令碼正在執行 Script Alert 指令碼提示 + Script File Access 指令碼檔案存取 + The script asks to read a file you choose. 指令碼要求讀取您選擇的檔案。 + The script asks to read and write a file you choose. 指令碼要求讀寫您選擇的檔案。 + The script asks to read and write a folder you choose, with everything in it. 指令碼要求讀寫您選擇的資料夾及其中的所有內容。 + Allow Once 允許一次 + Always Allow This Script 一律允許此指令碼 + Deny 拒絕 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 Do not show this warning again 不再顯示此警告 Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 @@ -2499,8 +2506,6 @@ file-filter Templates 範本 @msg Script file could not be read 無法讀取指令碼檔案 @msg Script folder has more than 2,048 entries 指令碼資料夾的項目超過 2,048 個 @msg Script file open mode must be r, w, e or a 指令碼檔案的開啟模式必須是 r、w、e 或 a -@msg Script file writing is not available 無法使用指令碼檔案寫入 -@msg Script file dialogs are not available 無法使用指令碼檔案對話方塊 @msg Script files cannot be opened in another application 指令碼檔案無法在其他應用程式中開啟 @msg Script file access is unavailable on the web 網頁版無法存取指令碼檔案 @msg Script has 256 files open 指令碼已開啟 256 個檔案 @@ -2571,6 +2576,27 @@ file-filter Templates 範本 @msg there is no script engine named {name} 沒有名為 {name} 的指令碼引擎 @msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 +@msg Script file access denied: {path} 指令碼的檔案存取遭拒:{path} +@msg Script file access to the app's own folders is not allowed 不允許指令碼存取應用程式本身的資料夾 +@msg Script file cannot encode the text 指令碼的檔案無法編碼該文字 +@msg Script file could not be written 無法寫入指令碼的檔案 +@msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 +@msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 +@msg Script file name is already in use 指令碼的檔案名稱已在使用中 +@msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 +@msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 +@msg Script file permission could not be saved 無法儲存指令碼的檔案權限 +@msg Script folder is not empty 指令碼的資料夾不是空的 +@msg Script files cannot make aliases 指令碼的檔案無法建立別名 +@msg Script file hidden setting cannot be changed 無法變更指令碼檔案的隱藏設定 +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:檔案對話框無法在內建函式、getter、轉換或 $.evalFile 執行的檔案的回呼中開啟;請從指令碼本身的程式碼中呼叫 +@msg the script wrote more file data than one run may write (32 MiB) 指令碼寫入的檔案資料超過一次執行可寫入的上限 (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 指令碼檔案對話框的 `answer` 必須是下列之一:once、always、deny、stop +@msg choose a file or folder first, or deny 請先選擇檔案或資料夾,或拒絕 +@msg the script file permissions could not be saved: {e} 無法儲存指令碼的檔案權限:{e} +@msg this script's file access can be allowed only once 此指令碼的檔案存取只能允許一次 +@msg Only the person at the keyboard can allow a script's file access 只有鍵盤前的人才能允許指令碼存取檔案 +@msg A script is given at most 2,048 files: the files picked after them were left out 指令碼最多取得 2,048 個檔案:之後選擇的檔案已略去 @msg Exported {path} 已匯出 {path} @msg no CSS to copy: select objects with CSS of their own 沒有可複製的 CSS:請選取有自己 CSS 的物件 @msg unknown highlight `{h}` 未知的反白顯示 `{h}` diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c4c6ded189..17fcb312ca 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -329,6 +329,11 @@ pub struct VectorcraftApp { /// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) pending_plugin_install: Option, + /// The paths Choose… picked in a script's file dialog, kept out of the dialog's fields, which + /// `ui.dialog.set` writes. + pub(crate) script_picked: Vec, + /// Choose… left out files past the most a script is given. + pub(crate) script_picked_left_out: bool, /// The pen end the canvas saw last and the tool its eraser end stands in for /// ([`stylus::sync_eraser_tool`]). pub(crate) pen_end: stylus::PenEnd, diff --git a/crates/ui-egui/src/picks.rs b/crates/ui-egui/src/picks.rs index ea1b51e049..694fc0e6d7 100644 --- a/crates/ui-egui/src/picks.rs +++ b/crates/ui-egui/src/picks.rs @@ -32,10 +32,14 @@ pub enum PickRequest { Open(FilePick), /// An open dialog for files to place. OpenMany, + /// An open dialog for several files of the pick's types. + OpenFiles(FilePick), /// A save dialog. Save(FilePick), /// A folder picker. Folder, + /// A folder picker that starts in the folder given. + FolderAt(String), } /// The paths a dialog shown off the UI thread picked (none: cancelled). A save dialog that reports @@ -192,10 +196,10 @@ impl Picks { /// The kind of dialog open off the UI thread (`ui.inspect`'s `fileDialog`). pub(crate) fn waiting_kind(&self) -> Option<&'static str> { self.waiting.as_ref().map(|w| match w.request { - PickRequest::Open(_) => "open", + PickRequest::Open(_) | PickRequest::OpenFiles(_) => "open", PickRequest::OpenMany => "place", PickRequest::Save(_) => "save", - PickRequest::Folder => "folder", + PickRequest::Folder | PickRequest::FolderAt(_) => "folder", }) } } @@ -350,19 +354,32 @@ pub(crate) fn folder(app: &mut VectorcraftApp) -> Option { ask(app, PickRequest::Folder)?.into_iter().next() } +/// A folder from the folder picker, which starts in `start` when the host can start it there. +pub(crate) fn folder_at(app: &mut VectorcraftApp, start: &str) -> Option { + ask(app, PickRequest::FolderAt(start.to_string()))?.into_iter().next() +} + /// Paths from the open dialog for files to place (none: cancelled). pub(crate) fn open_many(app: &mut VectorcraftApp) -> Vec { ask(app, PickRequest::OpenMany).unwrap_or_default() } +/// Paths from an open dialog for several files of `pick`'s types (none: cancelled, or shown off the +/// UI thread for now). +pub(crate) fn open_files(app: &mut VectorcraftApp, pick: &FilePick) -> Vec { + ask(app, PickRequest::OpenFiles(pick.clone())).unwrap_or_default() +} + /// Whether the host shows `request`'s kind of dialog at all. pub(crate) fn can(app: &VectorcraftApp, request: &PickRequest) -> bool { let s = &app.services; match request { PickRequest::Open(_) => s.pick_open.is_some(), PickRequest::OpenMany => s.pick_open_multi.is_some() || s.pick_open.is_some(), + PickRequest::OpenFiles(_) => s.pick_open_files.is_some() || s.pick_open.is_some(), PickRequest::Save(_) => s.pick_save.is_some(), PickRequest::Folder => s.pick_folder.is_some(), + PickRequest::FolderAt(_) => s.pick_folder_at.is_some() || s.pick_folder.is_some(), } } @@ -402,11 +419,21 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest) -> Option { PickRequest::Open(pick) => one(s.pick_open.as_mut().and_then(|f| f(pick))), PickRequest::Save(pick) => one(s.pick_save.as_mut().and_then(|f| f(pick))), PickRequest::Folder => one(s.pick_folder.as_mut().and_then(|f| f())), + PickRequest::FolderAt(start) => match (s.pick_folder_at.as_mut(), s.pick_folder.as_mut()) { + (Some(at), _) => one(at(start)), + (None, Some(f)) => one(f()), + (None, None) => None, + }, PickRequest::OpenMany => match (s.pick_open_multi.as_mut(), s.pick_open.as_mut()) { (Some(many), _) => Some(many()), (None, Some(f)) => one(f(&FilePick::default())), (None, None) => None, }, + PickRequest::OpenFiles(pick) => match (s.pick_open_files.as_mut(), s.pick_open.as_mut()) { + (Some(many), _) => Some(many(pick)), + (None, Some(f)) => one(f(pick)), + (None, None) => None, + }, } } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 02c2229741..799e73b2cc 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,7 +1,7 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm` or `prompt`, waits for the person's answer. +//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. use serde_json::json; @@ -44,6 +44,15 @@ pub fn poll(app: &mut VectorcraftApp) { /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. fn ask(app: &mut VectorcraftApp) -> bool { + if let Some(picker) = app.session.script_picker() { + if app.ui.dialog.is_none() { + script_run::open_picker(app, &picker); + } + return true; + } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::PICKER_KIND) { + app.ui.dialog = None; + } if let Some(dialog) = app.session.script_dialog() { if app.ui.dialog.is_none() { script_run::open_notice(app, &dialog); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 676a9a48c8..ce48ef17c1 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -35,6 +35,11 @@ pub type PickOpen = Box Option>; pub type PickSave = Box Option>; +pub type PickOpenFiles = Box Vec>; + +/// Shows a folder picker that starts in the given folder; returns the folder picked. +pub type PickFolderAt = Box Option>; + pub type ReadFn = Box Result, String>>; /// The first `max` bytes of the file at a path (all of it when it is shorter); the rest of the file @@ -120,6 +125,9 @@ pub struct Services { pub open_url: Option, /// Show an open dialog for several files (File → Place…); returns their paths (none: cancelled). pub pick_open_multi: Option Vec>>, + /// Show an open dialog for several files of the pick's types (a script's `File.openDialog` with + /// `multiSelect`); returns their paths (none: cancelled). Without it, an open dialog for one. + pub pick_open_files: Option, /// Web: start an async pick of files to place (they arrive via `place_inbox`). pub place_async: Option>, /// Files that arrived asynchronously to be placed (web: picked for Place, or dropped on the @@ -160,6 +168,9 @@ pub struct Services { pub open_in_photocraft: Option, /// Show a folder picker; returns its path (desktop: Relink to Folder, Package). pub pick_folder: Option Option>>, + /// Show a folder picker that starts in a folder (a script's `selectDlg`); returns its path. + /// Without it, `pick_folder`, which starts where the host starts it. + pub pick_folder_at: Option, /// Show the system's color sampler, which picks a color anywhere on the screen (macOS, Linux /// through the desktop portal, and browsers with an EyeDropper): Sample Color from Screen /// ([`screen_color`]). Without it that command answers with an error and the Color Picker's diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index e808cf2463..f0926e1979 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -53,6 +53,7 @@ pub(crate) fn off_the_ui_thread(services: &mut Services) -> (Shown, Written) { services.pick_open = Some(Box::new(in_line)); services.pick_save = Some(Box::new(in_line)); services.pick_open_multi = Some(Box::new(|| panic!("no dialog on the UI thread"))); + services.pick_open_files = Some(Box::new(|_: &FilePick| panic!("no dialog on the UI thread"))); services.pick_folder = Some(Box::new(|| panic!("no dialog on the UI thread"))); services.read = Some(Box::new(|_: &str| Ok(SVG.to_vec()))); services.write = Some(Box::new(move |path: &str, _: &[u8]| { @@ -1074,11 +1075,11 @@ fn without_tests(code: &str) -> String { } /// The calls in `code` (from [`code_only`]) of the host's in-line dialogs: [`Services`]' -/// `pick_open`, `pick_save`, `pick_folder` and `pick_open_multi` used other than to ask whether -/// the host has them (`.is_some()`, `.is_none()`). +/// `pick_open`, `pick_save`, `pick_folder`, `pick_folder_at`, `pick_open_multi` and +/// `pick_open_files` used other than to ask whether the host has them (`.is_some()`, `.is_none()`). fn in_line_dialogs(code: &str) -> Vec { let mut found = vec![]; - for name in ["pick_open", "pick_save", "pick_folder", "pick_open_multi"] { + for name in ["pick_open", "pick_save", "pick_folder", "pick_folder_at", "pick_open_multi", "pick_open_files"] { let field = format!(".{name}"); let mut rest = code; while let Some(at) = rest.find(&field) { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 08ac8e1917..ba6553e068 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -267,9 +267,13 @@ fn a_stop_names_the_files_the_run_left_written() { let dir = folder("written"); let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); - let source = format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"); + let source = format!("Folder.selectDialog('Folder'); vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"); menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); script_runs::poll(&mut app); + assert!(app.session.script_picker().is_some(), "the run waits at its folder dialog"); + let paths = vec![dir.to_string_lossy().into_owned()]; + assert!(app.session.script_pick(vectorcraft_engine::script::files::PickAnswer::Allow { paths, always: false })); + script_runs::poll(&mut app); assert!(path.exists()); app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, json!({}))); confirm(&mut app).unwrap(); @@ -277,6 +281,327 @@ fn a_stop_names_the_files_the_run_left_written() { let _ = std::fs::remove_dir_all(&dir); } +/// A script's open dialog with `multiSelect` shows the host's dialog for several files, with the +/// file types of the script's filter, and the script gets every file picked. +#[test] +fn a_scripts_open_dialog_picks_several_files_of_its_types() { + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let dir = folder("several"); + let paths: Vec = ["a.txt", "b.txt"].iter().map(|n| dir.join(n).to_string_lossy().into_owned()).collect(); + for p in &paths { + std::fs::write(p, "x").unwrap(); + } + let (seen, given) = (asked.clone(), paths.clone()); + let services = crate::Services { + pick_open: Some(Box::new(|_: &crate::FilePick| panic!("the dialog for one file"))), + pick_open_files: Some(Box::new(move |pick: &crate::FilePick| { + seen.borrow_mut().push(pick.filters.clone()); + given.clone() + })), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick', 'Text:*.txt;All files:*.*', true); vc.log([f.length, f[0].name, f[1].name]);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + assert_eq!(*asked.borrow(), vec![vec![("Text".to_string(), vec!["txt".to_string()]), ("All files".to_string(), vec!["*".to_string()])]]); + assert_eq!(app.script_picked, paths); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([[2, "a.txt", "b.txt"]])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A folder's `selectDlg` asks the host for a folder picker that starts in that folder, and +/// `Folder.selectDialog` for one that starts where the host starts it. +#[test] +fn a_scripts_folder_dialog_starts_in_the_folder_it_was_asked_from() { + let dir = folder("selectstart"); + let requests = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let seen = requests.clone(); + let picked = dir.to_string_lossy().into_owned(); + let services = crate::Services { + start_pick: Some(Box::new(move |request: crate::picks::PickRequest| { + seen.borrow_mut().push(request); + None + })), + pick_folder: Some(Box::new(move || Some(picked.clone()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = format!( + "var a = new Folder({:?}).selectDlg('Pick'); var b = Folder.selectDialog('Pick'); vc.log([a !== null, b !== null]);", + dir.to_string_lossy() + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + for _ in 0..2 { + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + } + finish(&mut app); + let start = app.session.script_report().map(|r| r["log"].clone()); + assert_eq!(start, Some(json!([[true, true]]))); + let r = requests.borrow(); + let starts_in_dir = |s: &str| std::fs::canonicalize(s).ok() == std::fs::canonicalize(&dir).ok(); + assert!(matches!(&r[..], [crate::picks::PickRequest::FolderAt(s), crate::picks::PickRequest::Folder] if starts_in_dir(s)), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Where the host shows file dialogs in line (Windows), a folder's `selectDlg` also opens the +/// folder picker in that folder, and `Folder.selectDialog` the one that starts where the host +/// starts it. +#[test] +fn a_scripts_folder_dialog_shown_in_line_starts_in_the_folder_it_was_asked_from() { + let dir = folder("selectstartinline"); + let shown = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let (at, plain) = (shown.clone(), shown.clone()); + let (picked_at, picked) = (dir.to_string_lossy().into_owned(), dir.to_string_lossy().into_owned()); + let services = crate::Services { + pick_folder_at: Some(Box::new(move |start: &str| { + at.borrow_mut().push(Some(start.to_string())); + Some(picked_at.clone()) + })), + pick_folder: Some(Box::new(move || { + plain.borrow_mut().push(None); + Some(picked.clone()) + })), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = format!( + "var a = new Folder({:?}).selectDlg('Pick'); var b = Folder.selectDialog('Pick'); vc.log([a !== null, b !== null]);", + dir.to_string_lossy() + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + for _ in 0..2 { + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + } + finish(&mut app); + assert_eq!(app.session.script_report().map(|r| r["log"].clone()), Some(json!([[true, true]]))); + let r = shown.borrow(); + let starts_in_dir = |s: &str| std::fs::canonicalize(s).ok() == std::fs::canonicalize(&dir).ok(); + assert!(matches!(&r[..], [Some(s), None] if starts_in_dir(s)), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A control request, handled as the app handles one: while `answering_control` is set. +fn control(app: &mut VectorcraftApp, method: &str, params: Value) -> Value { + let (req, _) = crate::control::ControlRequest::new(method, params); + app.ui.answering_control = true; + let outcome = crate::control::handle(app, &egui::Context::default(), &req); + app.ui.answering_control = false; + let crate::control::Outcome::Done(r) = outcome else { panic!("expected an immediate reply") }; + r +} + +const BY_PERSON: &str = "Only the person at the keyboard can allow a script's file access"; + +/// The paths a script's file dialog allows come from Choose… alone: `ui.dialog.set` cannot set +/// them, and fields set on the dialog do not let Always Allow keep a grant the run cannot keep. +#[test] +fn a_scripts_file_dialog_takes_no_paths_from_automation() { + let dir = folder("automated"); + let secret = dir.join("secret.txt"); + std::fs::write(&secret, "secret").unwrap(); + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick'); vc.log(f === null ? null : f.fsName);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND)); + let p = secret.to_string_lossy().into_owned(); + let r = control(&mut app, "ui.dialog.set", json!({"field": "paths", "value": [p]})); + assert!(r["error"].as_str().is_some_and(|e| e.contains("no field `paths`")), "{r}"); + let always = json!({"fields": [{"field": "canAlways", "value": true}, {"field": "answer", "value": "always"}], "action": "confirm"}); + let r = control(&mut app, "ui.dialog.set", always.clone()); + assert_eq!(r["error"], BY_PERSON, "{r}"); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + d.fields.insert("answer".into(), json!("once")); + assert_eq!(confirm(&mut app).unwrap_err(), "choose a file or folder first, or deny"); + app.script_picked = vec![p]; + let r = control(&mut app, "ui.dialog.set", always); + assert_eq!(r["error"], BY_PERSON, "{r}"); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + d.fields.insert("canAlways".into(), json!(true)); + d.fields.insert("answer".into(), json!("always")); + assert_eq!(confirm(&mut app).unwrap_err(), "this script's file access can be allowed only once"); + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "deny"}], "action": "confirm"})); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Allow Once and Always Allow This Script are taken only from the person at the keyboard: a control +/// request and synthetic input are refused and the dialog stays open, after a person picked a file +/// with Choose… too, while Deny from automation is taken. +#[test] +fn a_scripts_file_access_is_allowed_only_by_the_person() { + let dir = folder("byperson"); + let picked = dir.join("picked.txt"); + std::fs::write(&picked, "picked").unwrap(); + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick'); vc.log(f === null ? null : f.name);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![picked.to_string_lossy().into_owned()]; + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "once"}], "action": "confirm"})); + assert_eq!(r["error"], BY_PERSON, "{r}"); + assert!(app.session.script_picker().is_some(), "the run still waits"); + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "deny"}], "action": "confirm"})); + assert!(r.get("error").is_none_or(Value::is_null), "Deny is taken from automation: {r}"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![picked.to_string_lossy().into_owned()]; + app.ui.dialog.as_mut().expect("the file dialog").fields.insert("answer".into(), json!("once")); + app.synthetic_frame = true; + assert_eq!(confirm(&mut app).unwrap_err(), BY_PERSON); + app.synthetic_frame = false; + assert!(app.session.script_picker().is_some(), "the run still waits"); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["picked.txt"])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The texts the dialog layer draws, once a few frames have let it settle. +fn dialog_texts(app: &mut VectorcraftApp) -> Vec { + fn texts(s: &egui::Shape, out: &mut Vec) { + 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 = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut v = vec![]; + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + v.clear(); + out.shapes.iter().for_each(|c| texts(&c.shape, &mut v)); + } + v +} + +/// The dialog says what the run asks for and shows the script's prompt, also after `ui.dialog.set` +/// changed the dialog's `kind` and `prompt` fields. +#[test] +fn a_scripts_file_dialog_says_what_the_run_asks_for() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "vc.log(Folder.selectDialog('Pick the export folder'));"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + let r = + control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "kind", "value": "open"}, {"field": "prompt", "value": "Nothing to see"}]})); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + let texts = dialog_texts(&mut app); + let folder = "The script asks to read and write a folder you choose, with everything in it."; + assert!(texts.iter().any(|t| t == folder), "{texts:?}"); + assert!(texts.iter().any(|t| t == "Pick the export folder"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "Nothing to see" || t == "The script asks to read a file you choose."), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// Enter in the file dialog gives Deny, its default answer, also after the person picked a folder. +#[test] +fn enter_in_a_scripts_file_dialog_denies() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "vc.log(Folder.selectDialog('Pick'));"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![folder("enterdeny").to_string_lossy().into_owned()]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + for events in [vec![], vec![], vec![enter]] { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::script_run::PICKER_KIND), "the dialog closes"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); +} + +/// Enter on the file dialog's focused Choose… button goes to that button and does not deny. +#[test] +fn enter_on_a_focused_choose_button_does_not_deny() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log(Folder.selectDialog('Pick'));" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let frame = |app: &mut VectorcraftApp, events| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + for events in [vec![], vec![], vec![key(egui::Key::Tab)], vec![]] { + frame(&mut app, events); + } + assert!(ctx.memory(|m| m.focused().is_some()), "Tab gives a button the keyboard focus"); + frame(&mut app, vec![key(egui::Key::Enter)]); + frame(&mut app, vec![]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND), "the dialog stays open"); + assert!(app.session.script_picker().is_some(), "the run still waits"); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// Choose… keeps at most the 2,048 files a script is given, and the dialog says the files picked +/// after them were left out. +#[test] +fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { + let given: Vec = (0..2050).map(|n| format!("/picked/{n}.txt")).collect(); + let all = given.clone(); + let services = crate::Services { pick_open_files: Some(Box::new(move |_: &crate::FilePick| all.clone())), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "File.openDialog('Pick', '', true);" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + dialogs::script_run::choose(&mut app, &mut d); + app.ui.dialog = Some(d); + assert_eq!(app.script_picked, given[..2048]); + let texts = dialog_texts(&mut app); + let note = "A script is given at most 2,048 files: the files picked after them were left out"; + assert!(texts.iter().any(|t| t == note), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); +} + #[test] fn a_new_app_shows_the_warning_by_default() { assert!(Session::new().prefs.show_external_script_warning); diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..dd5de656cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2218,8 +2218,8 @@ script reads files with them: - `open('r')` opens a file to read, and `read([chars])`, `readln()`, `readch()`, `seek(pos[, mode])`, `tell()`, `eof` and `close()` read it. `read`, `readln` and `readch` count characters, and `seek` and `tell` count bytes. `readln` and `readch` take CR, LF, CRLF and LF CR as one line end. `folder.getFiles([mask])` lists a folder, sorted by name; - the mask matches `*` and `?` without regard to case, and a function as the mask keeps the entries it returns true - for. + the mask matches `*` and `?`, without regard to case on Windows and macOS and with case elsewhere, and a function + as the mask keeps the entries it returns true for. - A method that fails returns `false`, `null` or an empty string and sets `error`, such as `Script file access denied`, `Script file does not exist` or `Script file is not open`. A count or a position that is not a finite number, or a negative count, throws a `RangeError`. @@ -2234,7 +2234,9 @@ VectorCraft reads files by these rules of its own: `getFiles` leaves such an entry out. A missing file is refused the same way unless the nearest folder above it that exists is inside the script's folder. It is also refused when a link above it leads to a folder that does not exist. - `open` reads the whole file. A file larger than 8 MiB is refused from its size before any of it is read, with - `Script file exceeds 8 MiB`, and a run that opens more than 32 MiB in all ends with an error. A run has at most 256 + `Script file exceeds 8 MiB`, and a run that opens more than 32 MiB in all ends with an error. A file opened again + after its objects closed counts only the bytes it grew by, and a file that another object has open counts again. A + run has at most 256 files open at once; another `open` returns `false` with `Script has 256 files open` until one is closed. - The encoding is the one the file's byte order mark gives (UTF-8, UTF-16LE or UTF-16BE), otherwise the `encoding` the script set before `open`, otherwise UTF-8 when the bytes are valid UTF-8, otherwise CP1252. `BINARY` reads each @@ -2245,11 +2247,111 @@ VectorCraft reads files by these rules of its own: folder gives `null` with `Script folder mask takes too many steps to match`. - A path longer than 32,767 characters throws a `RangeError` (`Script file path exceeds 32,767 characters`) when a `File` or `Folder` is made from it. -- Writing is not available yet: `open('w')`, `open('e')`, `open('a')`, `write`, `writeln`, `copy`, `remove`, - `rename`, `create` and `createAlias` return `false` with `Script file writing is not available`, and setting - `length`, `hidden` or `readonly` sets `error` to that message and changes nothing. The file - and folder dialogs return `null`, and `execute` opens nothing and returns `false`. In the web build every lookup - fails with `Script file access is unavailable on the web`. +- `createAlias` returns `false` with `Script files cannot make aliases`, setting `hidden` sets `error` to `Script + file hidden setting cannot be changed` and changes nothing, and `execute` opens nothing and returns `false`. In the + web build every lookup fails with `Script file access is unavailable on the web`. + +The help page's writing members work as it describes +(, +): + +- `open('w')` empties the file, or makes it, `open('e')` opens a file that is there, and `open('a')` opens it at its + end. `write(...values)` writes the values as `String(value)` gives them, and `writeln(...values)` adds the line end + `lineFeed` names: CR LF for `Windows`, CR for `Macintosh` and LF for `Unix`. A byte order mark is written only + when the script writes ``. +- `copy(target)` copies the file to a path or a `File` and replaces a file that is there. `remove()` deletes a file, + or a folder only when it is empty (`Script folder is not empty`), at once and without the trash. `rename(name)` + takes a name without a folder; a name that is in use gives `Script file name is already in use`, and the object + takes the new path; another object that has the file open writes to the new path. An object whose changes + `close` could not write does not remove or rename its file, and another object that has a removed file open + drops its changes and takes no more writes. `copy` of a file over 8 MiB gives `Script file exceeds 8 MiB`, and `copy` of a file that + is open copies what the open file holds; an object that has the target open then holds the copy. `folder.create()` makes the folder and the folders above it, and gives `Script file access denied` without making any when one of them is outside the places the script may write. Setting `length` cuts the file or + pads it with zero bytes, also in an object that has the file open, and setting `readonly` changes the file (on + Unix, setting it clears every write bit, and clearing it gives back the bits the run cleared, or else the owner's + write bit). `changePath` of an object whose changes cannot be written gives `false` with `error` set and keeps its path. `copy` onto the file itself leaves it as it is, and `open('w')` with an + encoding that is not one gives `false` and leaves the file as it is. +- `File.openDialog(prompt, filter, multiSelect)`, `File.saveDialog(prompt, filter)` and `Folder.selectDialog(prompt)`, + and the objects' `openDlg`, `saveDlg` and `selectDlg`, give a `File` or a `Folder`, or `null` when the person + cancels; `multiSelect` gives an array of the files picked. A string `filter` such as `"JavaScript:*.jsx;All + files:*.*"` gives the file types the dialog shows: each `name:pattern` starts a type, a pattern without a name adds + to the type before it, and patterns are separated by `,` or `;`. `*.ext` patterns name extensions and `*` or `*.*` + every file; other patterns are left out. A `filter` that is a function is called with a `File` for each file + picked, and the files it gives a false value for are left out of the result; when none is left, the dialog + gives `null`. The dialog itself then shows every file. + +VectorCraft writes files by these rules of its own: + +- A script writes only in `Folder.temp`, `Folder.userData` and what a person allowed it in a file dialog. Its own + folder is only read. `Folder.temp` is a folder for the run, made when the script first names it and deleted when + the run ends; `new File()` names a new file there. `Folder.userData` is the script's own folder in the Script Data + folder next to the settings, kept between runs; a script given as `source`, or a session without a settings + folder, gets one inside `Folder.temp`. When that folder is a link, `Folder.userData` is `null` and the place the + link leads to is not granted. When automation write roots are set and do not take the folder, `Folder.temp` or + `Folder.userData` is `null` and the folder is not made; the same holds when they do not take a missing folder above it. When automation write roots are set, the place written must also be inside + them. Opening a file with `e` or `a` reads it, so the automation read roots apply to it as well. The folder that + holds the settings (the Scripts and Plug-ins folders among them) is kept out of every grant, also before it has + been made, apart from the script's own `Folder.userData`, and a folder that holds it cannot be renamed. Anything + else gives `false` with + `Script file access denied`. +- What a script writes is written when it closes the file or when the run ends, also when the run fails. At the + run's end the files left open are written in the order they were opened. A file + that `close` could not write is written again when the run ends, and a `write` that would pass the run's limit + is not written. A run that + would otherwise succeed fails when a changed file it left open cannot be written, with + `Error: the script left open files that could not be written` and the files' paths. One file + holds at most 8 MiB, and a run that writes more than 32 MiB in all ends with an error. `write` encodes in the + file's encoding: `ASCII` and `ISO-8859-1` give `false` with `Script file cannot encode the text` for a character + they cannot hold, and `BINARY` writes each character's low byte. `write` and `writeln` turn their values into text + only for an open file, and stop once the text is longer than 16,777,216 UTF-16 code units, giving `false` with + `Script file exceeds 8 MiB`. Each object that has a file open holds its own bytes, so the 32 MiB counts what + setting `length` adds to the file and to each such object, and what `copy` writes to its target and to each such + object of the target. The report's `written` names each file written, at most 4,096 of them; a run that wrote more + also has `writtenMore: true`. +- In the app a file dialog shows the script's prompt and what the script asks for: a file to read (open), a file to + read and write (save), or a folder to read and write with everything in it. The person chooses with Choose…, whose + dialog picks several files at once, and adds them to those chosen before, when the script asked for several with + `multiSelect` (Choose… keeps at most 2,048, and the dialog says when it left out the files picked after them), and + then picks Allow Once, Always Allow This Script or Deny; Deny, Enter, Escape and Cancel give `null`, and Stop ends + the run. Choose… for a folder's `selectDlg` opens the host's folder dialog in that folder. + The prompt and what the dialog says the script asks for come from the script's request, so `ui.dialog.set` on the + dialog's `kind` or `prompt` does not change them. Only the person at the keyboard allows access: an `answer` of + `once` or `always` from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input gives `Only the person at the + keyboard can allow a script's file access`, and the dialog stays open; `deny` and `stop` are taken from automation. + Always Allow This Script keeps the grant in `Script Grants.json` next to the settings for that script file with + that text with the files it includes, by its SHA-256, so a changed or moved script, or a changed included file, + asks again. It is offered only for a script run from a file. The grant also keeps the SHA-256 of each source the + run evaluated up to its end (a file `$.evalFile` ran, a string given to `eval` or `Function`, at most 256). A later + run loses the grant before it evaluates a source the grant does not list, and from the start when its + `#targetengine` engine holds code the grant does not list, such as another script's. A kept grant stays on the + real path that was allowed: when that path now leads elsewhere, through a link put in its place or in a folder + above it, the grant is not used. +- A command a script runs with `vc.run` reads and writes files only where the script's `File` and `Folder` objects + may, and in the files the open documents were opened from or saved to. Anything else fails with + `Script file access denied` and the path, saving into a user library (swatches, brushes, symbols or graphic + styles) included; reading the app's own libraries is allowed. A script given as `source` that a person allowed nothing writes only in + its `Folder.temp` and `Folder.userData` and to the open documents' own files. + A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's + own folders is not allowed`. +- A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to + `Script file dialogs need a person to answer them`, and takes no kept grant. In the app, a file dialog inside a + built-in's callback, a getter, a conversion or a file `$.evalFile` runs throws an error. + +`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file}`, with `code` +the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's +grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later +takes its place), and `file` the grants +file's path, or `null` without a settings folder. `script.grants.revoke {script?, path?, all?}` removes the grants of +a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. While a script +runs it is refused with the busy error, as the run keeps the grants it started with. A script cannot run either +command. + +```json +{"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} +``` + +```sh +vectorcraft-cli run --cmd script.grants --params '{}' +``` Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and `$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message` (or `name: file:line:column: message` when the error is in another diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..ba3af3858f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -783,7 +783,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. - - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; writing, the file dialogs and `execute` are not available yet. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`.