From 4716646c6bb4773c9866095029920ad4cc719b20 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:42:56 -0800 Subject: [PATCH 01/48] Scripts: File and Folder objects write files inside a script's scope, with per-script grants and pickers A script's File and Folder objects now open files for writing, appending and editing, and copy, rename, remove and create files and folders. A script reads and writes its run's temporary folder (Folder.temp) and its own data folder (Folder.userData), kept between runs for a script run from a file and inside Folder.temp for a script given as text. It reads its own folder, and reaches other places only through File.openDialog, File.saveDialog, Folder.selectDialog and the objects' openDlg, saveDlg and selectDlg. - A file dialog asks first. The person picks the file or folder with Choose..., then allows it once or, for a script run from a file, always. A kept grant is bound to the script's path, the SHA-256 of its text and every source the run evaluated. It is withdrawn when a later run of the script evaluates other code, including code an earlier run left in the same named engine. It stays on the real path that was granted, so a link put in that place later does not carry it elsewhere. - A dialog's filter is a string of file types or a function that is called with each file picked; multiSelect gives an array of the files picked, at most 2,048, and the dialog says when more were left out. - A folder's selectDlg opens the host's folder dialog in that folder, also where the host shows file dialogs in line. Enter in the file dialog denies, unless it goes to the focused Choose... button. script.grants.revoke is refused with the busy error while a script runs, as the run keeps the grants it started with. - The paths a file dialog allows come only from the host's file dialog: ui.dialog.set cannot set them. Only the person at the keyboard allows access; Allow Once and Always Allow sent by automation are refused. The dialog describes the access the run asked for, whatever its fields say. - No grant reaches the settings folder, also when the script's own folder holds it. - A file left open is not written through a link put in place of its folder since it was opened, and Folder.userData is null when the data folder or the script's folder in it is a link. - copy onto another link to the same file (a hard link) leaves the file's bytes as they are, after the source's open objects have written what they hold. Files are compared by identity (device and inode on Unix, volume and file index on Windows). - Folder.temp and Folder.userData check each folder they make against the automation write roots first, and Folder.create() makes nothing when a missing folder above the target is outside the places the script may write. - An open file holds at most 8 MiB, a run writes at most 32 MiB and keeps at most 256 files open, and the files a run left open are written in the order they were opened. Setting length and copying a file count the bytes every open object of that file takes, and write checks the joined text against the limit while joining it. The report names at most 4,096 written files and sets writtenMore when there were more. - Errors a script sees are translated in every complete message catalog. --- apps/vectorcraft-cli/src/main.rs | 6 +- apps/vectorcraft/src/host_services.rs | 48 +- apps/vectorcraft/src/main.rs | 1 + apps/vectorcraft/src/prefs_dir.rs | 9 + crates/engine/Cargo.toml | 5 +- crates/engine/src/cmd/scripts.rs | 66 +- crates/engine/src/file_access.rs | 254 +++- crates/engine/src/lib.rs | 4 + crates/engine/src/script/files.rs | 1339 +++++++++++++++++++++- crates/engine/src/script/mod.rs | 165 ++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/script_io.rs | 1259 +++++++++++++++++++- crates/engine/src/tests/script_run.rs | 140 ++- crates/js/src/builtins.rs | 2 + crates/js/src/file_classes.rs | 362 +++++- crates/js/src/host.rs | 7 +- crates/js/src/host_tests.rs | 18 + crates/js/src/interp.rs | 15 + crates/js/src/realm.rs | 18 +- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/dialogs.rs | 4 + crates/ui-egui/src/dialogs/script_run.rs | 214 +++- crates/ui-egui/src/i18n/bg.tsv | 7 + crates/ui-egui/src/i18n/bs.tsv | 7 + crates/ui-egui/src/i18n/ca.tsv | 30 +- crates/ui-egui/src/i18n/cs.tsv | 30 +- crates/ui-egui/src/i18n/da.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 30 +- crates/ui-egui/src/i18n/el.tsv | 30 +- crates/ui-egui/src/i18n/es.tsv | 30 +- crates/ui-egui/src/i18n/fi.tsv | 30 +- crates/ui-egui/src/i18n/fr.tsv | 30 +- crates/ui-egui/src/i18n/hi.tsv | 30 +- crates/ui-egui/src/i18n/hu.tsv | 30 +- crates/ui-egui/src/i18n/id.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 30 +- crates/ui-egui/src/i18n/ja.tsv | 30 +- crates/ui-egui/src/i18n/ka.tsv | 30 +- crates/ui-egui/src/i18n/ko.tsv | 30 +- crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 30 +- crates/ui-egui/src/i18n/pt-br.tsv | 30 +- crates/ui-egui/src/i18n/ru.tsv | 30 +- crates/ui-egui/src/i18n/sv.tsv | 30 +- crates/ui-egui/src/i18n/tests.rs | 66 +- crates/ui-egui/src/i18n/tr.tsv | 30 +- crates/ui-egui/src/i18n/uk.tsv | 30 +- crates/ui-egui/src/i18n/vi.tsv | 30 +- crates/ui-egui/src/i18n/zh-hans.tsv | 30 +- crates/ui-egui/src/i18n/zh-hant.tsv | 30 +- crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/picks.rs | 31 +- crates/ui-egui/src/script_runs.rs | 11 +- crates/ui-egui/src/services.rs | 11 + crates/ui-egui/src/tests/picks.rs | 7 +- crates/ui-egui/src/tests/script_run.rs | 327 +++++- docs/mcp.md | 118 +- docs/target-app-parity.md | 3 +- 58 files changed, 4948 insertions(+), 265 deletions(-) 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`. From 1f64044f1c6c2d75b91a319bbd2d9faf45d40e57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:45:25 -0800 Subject: [PATCH 02/48] Web: Korean and Hindi interface text draws with real glyphs The web build had no face for Hangul or Devanagari, so a Korean or Hindi interface, and a layer or file name in either script, drew as missing-glyph boxes. - crates/text/web-fonts.txt gains a `demand` kind: NanumGothic Regular and Noto Sans Devanagari Regular are served beside the wasm like the other web faces, and fetched only when the interface language or the interface's own text needs their script. They are not fetched at startup or in the background queue. - The interface reports the characters no loaded font covers (`on_missing_glyphs`), and keeps them so that they are looked for again when the font database changes. The frame after a face arrives adds it to the interface fonts, and the frame after that draws the characters painted before it with that face. - After a failed fetch the next try comes about 30 seconds later, and the wait doubles after each further failure, for at most five tries. - A new test checks that the two faces cover every Hangul and Devanagari character the catalogs use, where craft-fonts has them. Docs: gaps.md, localization-hi.md, localization-parity.md, target-app-parity.md. --- apps/vectorcraft-web/src/api.rs | 2 +- apps/vectorcraft-web/src/demand.rs | 110 +++++++++++++++++++++++ apps/vectorcraft-web/src/fonts.rs | 59 ++++++++++-- apps/vectorcraft-web/src/main.rs | 2 + apps/vectorcraft-web/src/web.rs | 5 ++ crates/text/build.rs | 7 +- crates/text/build/web_fonts.rs | 24 +++-- crates/text/src/craft_fonts.rs | 72 ++++++++++++++- crates/text/web-fonts.txt | 4 + crates/ui-egui/src/i18n.rs | 2 +- crates/ui-egui/src/i18n/tests.rs | 30 +++++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/ui_fonts.rs | 140 +++++++++++++++++++++++++---- docs/gaps.md | 3 +- docs/localization-hi.md | 11 ++- docs/localization-parity.md | 7 +- docs/target-app-parity.md | 1 + 17 files changed, 430 insertions(+), 50 deletions(-) create mode 100644 apps/vectorcraft-web/src/demand.rs diff --git a/apps/vectorcraft-web/src/api.rs b/apps/vectorcraft-web/src/api.rs index eddd04f1b7..1be921baf3 100644 --- a/apps/vectorcraft-web/src/api.rs +++ b/apps/vectorcraft-web/src/api.rs @@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin>> { }) } -async fn sleep(ms: i32) { +pub(crate) async fn sleep(ms: i32) { let promise = js_sys::Promise::new(&mut |resolve, _| { if let Some(window) = web_sys::window() { let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs new file mode 100644 index 0000000000..cbab6014bf --- /dev/null +++ b/apps/vectorcraft-web/src/demand.rs @@ -0,0 +1,110 @@ +//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most +//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after +//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures. + +/// The wait after a face's first failed fetch before it is fetched again (ms). +const RETRY_MS: i32 = 30_000; +/// Failed fetches of a face after which it is not fetched again this session. +pub(crate) const MAX_TRIES: u32 = 5; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum State { + Idle, + /// Being fetched, after `tries` failed fetches. + Loading { + tries: u32, + }, + Loaded, + /// `tries` fetches failed; the next may start at `retry_at` (ms). + Failed { + tries: u32, + retry_at: f64, + }, +} + +/// The fetch state of each face of a web font list, by index. +#[derive(Debug, Default)] +pub(crate) struct Demand { + states: Vec, +} + +impl Demand { + /// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not + /// loaded, not being fetched, and not waiting to be fetched again. They are marked as being + /// fetched. + pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec { + let mut out = Vec::new(); + for &i in wanted { + if self.states.len() <= i { + self.states.resize(i + 1, State::Idle); + } + let Some(state) = self.states.get_mut(i) else { continue }; + let tries = match *state { + State::Idle => Some(0), + State::Loading { .. } | State::Loaded => None, + State::Failed { tries, retry_at } => (tries < MAX_TRIES && now >= retry_at).then_some(tries), + }; + if let Some(tries) = tries { + *state = State::Loading { tries }; + out.push(i); + } + } + out + } + + /// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`. + /// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it + /// loaded or has failed [`MAX_TRIES`] times. + pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option { + let state = self.states.get_mut(i)?; + let State::Loading { tries } = *state else { return None }; + if ok { + *state = State::Loaded; + return None; + } + let tries = tries + 1; + let wait = RETRY_MS << (tries - 1).min(4); + *state = State::Failed { tries, retry_at: now + f64::from(wait) }; + (tries < MAX_TRIES).then_some(wait) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_face_is_fetched_once_and_kept() { + let mut d = Demand::default(); + assert_eq!(d.start(&[2], 0.0), [2]); + assert!(d.start(&[2], 1.0).is_empty(), "already being fetched"); + assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry"); + assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again"); + assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own"); + assert_eq!(d.finished(7, false, 4.0), None, "a face never started"); + } + + #[test] + fn a_failed_face_waits_longer_after_each_failure_and_then_stops() { + let mut d = Demand::default(); + let mut now = 0.0; + // The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first. + for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) { + assert_eq!(d.start(&[0], now), [0], "at {now}"); + assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}"); + assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}"); + now += f64::from(wait); + } + // The fifth fetch, and after it fails, none. + assert_eq!(d.start(&[0], now), [0]); + assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures"); + assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures"); + // A later success after failures keeps the face. + let mut d = Demand::default(); + d.start(&[1], 0.0); + assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS)); + assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]); + assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None); + assert!(d.start(&[1], 1e12).is_empty()); + } +} diff --git a/apps/vectorcraft-web/src/fonts.rs b/apps/vectorcraft-web/src/fonts.rs index 2677c11edf..d2403e8084 100644 --- a/apps/vectorcraft-web/src/fonts.rs +++ b/apps/vectorcraft-web/src/fonts.rs @@ -1,17 +1,22 @@ //! Craft-fonts faces served beside the wasm (`fonts//…`, copied by //! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup` -//! ones before the app starts, [`spawn_background_fonts`] the rest once it runs. The browser checks -//! each file against its SHA-256 (Subresource Integrity). A face that fails is logged and skipped: -//! the app runs without it. With `WEB_FONTS` empty (built without craft-fonts) both do nothing. +//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and +//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the +//! interface's own text needs its script. The browser checks each file against its SHA-256 +//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With +//! `WEB_FONTS` empty (built without craft-fonts) these do nothing. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; +use vectorcraft_text::craft_fonts::demand_fonts; use vectorcraft_text::{FontDb, WEB_FONTS, WebFont}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; use wasm_bindgen_futures::JsFuture; +use crate::demand::Demand; + /// Per startup face: the page shows its loading text meanwhile. const STARTUP_TIMEOUT_MS: i32 = 20_000; /// Per background face. @@ -22,12 +27,49 @@ const BACKGROUND_PARALLEL: usize = 4; thread_local! { /// The background fetch runs once per page, though a graphics restart creates the app again. static BACKGROUND_STARTED: Cell = const { Cell::new(false) }; + /// The `demand` faces' fetches. + static DEMAND: RefCell = RefCell::new(Demand::default()); + /// The running app's context, asked for a frame when a `demand` face arrives (none before the + /// app starts: its first frame looks through the faces loaded by then). + static REPAINT: RefCell> = const { RefCell::new(None) }; +} + +/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or +/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those +/// characters with it from then on. Set as the interface's missing-glyph handler +/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name +/// before the app starts. +pub fn want_chars(chars: &[char]) { + let wanted = demand_fonts(WEB_FONTS, chars.iter().copied()); + if !wanted.is_empty() { + fetch_demand(&wanted); + } +} + +/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start. +/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives. +fn fetch_demand(wanted: &[usize]) { + for i in DEMAND.with(|d| d.borrow_mut().start(wanted, js_sys::Date::now())) { + let Some(f) = WEB_FONTS.get(i) else { continue }; + wasm_bindgen_futures::spawn_local(async move { + let ok = load(f, BACKGROUND_TIMEOUT_MS).await; + let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, js_sys::Date::now())); + if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) { + ctx.request_repaint(); + } + if let Some(wait) = retry { + // A second longer, so a clock the browser coarsens still reads the wait as over. + crate::api::sleep(wait.saturating_add(1_000)).await; + fetch_demand(&[i]); + } + }); + } } /// Fetch and register the `startup` faces (one after the other). Returns how many loaded. pub async fn load_startup_fonts() -> usize { let mut loaded = 0; - for f in WEB_FONTS.iter().filter(|f| f.startup) { + for f in WEB_FONTS.iter().filter(|f| f.startup && !f.demand) { if load(f, STARTUP_TIMEOUT_MS).await { loaded += 1; } @@ -36,13 +78,14 @@ pub async fn load_startup_fonts() -> usize { } /// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for -/// a frame after each so the font menus and the canvas pick it up. Only the first call does -/// anything. +/// a frame after each so the font menus and the canvas pick it up. Only the first call fetches +/// anything; each call makes `ctx` the context a `demand` face asks for a frame. pub fn spawn_background_fonts(ctx: egui::Context) { + REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone())); if BACKGROUND_STARTED.with(|s| s.replace(true)) { return; } - let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect()); + let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup && !f.demand).collect()); let next = Rc::new(Cell::new(0usize)); for _ in 0..BACKGROUND_PARALLEL.min(queue.len()) { let (queue, next, ctx) = (queue.clone(), next.clone(), ctx.clone()); diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index 3808c281f9..8943e47c76 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -21,6 +21,8 @@ #[cfg(target_arch = "wasm32")] mod api; +#[cfg(any(target_arch = "wasm32", test))] +mod demand; #[cfg(target_arch = "wasm32")] mod fonts; #[cfg(any(target_arch = "wasm32", test))] diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 2de7f3b481..6d9e0cadd5 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -81,6 +81,11 @@ pub fn start() { return; }; detect_language(); + // The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the + // startup fonts, without holding up the start. Text in those scripts painted later (a saved + // interface language, another one chosen, a layer or file name) has its face fetched then. + vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars); + crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::>()); wasm_bindgen_futures::spawn_local(async move { // Before the first frame, which looks for copies a crash left behind. let locks = WebLocks::start(RECOVERY_PREFIX).await; diff --git a/crates/text/build.rs b/crates/text/build.rs index 412c471c11..5402ddbe07 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -125,16 +125,19 @@ fn web_font_entries(dir: &Path) -> Result<(String, Vec), String> { missing.push(format!("{} {}", e.family, e.style)); continue; }; - let (Some(file), Some(sha)) = (row.get(2), row.get(6)) else { + let (Some(file), Some(scripts), Some(sha)) = (row.get(2), row.get(3), row.get(6)) else { return Err(format!("malformed manifest row for {} {}", e.family, e.style)); }; let integrity = web_fonts::sri(sha).ok_or_else(|| format!("bad sha256 for {} {}", e.family, e.style))?; + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( out, - " WebFont {{ family: {:?}, style: {:?}, startup: {}, url: {:?}, integrity: {:?} }},", + " WebFont {{ family: {:?}, style: {:?}, startup: {}, demand: {}, scripts: &[{}], url: {:?}, integrity: {:?} }},", e.family, e.style, e.startup, + e.demand, + scripts.join(", "), web_fonts::url(sha, file), integrity, ); diff --git a/crates/text/build/web_fonts.rs b/crates/text/build/web_fonts.rs index ccd387afab..ac58913afc 100644 --- a/crates/text/build/web_fonts.rs +++ b/crates/text/build/web_fonts.rs @@ -5,8 +5,11 @@ /// One line of `web-fonts.txt`: `when | family | style`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Listed<'a> { - /// `startup` (fetched before the app starts) rather than `background`. + /// `startup` (fetched before the app starts). pub startup: bool, + /// `demand` (fetched when the interface needs a character of one of the face's scripts). + /// Neither this nor `startup`: `background`. + pub demand: bool, pub family: &'a str, pub style: &'a str, } @@ -23,15 +26,16 @@ pub fn parse_list(text: &str) -> Result>, String> { let [when, family, style] = fields.as_slice() else { return Err(format!("web-fonts.txt line {}: expected `when | family | style`", i + 1)); }; - let startup = match *when { - "startup" => true, - "background" => false, - other => return Err(format!("web-fonts.txt line {}: `{other}` is neither startup nor background", i + 1)), + let (startup, demand) = match *when { + "startup" => (true, false), + "background" => (false, false), + "demand" => (false, true), + other => return Err(format!("web-fonts.txt line {}: `{other}` is not startup, background or demand", i + 1)), }; if family.is_empty() || style.is_empty() { return Err(format!("web-fonts.txt line {}: empty family or style", i + 1)); } - out.push(Listed { startup, family, style }); + out.push(Listed { startup, demand, family, style }); } Ok(out) } @@ -105,12 +109,14 @@ mod tests { #[test] fn list_parsing() { - let l = parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\n").unwrap(); + let l = + parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\ndemand | NanumGothic | Regular\n").unwrap(); assert_eq!( l, [ - Listed { startup: true, family: "Noto Sans Arabic", style: "Regular" }, - Listed { startup: false, family: "Amiri", style: "Bold Italic" } + Listed { startup: true, demand: false, family: "Noto Sans Arabic", style: "Regular" }, + Listed { startup: false, demand: false, family: "Amiri", style: "Bold Italic" }, + Listed { startup: false, demand: true, family: "NanumGothic", style: "Regular" } ] ); assert!(parse_list("soon | A | B").unwrap_err().contains("line 1")); diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index b15b77ec72..24eef3de40 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -19,8 +19,13 @@ pub struct CraftFont { pub struct WebFont { pub family: &'static str, pub style: &'static str, - /// Fetched before the app starts (a fallback the first frame needs), else in the background. + /// Fetched before the app starts (a fallback the first frame needs). pub startup: bool, + /// Fetched only when the interface needs a character of one of [`WebFont::scripts`] (see + /// [`demand_fonts`]). With neither this nor `startup`, fetched in the background. + pub demand: bool, + /// ISO 15924 scripts the face is for (its craft-fonts manifest row), e.g. `"Hang"`. + pub scripts: &'static [&'static str], /// Site-relative URL, `fonts//`. pub url: &'static str, /// Subresource Integrity value, `sha256-`; the browser rejects other bytes. @@ -106,10 +111,65 @@ pub fn japanese_ui_fonts(bold: bool) -> Vec<&'static CraftFont> { v } +/// The script of `c` that a `demand` web face is fetched for: `"Hang"` for Hangul (jamo, +/// compatibility jamo, syllables and the halfwidth forms) and `"Deva"` for Devanagari (with its +/// extended blocks and the Vedic extensions). `None` for every other character. +pub fn demand_script(c: char) -> Option<&'static str> { + match c as u32 { + 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xFFA0..=0xFFDC => Some("Hang"), + 0x0900..=0x097F | 0x1CD0..=0x1CFF | 0xA8E0..=0xA8FF | 0x11B00..=0x11B5F => Some("Deva"), + _ => None, + } +} + +/// The indexes in `fonts` of the `demand` faces for the scripts of `chars` (by +/// [`demand_script`]), each once, in `fonts` order. +pub fn demand_fonts(fonts: &[WebFont], chars: impl IntoIterator) -> Vec { + let mut scripts: Vec<&str> = Vec::new(); + for s in chars.into_iter().filter_map(demand_script) { + if !scripts.contains(&s) { + scripts.push(s); + } + } + fonts.iter().enumerate().filter(|(_, f)| f.demand && f.scripts.iter().any(|s| scripts.contains(s))).map(|(i, _)| i).collect() +} + #[cfg(test)] mod tests { use super::*; + fn web_font(family: &'static str, startup: bool, demand: bool, scripts: &'static [&'static str]) -> WebFont { + WebFont { family, style: "Regular", startup, demand, scripts, url: "", integrity: "" } + } + + #[test] + fn demand_scripts_of_hangul_and_devanagari() { + for c in ['한', '국', 'ㄱ', 'ᄀ', 'ᄀ'] { + assert_eq!(demand_script(c), Some("Hang"), "{c}"); + } + for c in ['ह', 'ि', '्', '़', '।', '\u{A8F2}'] { + assert_eq!(demand_script(c), Some("Deva"), "{c}"); + } + for c in ['A', 'é', 'ا', 'ก', 'ა', '日', 'ロ', '中'] { + assert_eq!(demand_script(c), None, "{c}"); + } + } + + #[test] + fn demand_fonts_follow_the_scripts_painted() { + let fonts = [ + web_font("Arabic", true, false, &["Arab"]), + web_font("Picked", false, false, &["Hang"]), + web_font("Korean", false, true, &["Hang", "Kore"]), + web_font("Devanagari", false, true, &["Deva"]), + ]; + assert_eq!(demand_fonts(&fonts, "한국어".chars()), [2], "Korean fetches only the Korean face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी".chars()), [3], "Hindi fetches only the Devanagari face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी 한국어 Layer".chars()), [2, 3], "each once, in list order"); + assert!(demand_fonts(&fonts, "English العربية 日本語".chars()).is_empty(), "other scripts fetch nothing"); + assert!(demand_fonts(&[], "한국어".chars()).is_empty(), "built without craft-fonts: nothing to fetch"); + } + #[test] fn document_fonts_keep_script_priority_and_include_every_face_once() { let font = |family, style, scripts| CraftFont { family, style, scripts, bytes: &[] }; @@ -157,7 +217,9 @@ mod tests { .collect(); assert_eq!(WEB_FONTS.len(), listed.len()); for (l, w) in listed.iter().zip(WEB_FONTS) { - assert_eq!((l.family, l.style, l.startup), (w.family, w.style, w.startup)); + assert_eq!((l.family, l.style, l.startup, l.demand), (w.family, w.style, w.startup, w.demand)); + let face = CRAFT_FONTS.iter().find(|f| f.family == w.family && f.style == w.style); + assert_eq!(face.map(|f| f.scripts), Some(w.scripts), "{} {}: the manifest's scripts", w.family, w.style); let (dir, name) = w.url.strip_prefix("fonts/").and_then(|r| r.split_once('/')).unwrap(); assert!(dir.len() == 16 && dir.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), "{}", w.url); assert!(name.ends_with(".ttf") || name.ends_with(".otf"), "{}", w.url); @@ -169,5 +231,11 @@ mod tests { let expected: Vec<_> = ["Noto Sans Arabic", "Noto Sans Thai", "Noto Sans Georgian"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); assert_eq!(startup, expected); + // Korean and Devanagari faces are fetched only on demand, never at startup or in the + // background queue every session runs. + let demand: Vec<_> = WEB_FONTS.iter().filter(|w| w.demand).map(|w| w.family).collect(); + let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); + assert_eq!(demand, expected); + assert!(WEB_FONTS.iter().all(|w| !(w.startup && w.demand))); } } diff --git a/crates/text/web-fonts.txt b/crates/text/web-fonts.txt index 7dbb8953b3..235ba98e13 100644 --- a/crates/text/web-fonts.txt +++ b/crates/text/web-fonts.txt @@ -2,6 +2,8 @@ # One face per line: when | family | style (family and style as in craft-fonts' fonts/manifest.txt). # startup = fetched before the app starts (fallbacks the first frame needs) # background = fetched after the app starts (fonts users pick by name) +# demand = fetched only when the interface language or the interface's own text needs one of +# the face's scripts (Korean, Hindi) # Read by build.rs (the WEB_FONTS table) and `cargo xtask web-fonts` (copies the files, a Trunk hook). startup | Noto Sans Arabic | Regular startup | Noto Sans Thai | Regular @@ -36,3 +38,5 @@ background | Reem Kufi | Regular background | Aref Ruqaa | Regular background | Aref Ruqaa | Bold background | Gulzar | Regular +demand | NanumGothic | Regular +demand | Noto Sans Devanagari | Regular diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 4ec89b8e32..7481197115 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -100,7 +100,7 @@ fn plural_polish(n: u64) -> usize { pub static LANGUAGES: [LangInfo; 28] = [ LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() }, // Hindi shares the integer zero/one rule with French. Desktop UI fonts are loaded lazily - // from installed faces by ui_fonts; the web needs a Devanagari font in its font set. + // from installed faces by ui_fonts; the web fetches a Devanagari craft-fonts face on demand. LangInfo { code: "hi", name: "हिन्दी", diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 66caa1c3a4..df3666bd19 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -631,6 +631,36 @@ fn bundled_fonts_cover_the_catalogs() { assert!(missing.is_empty(), "characters without a glyph: {missing:#?}"); } +/// The faces the web build fetches on demand (`web-fonts.txt`: NanumGothic for Korean, Noto Sans +/// Devanagari for Hindi) cover every character of their scripts that a catalog or a language name +/// uses. Checked where the craft-fonts checkout has them (the desktop build embeds every face). +#[test] +fn web_demand_fonts_cover_the_catalogs() { + use vectorcraft_text::craft_fonts::demand_script; + let demand: Vec<_> = vectorcraft_text::WEB_FONTS.iter().filter(|w| w.demand).collect(); + if demand.is_empty() { + eprintln!("skipped: built without craft-fonts, or one without NanumGothic and Noto Sans Devanagari"); + return; + } + let mut chars: std::collections::BTreeSet = LANGUAGES.iter().flat_map(|l| l.name.chars()).collect(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + chars.extend(entries.iter().flat_map(|(_, _, tr)| tr.chars())); + } + let mut missing = std::collections::BTreeMap::new(); + for w in demand { + let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.family == w.family && f.style == w.style) else { continue }; + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + db.add_font(f.bytes.to_vec()); + let face = db.face(f.family, f.style).expect("the craft-fonts face loads"); + let gone: String = chars.iter().filter(|c| demand_script(**c).is_some_and(|s| w.scripts.contains(&s)) && !face.covers(**c)).collect(); + if !gone.is_empty() { + missing.insert(w.family, gone); + } + } + assert!(missing.is_empty(), "characters the web's demand faces lack: {missing:#?}"); +} + /// The Traditional Chinese catalog holds no Simplified-only characters (a translation written /// in the wrong script would read as a typo to every user). #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c4c6ded189..a785625da9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -127,6 +127,7 @@ pub use services::{ }; use state::{GeometryStamp, InputGeneration, PendingScreenshot, QueuedScreenshot}; pub(crate) use state::{InputFrame, take_frame_once}; +pub use ui_fonts::on_missing_glyphs; pub struct VectorcraftApp { pub session: Session, diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index ac3f260e95..e9bae8b4af 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -6,52 +6,95 @@ //! don't have, an installed font covering it is looked for (in the background on native) and added //! to egui's families as their last fallback, on the baseline of each family's first face, from //! the next frame on. Text the UI fonts cover costs no font loading or memory. On the web, which -//! has no system fonts, such characters stay missing-glyph boxes (Japanese too, unless built with -//! craft-fonts). +//! has no system fonts, the shell is told which characters no loaded font covers +//! ([`on_missing_glyphs`]) and fetches a face for them (Korean, Devanagari) when it has one; until +//! a face arrives they stay missing-glyph boxes (Japanese too, unless built with craft-fonts). +//! Characters no font covered are looked for again whenever the font database changes. use std::collections::HashSet; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use egui::epaint::Shape; use egui::epaint::text::{FontInsert, FontPriority, InsertFontFamily}; use egui::{FontData, FontDefinitions, FontFamily, FontId, FontTweak, LayerId}; use vectorcraft_text::{FontDb, FontFace}; +/// Called with the painted characters no loaded or installed font covers. +static MISSING_GLYPHS: OnceLock = OnceLock::new(); + +/// Have `f` called (on the UI thread, after a frame) with the characters the interface painted +/// that no loaded or installed font covers, so it can load a font for them: the web shell fetches +/// its `demand` craft-fonts faces. A character is reported again only after the fonts change and it +/// is still not covered. The first call sets it; later calls are ignored. +pub fn on_missing_glyphs(f: fn(&[char])) { + let _ = MISSING_GLYPHS.set(f); +} + +/// What one search for fallback faces found. +struct Found { + /// The faces covering the characters looked for, each once. + faces: Vec>, + /// The characters no face covers. + uncovered: Vec, + /// [`FontDb::generation`] when the search ended. + generation: u64, +} + #[derive(Default)] pub(crate) struct UiFonts { /// Characters looked at already: the UI fonts have them, a fallback was added (or is being /// looked for), or no font has them. seen: HashSet, + /// Characters no font covered at the last search: looked for again once the font database's + /// generation is no longer [`UiFonts::searched`]. + uncovered: HashSet, + /// The font database's generation when the last search ended. + searched: u64, /// The fonts added to egui, by name. added: HashSet, /// The faces covering the characters being looked for (native: looked for on a thread). #[cfg(not(target_arch = "wasm32"))] - pending: Option>>>, + pending: Option>, } impl UiFonts { /// After a frame is laid out: add the fallback fonts found since the last frame, and look for /// fonts covering the characters this frame painted that the UI fonts lack. pub(crate) fn frame(&mut self, ctx: &egui::Context) { + self.frame_in(ctx, FontDb::global(), MISSING_GLYPHS.get().copied().unwrap_or(|_| {})); + } + + /// [`UiFonts::frame`] looking through `db`, reporting uncovered characters to `report`. + fn frame_in(&mut self, ctx: &egui::Context, db: &'static FontDb, report: fn(&[char])) { #[cfg(not(target_arch = "wasm32"))] - if let Some(faces) = self.pending.as_ref().and_then(|rx| rx.try_recv().ok()) { + if let Some(found) = self.pending.as_ref().and_then(|rx| rx.try_recv().ok()) { self.pending = None; - self.install(ctx, &faces); + self.found(ctx, found, report); + } + let mut missing = self.missing(ctx); + #[cfg(not(target_arch = "wasm32"))] + let idle = self.pending.is_none(); + #[cfg(target_arch = "wasm32")] + let idle = true; + // A font added since (a web face fetched for them) may cover them now. + if idle && !self.uncovered.is_empty() && db.generation() != self.searched { + missing.extend(self.uncovered.drain()); + missing.sort_unstable(); + missing.dedup(); } - let missing = self.missing(ctx); if missing.is_empty() { return; } let find = move || { - let mut faces: Vec> = vec![]; + let (mut faces, mut uncovered): (Vec>, Vec) = (vec![], vec![]); for c in missing { - if let Some(f) = FontDb::global().face_covering(c) - && !faces.iter().any(|x| x.id() == f.id()) - { - faces.push(f); + match db.face_covering(c) { + Some(f) if !faces.iter().any(|x| x.id() == f.id()) => faces.push(f), + Some(_) => {} + None => uncovered.push(c), } } - faces + Found { faces, uncovered, generation: db.generation() } }; // Native: the installed fonts are read off the UI thread. Characters met meanwhile wait for // the next search (they aren't marked seen until then). @@ -70,7 +113,17 @@ impl UiFonts { } // The web has only the loaded fonts to look through: quick, on this thread. #[cfg(target_arch = "wasm32")] - self.install(ctx, &find()); + self.found(ctx, find(), report); + } + + /// Add the faces a search found, and keep (and report) the characters it found no face for. + fn found(&mut self, ctx: &egui::Context, found: Found, report: fn(&[char])) { + self.install(ctx, &found.faces); + self.searched = found.generation; + if !found.uncovered.is_empty() { + report(&found.uncovered); + self.uncovered.extend(found.uncovered); + } } /// Characters painted this frame that the UI fonts lack and haven't been looked for, now @@ -135,8 +188,14 @@ impl UiFonts { /// Wait for the font search running, if any, and add what it found (tests). #[cfg(test)] pub(crate) fn finish(&mut self, ctx: &egui::Context) { - if let Some(faces) = self.pending.take().and_then(|rx| rx.recv().ok()) { - self.install(ctx, &faces); + self.finish_with(ctx, |_| {}); + } + + /// [`UiFonts::finish`], reporting uncovered characters to `report` (tests). + #[cfg(test)] + fn finish_with(&mut self, ctx: &egui::Context, report: fn(&[char])) { + if let Some(found) = self.pending.take().and_then(|rx| rx.recv().ok()) { + self.found(ctx, found, report); } } } @@ -399,8 +458,53 @@ mod tests { for c in installed { assert!(has_glyph(&ctx, c), "{c} has a glyph"); } - // Looked for once: a later frame starts no search. + // Looked for once: a later frame starts no search, unless characters no font covered are + // looked for again because the fonts changed (other tests add fonts meanwhile). + let searched = fonts.searched; frame(&ctx, &mut fonts, text); - assert!(fonts.pending.is_none()); + assert!(fonts.pending.is_none() || FontDb::global().generation() != searched, "a search with the fonts unchanged"); + } + + thread_local! { + static REPORTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + fn report(chars: &[char]) { + REPORTED.with(|r| r.borrow_mut().extend_from_slice(chars)); + } + + /// Run a frame painting `text` with fallbacks looked for in `db`, then wait for the search. + fn frame_in(ctx: &egui::Context, fonts: &mut UiFonts, text: &str, db: &'static FontDb) { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.label(text); + fonts.frame_in(ui.ctx(), db, report); + }); + out.textures_delta.clear(); + fonts.finish_with(ctx, report); + } + + /// A character painted while no font covers it is reported once, and draws once a font that + /// covers it is added (as the web fetches one), with no further search while the fonts stay + /// the same. + #[test] + fn a_font_added_later_draws_characters_painted_before_it() { + use vectorcraft_text::test_fonts::{TALL_IDEOGRAPH_FAMILY, tall_ideograph_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts::default(); + frame_in(&ctx, &mut fonts, "Layer 编", db); + assert!(!has_glyph(&ctx, '编'), "no font covers 编 yet"); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), ['编'], "reported once"); + frame_in(&ctx, &mut fonts, "Layer 编", db); + assert!(fonts.pending.is_none() && REPORTED.with(|r| r.borrow().len()) == 1, "no new search while the fonts are the same"); + db.add_font(tall_ideograph_font().expect("the test face builds")); + assert!(db.face(TALL_IDEOGRAPH_FAMILY, "Regular").is_some()); + // The next frame looks again and adds the face; the one after draws with it. + frame_in(&ctx, &mut fonts, "Layer 编", db); + frame_in(&ctx, &mut fonts, "Layer 编", db); + assert!(has_glyph(&ctx, '编'), "the added face draws 编"); + assert!(fonts.uncovered.is_empty()); + assert_eq!(REPORTED.with(|r| r.borrow().len()), 1, "a covered character is not reported again"); } } diff --git a/docs/gaps.md b/docs/gaps.md index d34956d4e0..6601892f04 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -775,7 +775,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Evidence:** Brazilian Portuguese catalog complete under the tests (menus, literals, messages; one|other plurals; #1914). Vietnamese catalog complete under the tests (menus, literals, messages; one plural form). Czech render-site bypasses reduced in file dialogs, diagnostics, preset names and contributor tooltips; gradient grammar and printer-mark context corrected (see [localization-parity.md](localization-parity.md)). Native review and the remaining missing-language work remain. - **Missing:** Arabic catalog and right-to-left layout; current gaps in other catalogs and native - review; Hindi wording/layout review and a web Devanagari font; a Korean UI font for the web. + review; Hindi wording/layout review. The web build fetches NanumGothic for Korean and Noto Sans + Devanagari for Hindi when the interface needs them (`crates/text/web-fonts.txt`, `demand`). Hindi now has a catalog and the pinned egui fork shapes Devanagari. Indonesian already has a catalog (see [localization-parity.md](localization-parity.md)); it is not an absent language. - **Estimate:** 50–85 h plus human review (Brazilian Portuguese completed 2026-10-14). diff --git a/docs/localization-hi.md b/docs/localization-hi.md index c130a7b088..733cfe46f0 100644 --- a/docs/localization-hi.md +++ b/docs/localization-hi.md @@ -85,9 +85,12 @@ The pinned egui fork shapes Devanagari with HarfRust. The desktop's existing `Ui finds an installed covering face, such as Nirmala UI, Kohinoor Devanagari or Noto Sans Devanagari. If a `CRAFT_FONTS_DIR` build includes a face tagged `Deva`, it is also installed at the end of each UI font family. No font binaries are added to this repository. Without either an embedded -or installed covering face, Hindi cannot display correctly. The web has no system fonts and -needs a Devanagari face supplied through craft-fonts; this catalog alone does not supply one. +or installed covering face, Hindi cannot display correctly. The web has no system fonts. A web +build made with craft-fonts serves Noto Sans Devanagari Regular beside the wasm and fetches it +when the interface language is Hindi or the interface paints Devanagari +(`crates/text/web-fonts.txt`, `demand`); until it arrives, Devanagari draws as missing-glyph boxes. +Other languages do not fetch it. Before release: native-speaker review of the draft (especially less common labels and error -messages), visual checks for clipped labels and matras at different UI scales, and a web-font -build. Reviewers should use this glossary to make terminology corrections consistently. +messages), and visual checks for clipped labels and matras at different UI scales, on the +desktop and on the web. Reviewers should use this glossary to make terminology corrections consistently. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 25dd92d552..3108b32140 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -29,20 +29,19 @@ Chinese by `imachus`). Only Georgian is recorded as reviewed by a native speaker | English | `en` | source, 100% | all | Latin | — | full | — | | Simplified Chinese (Mandarin) | `zh-hans` | 5,102 rows, 791 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | all | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (604 messages) | Latin | no | full | — (review) | -| Hindi | `hi` | 7,877 rows (2026-11-06): 2,537 `@msg`, 45 `@msgplural`, 38 `@plural`; no gaps in the untranslated report | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; wider proofread welcome | complete catalog, machine-assisted draft | native review, layout and web font | +| Hindi | `hi` | 7,877 rows (2026-11-06): 2,537 `@msg`, 45 `@msgplural`, 38 `@plural`; no gaps in the untranslated report | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; wider proofread welcome | complete catalog, machine-assisted draft | native review and layout | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 4,020 / 4,020 (100%) | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 6,106 catalog entries (counted 2026-10-31 on `main` at `d26dd933a`): menus, `tl!` literals and messages complete when counted; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 5,279 rows, 750 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial; one plural form | dialogs and tooltips all; 750 message rows (French has 796) | Latin | no | full | — (review) | | Japanese | `ja` | 4,004 / 4,020 (99.6%) | all | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | | German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (602 of 604 message rows; landed 2026-10-10) | Latin | contributor-written, not reviewed | full | — (review) | -| Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build has no Korean UI font yet (craft-fonts); IME path exists | no (AI-drafted) | full | — (review; web font) | +| Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build fetches NanumGothic from craft-fonts when the interface needs it; IME path exists | no (AI-drafted) | full | — (review) | | Vietnamese | `vi` | 4,886 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form; 4,046 plain + 18 `@plural` + 28 contextual + 794 `@msg` | all | Latin with Vietnamese diacritics (stacked marks attach in precomposed, decomposed and keyboard forms, #4491; glyph tests pass) | contributor is a Vietnamese speaker; AI-assisted draft, further native review welcome | full | — (review) | **Historical 12-language score: ~82%** (equal weights: 100 + 85 + 100 + 0 + 0 + 100 + 100 + 100 + 100 + 98 + 100 + 100, over 12). **To `full` for all twelve: ~50–85 h** (historical estimate, not re-scored here). Hindi now has -a complete catalog and UI shaping; its remaining work is native review, layout checking and the -web font. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each +a complete catalog and UI shaping; its remaining work is native review and layout checking. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each plus review. Native-speaker review is human work and isn't in the hours. ## Other shipped languages diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..dd5fb374e4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1293,6 +1293,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Line-end Punctuation Half Width, both composers measure a line with its last character set as narrow as Mojikumi sets it ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-mojikumi-for-japanese-text-composition.html)): a closing bracket, comma or full stop that fits at half width ends the line, and the character before it no longer goes to the next line with it. A mark that already lost its half to the punctuation after it and a line that ends in a hyphen take nothing more off, and the quarter em between Japanese and Latin text counts only where the line ends there. Kinsoku Shori Type and Burasagari Regular measure lines the same way; right-to-left lines and Mojikumi None break as before. In a frame that is not a rectangle, or with text wrap, a line's first word is measured as it is set (an opening bracket at its start flush, its last character narrowed) when layout looks for a line wide enough for it, and it ends only where the line may break, so kinsoku keeps an opening bracket with the character after it and a No Break run counts whole (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/vertical.rs`). Scores and estimates are unchanged. The Paragraph panel's Mojikumi Set lists the five predefined sets the help page names (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku and YakumonoZenkaku), then Line-end Punctuation Half Width, and `text.setFormat {mojikumi}` takes each of them. YakumonoHankaku sets every bracket, comma and full stop half width and takes a quarter em off each side of a middle dot; GyomatsuYakumonoHankaku keeps punctuation full width inside a line, sets an opening bracket flush at a line's start and a closing mark half width at its end, and takes the quarter em after a middle dot off at a line's end; GyomatsuYakumonoZenkaku keeps punctuation full width and adds a quarter em between Japanese and Latin text; YakumonoZenkaku sets characters as None does. These widths are VectorCraft's own rules, from the help page's one-line description of each set. Both composers and vertical type measure each line as it is set, the sets save with the document and paragraph styles, and a `.ai` save reports the new sets as left out (`crates/text/src/tests/vertical.rs`, `crates/ui-egui/src/panels/paragraph/tests.rs`). Scores and estimates are unchanged. Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). + On the web, Korean and Hindi interface text draws with real glyphs: a web build made with craft-fonts fetches NanumGothic for Hangul (about 2 MB) or Noto Sans Devanagari (about 280 KB) only when the interface language or the interface's own text (a layer or file name, the language picker) needs that script. The frame after the face arrives adds it to the interface fonts, and the frame after that draws the characters painted before it with that face. Sessions in other languages do not download them at startup. After a failed fetch the next try comes about 30 seconds later, and the wait doubles after each further failure, for at most five tries (`crates/text/web-fonts.txt`, `apps/vectorcraft-web/src/fonts.rs`, `apps/vectorcraft-web/src/demand.rs`, `crates/ui-egui/src/ui_fonts.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. From db26ce4a945368723aec538608c6c595626609ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:11:22 -0800 Subject: [PATCH 03/48] Tests: the script report test allows its script the folder it writes in A script now writes only in its own folders and in what a person allowed it, so the ui.inspect script report test picks the test folder in the script's folder dialog before the script exports into it. --- crates/ui-egui/src/tests/automation.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index d7f438d285..3683ec1ae7 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -1004,22 +1004,26 @@ fn ui_inspect_keeps_text_that_only_looks_like_a_library_id() { let _ = std::fs::remove_dir_all(base); } -/// `ui.inspect`'s `scriptReport` names a file the person's script wrote outside the read root, and -/// the included file a failed run stopped in (also in its error line), by its file name; the person -/// sees the paths. +/// `ui.inspect`'s `scriptReport` names a file the person's script wrote outside the read root (in +/// the folder the person allowed it), and the included file a failed run stopped in (also in its +/// error line), by its file name; the person sees the paths. #[test] fn ui_inspect_script_report_leaves_out_files_outside_the_read_root() { let (mut app, tx, base) = confined("inspect-script-report"); let (kept, hidden) = (s(base.join("in/kept.svg")), s(base.join("outside/hidden.svg"))); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let source = format!( - "vc.run('document.export', {{path: {kept}, format: 'svg'}}); vc.run('document.export', {{path: {hidden}, format: 'svg'}});", + "Folder.selectDialog('Folder'); vc.run('document.export', {{path: {kept}, format: 'svg'}}); vc.run('document.export', {{path: {hidden}, format: 'svg'}});", kept = json!(kept), hidden = json!(hidden) ); let finish = |app: &mut VectorcraftApp, params: Value| { app.session.execute("script.run", ¶ms).unwrap(); for _ in 0..10_000 { + if app.session.script_picker().is_some() { + let paths = vec![s(base.clone())]; + assert!(app.session.script_pick(vectorcraft_engine::script::files::PickAnswer::Allow { paths, always: false })); + } if app.session.script_pump().is_some() { break; } From 3b072ad0785756deb10a46e25c64f9cd1c9e12d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:19:20 -0800 Subject: [PATCH 04/48] Tests: the font-added-later test uses a character no craft-fonts face covers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit a_font_added_later_draws_characters_painted_before_it painted 编, which Noto Sans CJK SC covers. With craft-fonts embedded (as in CI), the test's font database already held that face, so nothing was reported and the test failed. It now paints U+F0000, a private-use character, drawn by a new test face (test_fonts::private_use_font) that maps only it. --- crates/text/src/test_fonts.rs | 13 +++++++++++++ crates/ui-egui/src/ui_fonts.rs | 24 +++++++++++++----------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 8c53e29a04..07af6e2d8d 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1322,6 +1322,19 @@ fn remapped_source_sans(family: &str, postscript: &str, mapping: &[(char, char)] Some(builder.build()) } +/// The family of [`private_use_font`]. +pub const PRIVATE_USE_FAMILY: &str = "Private Use Sans"; + +/// The character [`private_use_font`] maps: the first code point of Supplementary Private Use +/// Area-A, which no bundled or craft-fonts face covers. +pub const PRIVATE_USE_CHAR: char = '\u{F0000}'; + +/// A face that maps only [`PRIVATE_USE_CHAR`] to the bundled Source Sans 3 `H` outline, for tests +/// that need a character no other font covers, with or without craft-fonts. +pub fn private_use_font() -> Option> { + remapped_source_sans(PRIVATE_USE_FAMILY, "PrivateUseSans-Regular", &[(PRIVATE_USE_CHAR, 'H')]) +} + /// The family of [`tall_ideograph_font`]. pub const TALL_IDEOGRAPH_FAMILY: &str = "Tall Ideograph Sans"; diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index e9bae8b4af..63ac7b5fc2 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -485,25 +485,27 @@ mod tests { /// A character painted while no font covers it is reported once, and draws once a font that /// covers it is added (as the web fetches one), with no further search while the fonts stay - /// the same. + /// the same. The character is a private-use one, which no craft-fonts face covers either (the + /// database holds them when the build embeds craft-fonts). #[test] fn a_font_added_later_draws_characters_painted_before_it() { - use vectorcraft_text::test_fonts::{TALL_IDEOGRAPH_FAMILY, tall_ideograph_font}; + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, PRIVATE_USE_FAMILY, private_use_font}; let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let mut fonts = UiFonts::default(); - frame_in(&ctx, &mut fonts, "Layer 编", db); - assert!(!has_glyph(&ctx, '编'), "no font covers 编 yet"); - assert_eq!(REPORTED.with(|r| r.borrow().clone()), ['编'], "reported once"); - frame_in(&ctx, &mut fonts, "Layer 编", db); + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(!has_glyph(&ctx, PRIVATE_USE_CHAR), "no font covers the character yet"); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [PRIVATE_USE_CHAR], "reported once"); + frame_in(&ctx, &mut fonts, &text, db); assert!(fonts.pending.is_none() && REPORTED.with(|r| r.borrow().len()) == 1, "no new search while the fonts are the same"); - db.add_font(tall_ideograph_font().expect("the test face builds")); - assert!(db.face(TALL_IDEOGRAPH_FAMILY, "Regular").is_some()); + db.add_font(private_use_font().expect("the test face builds")); + assert!(db.face(PRIVATE_USE_FAMILY, "Regular").is_some()); // The next frame looks again and adds the face; the one after draws with it. - frame_in(&ctx, &mut fonts, "Layer 编", db); - frame_in(&ctx, &mut fonts, "Layer 编", db); - assert!(has_glyph(&ctx, '编'), "the added face draws 编"); + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); assert!(fonts.uncovered.is_empty()); assert_eq!(REPORTED.with(|r| r.borrow().len()), 1, "a covered character is not reported again"); } From d4912493296dd7889c94a792894681ba18b8aefb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:41:08 -0800 Subject: [PATCH 05/48] Web: a clock set back after a failed font fetch no longer stops its retry The demand-font retry deadlines were read from the wall clock. If the system clock went back after a fetch failed, the retry timer fired but the deadline still lay ahead, so the face was never fetched again that session. The deadlines now use the monotonic clock (now_ms), and a retry also starts when the clock reads earlier than the failure. --- apps/vectorcraft-web/src/demand.rs | 20 +++++++++++++++++--- apps/vectorcraft-web/src/fonts.rs | 4 ++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs index cbab6014bf..d2a2317bd3 100644 --- a/apps/vectorcraft-web/src/demand.rs +++ b/apps/vectorcraft-web/src/demand.rs @@ -15,9 +15,11 @@ enum State { tries: u32, }, Loaded, - /// `tries` fetches failed; the next may start at `retry_at` (ms). + /// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or + /// at once when the clock reads earlier than `failed_at`. Failed { tries: u32, + failed_at: f64, retry_at: f64, }, } @@ -42,7 +44,7 @@ impl Demand { let tries = match *state { State::Idle => Some(0), State::Loading { .. } | State::Loaded => None, - State::Failed { tries, retry_at } => (tries < MAX_TRIES && now >= retry_at).then_some(tries), + State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries), }; if let Some(tries) = tries { *state = State::Loading { tries }; @@ -64,7 +66,7 @@ impl Demand { } let tries = tries + 1; let wait = RETRY_MS << (tries - 1).min(4); - *state = State::Failed { tries, retry_at: now + f64::from(wait) }; + *state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) }; (tries < MAX_TRIES).then_some(wait) } } @@ -107,4 +109,16 @@ mod tests { assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None); assert!(d.start(&[1], 1e12).is_empty()); } + + /// A clock that reads earlier than the failure (one set back meanwhile) does not hold the + /// retry back: the timer that asks for it has waited already. + #[test] + fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() { + let mut d = Demand::default(); + let failed_at = 1e12; + d.start(&[0], failed_at); + assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS)); + assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting"); + assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour"); + } } diff --git a/apps/vectorcraft-web/src/fonts.rs b/apps/vectorcraft-web/src/fonts.rs index d2403e8084..873474f6c3 100644 --- a/apps/vectorcraft-web/src/fonts.rs +++ b/apps/vectorcraft-web/src/fonts.rs @@ -49,11 +49,11 @@ pub fn want_chars(chars: &[char]) { /// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start. /// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives. fn fetch_demand(wanted: &[usize]) { - for i in DEMAND.with(|d| d.borrow_mut().start(wanted, js_sys::Date::now())) { + for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) { let Some(f) = WEB_FONTS.get(i) else { continue }; wasm_bindgen_futures::spawn_local(async move { let ok = load(f, BACKGROUND_TIMEOUT_MS).await; - let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, js_sys::Date::now())); + let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms())); if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) { ctx.request_repaint(); } From eb1f29f94bcc66f4362b9dd448f43b3012005afe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:56:02 -0800 Subject: [PATCH 06/48] Scripts: a script in the settings folder reads only its own file there A script run from a file directly in the settings folder could read every file in that folder, Script Grants.json included, because its own folder was left open inside the fence. Only folders below the settings folder stay open now, and a script in the settings folder itself reads only its own file there. --- crates/engine/src/script/files.rs | 10 ++++++++-- crates/engine/src/tests/script_io.rs | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 37f3b93213..258d5a2863 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -79,7 +79,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; use super::{Host, bump}; -use crate::file_access::{ScriptRead, ScriptScope}; +use crate::file_access::{ScriptRead, ScriptScope, path_inside}; /// The most bytes of one file a script opens. pub const MAX_FILE_BYTES: usize = 8 << 20; @@ -331,7 +331,13 @@ impl Disk { let _ = d.saw(hash); } if let Some(f) = fenced { - let own = d.scope.roots().to_vec(); + // A script's folder inside the settings folder stays open; the settings folder itself + // does not, only the script's own file there. + let roots = d.scope.roots(); + let mut own: Vec = roots.iter().filter(|r| !path_inside(&f, r)).cloned().collect(); + if roots.iter().any(|r| path_inside(r, &f) && path_inside(&f, r)) { + own.extend(d.script.as_ref().map(|(p, _)| p.clone())); + } d.scope.fence(f.clone(), &own); d.writes.fence(f, &[]); } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 0d09bd2796..e3e7ade3a2 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1108,6 +1108,25 @@ fn script_files_in_a_folder_above_the_settings_folder_do_not_reach_it() { let _ = std::fs::remove_dir_all(base); } +/// A script run from the settings folder itself reads its own file there, but no other file in the +/// settings folder. +#[test] +fn script_files_in_the_settings_folder_do_not_reach_it() { + let base = folder("insettings"); + let mut s = Session::new(); + s.attach_script_data(base.join("main/Script Data")); + write(&base.join("main/Script Grants.json"), b"{\"version\": 1, \"grants\": []}"); + let r = run_in( + &mut s, + &base, + "var a = new File('main.jsx'), g = new File('Script Grants.json');\n\ + var out = [a.open('r'), a.read().length > 0]; a.close(); out.push(g.open('r'), g.error, g.exists); vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([[true, true, 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() { From 679d4ac03c1bdd8d58d2bb3893139e3eb6cd10a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:22:54 -0800 Subject: [PATCH 07/48] UI fonts: a font added during a fallback search has its characters looked for again The search for fallback faces now reads the font database's generation before its lookups instead of after them. When a font is added while the search runs, the generation kept is older than the database's, so the next frame looks again for the characters the search did not find. --- crates/ui-egui/src/ui_fonts.rs | 60 ++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 63ac7b5fc2..fd994fa6bf 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -36,10 +36,26 @@ struct Found { faces: Vec>, /// The characters no face covers. uncovered: Vec, - /// [`FontDb::generation`] when the search ended. + /// [`FontDb::generation`] when the search started. generation: u64, } +/// Look in `db` for the faces covering `chars`, each through `lookup`. +fn search(db: &FontDb, chars: Vec, lookup: impl Fn(&FontDb, char) -> Option>) -> Found { + // Read before the lookups: when a font is added during them, the generation kept is older than + // the database's, and the characters not found are looked for again. + let generation = db.generation(); + let (mut faces, mut uncovered): (Vec>, Vec) = (vec![], vec![]); + for c in chars { + match lookup(db, c) { + Some(f) if !faces.iter().any(|x| x.id() == f.id()) => faces.push(f), + Some(_) => {} + None => uncovered.push(c), + } + } + Found { faces, uncovered, generation } +} + #[derive(Default)] pub(crate) struct UiFonts { /// Characters looked at already: the UI fonts have them, a fallback was added (or is being @@ -48,7 +64,7 @@ pub(crate) struct UiFonts { /// Characters no font covered at the last search: looked for again once the font database's /// generation is no longer [`UiFonts::searched`]. uncovered: HashSet, - /// The font database's generation when the last search ended. + /// The font database's generation when the last search started. searched: u64, /// The fonts added to egui, by name. added: HashSet, @@ -85,17 +101,7 @@ impl UiFonts { if missing.is_empty() { return; } - let find = move || { - let (mut faces, mut uncovered): (Vec>, Vec) = (vec![], vec![]); - for c in missing { - match db.face_covering(c) { - Some(f) if !faces.iter().any(|x| x.id() == f.id()) => faces.push(f), - Some(_) => {} - None => uncovered.push(c), - } - } - Found { faces, uncovered, generation: db.generation() } - }; + let find = move || search(db, missing, FontDb::face_covering); // Native: the installed fonts are read off the UI thread. Characters met meanwhile wait for // the next search (they aren't marked seen until then). #[cfg(not(target_arch = "wasm32"))] @@ -491,6 +497,9 @@ mod tests { fn a_font_added_later_draws_characters_painted_before_it() { use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, PRIVATE_USE_FAMILY, private_use_font}; let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + // Scanned first, as the app's database is at startup: a first scan during the search would + // change the generation and start one more search. + db.families(); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let mut fonts = UiFonts::default(); @@ -509,4 +518,29 @@ mod tests { assert!(fonts.uncovered.is_empty()); assert_eq!(REPORTED.with(|r| r.borrow().len()), 1, "a covered character is not reported again"); } + + /// A font added while a search runs (another thread loading one) leaves the search's generation + /// older than the database's, so the next frame looks again for the characters it did not find. + #[test] + fn a_font_added_during_a_search_has_its_characters_looked_for_again() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + let found = search(db, vec![PRIVATE_USE_CHAR], |db, c| { + let face = db.face_covering(c); + db.add_font(private_use_font().expect("the test face builds")); + face + }); + assert_eq!(found.uncovered, [PRIVATE_USE_CHAR], "the lookup ran before the font was added"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts::default(); + fonts.found(&ctx, found, |_| {}); + // Painted before: the character is looked for again only because the fonts changed. + fonts.seen.insert(PRIVATE_USE_CHAR); + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); + } } From ea21d344c9f133f590a90b1a04ea4cee88fafe72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:36:36 -0800 Subject: [PATCH 08/48] i18n: Dutch rows for script file access messages --- crates/ui-egui/src/i18n/nl.tsv | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index df8847ea77..f1e6c1fc37 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -83,6 +83,27 @@ @msg Script file path exceeds 32,767 characters Het pad van het scriptbestand is langer dan 32.767 tekens @msg Script folder mask takes too many steps to match Het masker van de scriptmap vraagt te veel stappen om te vergelijken @msg the script opened more file data than one run may open (32 MiB) het script heeft meer bestandsgegevens geopend dan één uitvoering mag openen (32 MiB) +@msg Script file access denied: {path} Toegang tot het scriptbestand geweigerd: {path} +@msg Script file access to the app's own folders is not allowed Scriptbestanden mogen geen toegang krijgen tot de eigen mappen van de app +@msg Script file cannot encode the text Het scriptbestand kan de tekst niet coderen +@msg Script file could not be written Het scriptbestand kon niet worden geschreven +@msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord +@msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven +@msg Script file name is already in use De naam van het scriptbestand is al in gebruik +@msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn +@msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd +@msg Script file permission could not be saved De toestemming voor het scriptbestand kon niet worden opgeslagen +@msg Script folder is not empty De scriptmap is niet leeg +@msg Script files cannot make aliases Scriptbestanden kunnen geen aliassen maken +@msg Script file hidden setting cannot be changed De instelling Verborgen van het scriptbestand kan niet worden gewijzigd +@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}: een bestandsdialoogvenster kan niet worden geopend binnen een callback van een ingebouwde functie, een getter, een conversie of een bestand dat door $.evalFile wordt uitgevoerd; roep het aan vanuit de eigen code van het script +@msg the script wrote more file data than one run may write (32 MiB) het script heeft meer bestandsgegevens geschreven dan één uitvoering mag schrijven (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` voor het bestandsdialoogvenster van een script moet een van deze waarden zijn: once, always, deny, stop +@msg choose a file or folder first, or deny kies eerst een bestand of map, of weiger +@msg the script file permissions could not be saved: {e} de toestemmingen voor scriptbestanden konden niet worden opgeslagen: {e} +@msg this script's file access can be allowed only once de bestandstoegang van dit script kan maar één keer worden toegestaan +@msg Only the person at the keyboard can allow a script's file access Alleen de persoon aan het toetsenbord kan de bestandstoegang van een script toestaan +@msg A script is given at most 2,048 files: the files picked after them were left out Een script krijgt maximaal 2.048 bestanden: de bestanden die daarna zijn gekozen, zijn weggelaten @msg File.seek: takes a position and a mode File.seek: verwacht een positie en een modus @msg vc.run: give a command id, as a string vc.run: geef een opdracht-id, als string @msg vc.run: takes a command id and an object of parameters vc.run: verwacht een opdracht-id en een object met parameters From 4f8e1d5ed2d59ce6c0c4f5d2f50a4fe8075546dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:48:48 -0800 Subject: [PATCH 09/48] i18n: Hindi script file messages use the glossary term for save --- crates/ui-egui/src/i18n/hi.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index b01e66ed4f..07ff5595c2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6614,7 +6614,7 @@ antiAlias Sharp शार्प @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 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 स्क्रिप्ट फ़ाइल की छिपी सेटिंग बदली नहीं जा सकती @@ -6622,7 +6622,7 @@ antiAlias Sharp शार्प @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 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 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं From 44c3ef4f56233a76ee9feea1ed543195d10a6309 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 09:06:12 -0800 Subject: [PATCH 10/48] UI fonts: a font search that cannot start keeps its characters When the thread for a fallback font search could not be created, the characters taken for that search were lost. Characters no font covered were already removed from the retry list, and characters met that frame were already marked seen, so neither was looked for again. Now the characters no font covered go back to the retry list, and the ones met that frame are looked for when they are painted again. A web test also checks that a face fetched again after a failure is not fetched a second time at once, whether the interface asks for its script again or the retry timer fires. --- apps/vectorcraft-web/src/demand.rs | 15 ++++++++ crates/ui-egui/src/ui_fonts.rs | 58 ++++++++++++++++++++++++++++-- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs index d2a2317bd3..7583248701 100644 --- a/apps/vectorcraft-web/src/demand.rs +++ b/apps/vectorcraft-web/src/demand.rs @@ -110,6 +110,21 @@ mod tests { assert!(d.start(&[1], 1e12).is_empty()); } + /// While a face is fetched again after a failure, neither the interface asking for its script + /// again nor the retry timer starts a second fetch of it. + #[test] + fn a_face_being_fetched_again_is_not_fetched_twice_at_once() { + let mut d = Demand::default(); + d.start(&[0], 0.0); + assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS)); + let retry = f64::from(RETRY_MS); + assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice"); + assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again"); + assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer"); + assert_eq!(d.finished(0, true, retry + 2_000.0), None); + assert!(d.start(&[0], 1e12).is_empty(), "loaded"); + } + /// A clock that reads earlier than the failure (one set back meanwhile) does not hold the /// retry back: the timer that asks for it has waited already. #[test] diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index fd994fa6bf..73c1a30891 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -71,6 +71,9 @@ pub(crate) struct UiFonts { /// The faces covering the characters being looked for (native: looked for on a thread). #[cfg(not(target_arch = "wasm32"))] pending: Option>, + /// The search thread can't be created (tests). + #[cfg(all(test, not(target_arch = "wasm32")))] + spawn_fails: bool, } impl UiFonts { @@ -93,14 +96,18 @@ impl UiFonts { #[cfg(target_arch = "wasm32")] let idle = true; // A font added since (a web face fetched for them) may cover them now. - if idle && !self.uncovered.is_empty() && db.generation() != self.searched { - missing.extend(self.uncovered.drain()); + let retry: Vec = + if idle && !self.uncovered.is_empty() && db.generation() != self.searched { self.uncovered.drain().collect() } else { vec![] }; + if !retry.is_empty() { + missing.extend_from_slice(&retry); missing.sort_unstable(); missing.dedup(); } if missing.is_empty() { return; } + #[cfg(not(target_arch = "wasm32"))] + let looked_for = missing.clone(); let find = move || search(db, missing, FontDb::face_covering); // Native: the installed fonts are read off the UI thread. Characters met meanwhile wait for // the next search (they aren't marked seen until then). @@ -108,13 +115,20 @@ impl UiFonts { { let (tx, rx) = std::sync::mpsc::channel(); let repaint = ctx.clone(); - let spawned = std::thread::Builder::new().name("ui-font-fallback".into()).spawn(move || { + let spawned = self.spawn_search(move || { // The receiver is gone only when the app is. let _ = tx.send(find()); repaint.request_repaint(); }); if spawned.is_ok() { self.pending = Some(rx); + } else { + // Not looked for: the characters met this frame are looked for when painted again, + // and the ones no font covered wait for the fonts to change again. + for c in looked_for.iter().filter(|c| !retry.contains(c)) { + self.seen.remove(c); + } + self.uncovered.extend(retry); } } // The web has only the loaded fonts to look through: quick, on this thread. @@ -122,6 +136,16 @@ impl UiFonts { self.found(ctx, find(), report); } + /// Run `search` on a thread of its own. + #[cfg(not(target_arch = "wasm32"))] + fn spawn_search(&self, search: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + #[cfg(test)] + if self.spawn_fails { + return Err(std::io::Error::other("no thread for the font search")); + } + std::thread::Builder::new().name("ui-font-fallback".into()).spawn(search).map(|_| ()) + } + /// Add the faces a search found, and keep (and report) the characters it found no face for. fn found(&mut self, ctx: &egui::Context, found: Found, report: fn(&[char])) { self.install(ctx, &found.faces); @@ -543,4 +567,32 @@ mod tests { assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); assert!(fonts.uncovered.is_empty()); } + + /// A search whose thread can't be created leaves its characters to be looked for later: a + /// character painted for the first time is looked for when it is painted again, and one no font + /// covered stays waiting for the fonts to change. + #[test] + fn a_search_that_cannot_start_keeps_its_characters() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + db.families(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts { spawn_fails: true, ..UiFonts::default() }; + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.pending.is_none() && !fonts.seen.contains(&PRIVATE_USE_CHAR), "not looked for yet"); + fonts.spawn_fails = false; + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.uncovered.contains(&PRIVATE_USE_CHAR), "looked for when painted again"); + db.add_font(private_use_font().expect("the test face builds")); + fonts.spawn_fails = true; + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.uncovered.contains(&PRIVATE_USE_CHAR), "still waiting to be looked for again"); + fonts.spawn_fails = false; + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); + } } From dbfffc8ecb155e7f95ae9bcee3d88d6555c66796 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 10:09:27 -0800 Subject: [PATCH 11/48] Scripts: commands read through the gate in runs the person starts, and the grants file is not written over when it cannot be read - A command a script runs reads only where the script may, also in a run the person started; only reads of the app's own folders inside the command are exempt. - Always and script.grants.revoke leave a grants file they cannot read as it is, and fail. - script.grants names a path outside the automation read roots by its file name alone. - copy reads the source once, within the 8 MiB limit, writes those bytes, and gives the copy the source's permissions. - write joins its values as UTF-16 before making them text, so a surrogate pair split between two values is one character. --- crates/engine/src/cmd/scripts.rs | 12 ++++- crates/engine/src/file_access.rs | 45 ++++++++++++----- crates/engine/src/script/files.rs | 68 +++++++++++++++++++------- crates/engine/src/tests/script_io.rs | 62 +++++++++++++++++++++++ crates/engine/src/tests/script_run.rs | 6 ++- crates/js/src/file_classes.rs | 12 +++-- crates/ui-egui/src/tests/script_run.rs | 14 +++++- docs/mcp.md | 10 ++-- 8 files changed, 186 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 623ab8a87f..a620d398c8 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -341,7 +341,17 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { 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()})) + // A script or a granted path outside the automation read roots is named by its file name alone. + let mut grants = script::files::stored_grants(dir); + for g in &mut grants { + for key in ["script", "path"] { + if let Some(name) = g[key].as_str().and_then(hidden_name) { + g[key] = json!(name); + } + } + } + let file = file.to_string_lossy(); + Ok(json!({"grants": grants, "file": super::fileio::shown_path(&file)})) } fn grants_revoke(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 9aaeb58dab..8979914d43 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -176,7 +176,7 @@ fn with_scope(scope: Option, f: impl FnOnce() -> T) -> T { /// Run `f` with `roots` in force on this thread (`None`: as things stand). pub fn confine(roots: Option<&Arc>, f: impl FnOnce() -> T) -> T { match roots { - Some(r) => with_scope(Some(Scope::Confined(r.clone())), f), + Some(r) => with_gate_reads_exempt(false, || with_scope(Some(Scope::Confined(r.clone())), f)), None => f(), } } @@ -184,24 +184,44 @@ pub fn confine(roots: Option<&Arc>, f: impl FnOnce() -> T) - /// Run `f` with no roots in force on this thread: what the person at the keyboard does, and the /// app's own folders. pub fn unconfined(f: impl FnOnce() -> T) -> T { - with_scope(Some(Scope::Unconfined), f) + with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f)) +} + +thread_local! { + /// Are reads on this thread exempt from the gate of the script command it runs? Only inside an + /// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]). + static GATE_READS_EXEMPT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Puts the exemption it replaced back when dropped (also when `f` panics). +struct RestoreExempt(bool); + +impl Drop for RestoreExempt { + fn drop(&mut self) { + GATE_READS_EXEMPT.with(|e| e.set(self.0)); + } +} + +fn with_gate_reads_exempt(exempt: bool, f: impl FnOnce() -> T) -> T { + let _restore = RestoreExempt(GATE_READS_EXEMPT.with(|e| e.replace(exempt))); + f() } /// 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, Option>); +pub struct ScopeHandle(Option, Option>, bool); impl ScopeHandle { /// The scope of the calling thread. pub fn capture() -> Self { - Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone())) + Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { - let Self(scope, gate) = self; - with_gate(gate, || with_scope(scope, f)) + let Self(scope, gate, exempt) = self; + with_gate(gate, || with_gate_reads_exempt(exempt, || with_scope(scope, f))) } } @@ -252,17 +272,18 @@ fn with_gate(gate: Option>, f: impl FnOnce() -> T) -> T { } /// 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. +/// writes must pass the gate as well as the automation roots, also when the run itself is +/// [`unconfined`] (one the person started). Reads of the app's own folders, inside an +/// [`unconfined`] the command enters, 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) + with_gate(Some(Arc::new(gate)), || with_gate_reads_exempt(false, f)) } /// May `path` be read (or written) by the script command this thread runs? Always outside one, -/// and for a read inside [`unconfined`]. +/// and for a read inside an [`unconfined`] the command entered. fn check_gate(path: &str, access: Access) -> Result<(), String> { - if matches!(access, Access::Read) && SCOPE.with(|s| matches!(*s.borrow(), Some(Scope::Unconfined))) { + if matches!(access, Access::Read) && GATE_READS_EXEMPT.with(std::cell::Cell::get) { return Ok(()); } GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 258d5a2863..ddc574ee71 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -431,7 +431,7 @@ impl Disk { } 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); + let Ok(mut grants) = try_read_store(&store) else { return }; for g in &mut grants { let ours = g["script"] == *script && g["sha256"] == *hash @@ -565,7 +565,8 @@ impl Disk { /// 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); + // A grants file that is there but cannot be read is left as it is. + let mut grants = try_read_store(&store).map_err(|_| NOT_SAVED)?; let script = shown(script); let code: Vec<&String> = self.ran.iter().collect(); for p in paths { @@ -880,15 +881,34 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { Ok(bytes) } -/// The grants the grants file at `store` holds; none when it is missing or cannot be read. +/// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant +/// that is not well formed is left out. fn read_store(store: &Path) -> Vec { - let Ok(bytes) = read_head(store, MAX_STORE_BYTES) else { return Vec::new() }; + load_store(store, false).unwrap_or_default() +} + +/// The grants the grants file at `store` holds, to change and write back; none when it is missing, +/// and `Err` when it is there but cannot be read, is too large, is not a grants file of this +/// version, or holds a grant that is not well formed or more grants than may be kept, so that a +/// change is not written over it. +fn try_read_store(store: &Path) -> std::io::Result> { + load_store(store, true) +} + +/// The grants file at `store` read as [`read_store`] reads it, or with `strict` as +/// [`try_read_store`] does. +fn load_store(store: &Path, strict: bool) -> std::io::Result> { + let bytes = match read_head(store, MAX_STORE_BYTES) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(e), + }; if bytes.len() > MAX_STORE_BYTES { - return Vec::new(); + return Err(std::io::Error::other("the grants file is too large")); } - let Ok(v) = serde_json::from_slice::(&bytes) else { return Vec::new() }; + let v = serde_json::from_slice::(&bytes).map_err(std::io::Error::other)?; if v["version"] != 1 { - return Vec::new(); + return Err(std::io::Error::other("the grants file has another version")); } let valid = |g: &serde_json::Value| { g["script"].is_string() @@ -898,7 +918,14 @@ fn read_store(store: &Path) -> Vec { && 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() + if strict { + let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?; + if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) { + return Err(std::io::Error::other("the grants file holds a grant that cannot be read")); + } + return Ok(grants.clone()); + } + Ok(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. @@ -930,7 +957,7 @@ pub(crate) fn stored_grants(data_dir: &Path) -> Vec { /// → 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 grants = try_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(); @@ -1636,28 +1663,33 @@ fn copy(host: &Host, a: &[Data]) -> Result { 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 bytes are read once, no more than the limit, and those bytes are what is charged and + // written: a source that grows after it is read does not copy more. + let copied = match read_head(&source, MAX_FILE_BYTES) { + Ok(bytes) if bytes.len() > MAX_FILE_BYTES => return Ok(error(TOO_LARGE)), + Ok(bytes) => bytes, + Err(_) => return Ok(error(READ_FAILED)), + }; // 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) }; + disk.charge_write(copied.len().saturating_mul(holders.saturating_add(usize::from(!itself))))?; + // The copy takes the source's permissions, as `std::fs::copy` gives them. + let permissions = std::fs::metadata(&source).map(|m| m.permissions()); + let r = + if itself { Ok(()) } else { std::fs::write(&target, &copied).and_then(|()| permissions.and_then(|p| std::fs::set_permissions(&target, p))) }; 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(); + if r.is_ok() { 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))) + Ok(done(r.map_err(|_| WRITE_FAILED))) } /// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to. diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e3e7ade3a2..b9bb6a2162 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -730,6 +730,34 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// `copy` gives the copy the source's permissions: the copy of a read-only file is read-only. +#[test] +fn script_file_copy_keeps_the_source_read_only() { + let base = folder("copyreadonly"); + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('x'); s.close(); s.readonly = true;\n\ + var out = [s.copy(d + '/t.txt'), new File(d + '/t.txt').readonly, new File(d + '/t.txt').length];\n\ + s.readonly = false; new File(d + '/t.txt').readonly = false; vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, true, 1]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `write` with several values joins them before making them text, so a surrogate pair split +/// between two values is written as one character. +#[test] +fn script_file_write_joins_a_surrogate_pair_split_between_values() { + let base = folder("surrogates"); + let r = run( + &base, + "var f = new File(Folder.temp.fsName + '/s.txt'); f.encoding = 'UTF-8'; f.open('w'); f.write('\\uD83D', '\\uDE00'); f.close();\n\ + f.open('r'); var t = f.read(); f.close(); vc.log([t === '\\uD83D\\uDE00', t.length]);", + ); + assert_eq!(r["log"], json!([[true, 2]])); + 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] @@ -754,6 +782,34 @@ fn script_file_grants_file_stays_within_its_size_limit() { let _ = std::fs::remove_dir_all(base); } +/// A grants file that is there but cannot be read (another version, not JSON, a grant that is not +/// well formed, or no list of grants) is not written over: a grant picked with Always is not kept, and a revoke fails, so the grants it holds stay. +#[test] +fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() { + let cases = [ + ("newer", br#"{"version": 2, "grants": [{"script": "x"}]}"#.as_slice()), + ("broken", b"{ not json".as_slice()), + ("malformed", br#"{"version": 1, "grants": [{"script": "x"}]}"#.as_slice()), + ("nolist", br#"{"version": 1, "grants": {}}"#.as_slice()), + ]; + for (name, held) in cases { + let base = folder(&format!("store-{name}")); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + let store = base.join("settings/Script Grants.json"); + write(&store, held); + let mut s = with_data(&base); + 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(), held, "{name}: the grants file is left as it was"); + assert!(s.execute("script.grants.revoke", &json!({"all": true})).is_err(), "{name}"); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: a revoke leaves it too"); + 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() { @@ -1387,6 +1443,12 @@ fn script_file_dialog_grants_are_kept_for_the_same_script_text() { 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); + // Under automation read roots, a path outside them is named by its file name alone. + let roots = AutomationRoots::new(&[&base.join("main")], &[]).unwrap(); + let hidden = confine(roots.as_ref(), || s.execute("script.grants", &json!({}))).unwrap(); + assert_eq!(hidden["grants"][0]["path"], "out.txt", "{hidden}"); + assert_eq!(hidden["grants"][0]["script"], grants["grants"][0]["script"], "the script inside the roots is named whole: {hidden}"); + assert_eq!(hidden["file"], "Script Grants.json", "{hidden}"); start_framed(&mut s, &base, &text); let r = pump_to_picker(&mut s).unwrap().unwrap(); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 0a4037a0d8..ab8345e6cb 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -316,7 +316,8 @@ fn an_export_that_fails_names_no_file() { } /// 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. +/// temporary folder and what a person allowed it, here), and the files of the open documents, +/// also in a run the person started. #[test] fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let dir = fresh_folder("gate"); @@ -354,6 +355,9 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { 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()); + let source = format!("{}{}", call("document.open", &own), call("document.open", &outside.join("copy.svg"))); + let r = crate::file_access::unconfined(|| run(&mut s, &source)).unwrap(); + assert_eq!(r["log"], json!(["ok", "denied"]), "a run the person starts reads through the gate as well: {r}"); 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}"); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index f6d87de964..0d8d997a91 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -542,19 +542,21 @@ fn write_values(i: &mut Interp, this: &Value, args: &[Value], what: &str, line: 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; + // The values are joined as UTF-16 code units and made text once, so a surrogate pair split + // between two values is one character. + let mut joined: Vec = Vec::new(); for a in args { i.use_fuel()?; let s = i.to_str(a)?; - units = units.saturating_add(s.len()); - if units > max { + if joined.len().saturating_add(s.len()) > max { let m = message(i, "tooLarge")?; set_slot(i, o, ERROR, m)?; return Ok(Value::Bool(false)); } - text.push_str(&s.to_rust_string()); + joined.extend_from_slice(&s.flat()); } + let mut text = String::from_utf16_lossy(&joined); + drop(joined); if line { text.push_str(line_end(i, o)?); } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index ba6553e068..202ac35c6f 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -553,10 +553,18 @@ fn enter_in_a_scripts_file_dialog_denies() { 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. +/// Enter on the file dialog's focused Choose… button goes to that button, which opens the folder +/// picker once, and does not deny. #[test] fn enter_on_a_focused_choose_button_does_not_deny() { - let mut app = app(); + let asked = std::rc::Rc::new(std::cell::Cell::new(0usize)); + let counted = asked.clone(); + let pick_folder: Box Option> = Box::new(move || { + counted.set(counted.get() + 1); + None + }); + let mut app = VectorcraftApp::new(Session::new(), crate::Services { pick_folder: Some(pick_folder), ..Default::default() }); + app.run("file.new", json!({})).unwrap(); 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); @@ -571,8 +579,10 @@ fn enter_on_a_focused_choose_button_does_not_deny() { frame(&mut app, events); } assert!(ctx.memory(|m| m.focused().is_some()), "Tab gives a button the keyboard focus"); + assert_eq!(asked.get(), 0); frame(&mut app, vec![key(egui::Key::Enter)]); frame(&mut app, vec![]); + assert_eq!(asked.get(), 1, "Enter chose the focused Choose… button"); 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); diff --git a/docs/mcp.md b/docs/mcp.md index 481961c67f..8fefe75b07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2263,7 +2263,7 @@ 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 ``. + when the script writes `\uFEFF`. - `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 @@ -2345,10 +2345,12 @@ VectorCraft writes files by these rules of its own: 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 +file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them +is given as its file name alone. `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. +runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but +cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script +cannot run either command. ```json {"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} From b153a3d7a673fab8f0baf2f294917a2004e1a1fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 10:31:59 -0800 Subject: [PATCH 12/48] Scripts: a file whose close could not write it stays open, so a later close tries again --- crates/engine/src/tests/script_io.rs | 15 +++++++++++++++ crates/js/src/file_classes.rs | 7 +++++-- docs/mcp.md | 3 ++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index b9bb6a2162..4fae8d33b8 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -730,6 +730,21 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// A file whose `close` could not write it stays open, so a later `close` writes it. +#[test] +fn script_file_close_that_fails_can_be_tried_again() { + let base = folder("closeagain"); + let r = run( + &base, + "var d = Folder.temp.fsName, f = new File(d + '/f.txt'); f.open('w'); f.write('kept');\n\ + new File(f.fsName).readonly = true; var out = [f.close(), f.error];\n\ + new File(f.fsName).readonly = false; out.push(f.close());\n\ + var g = new File(f.fsName); g.open('r'); out.push(g.read()); g.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[false, "Script file could not be written", true, "kept"]])); + let _ = std::fs::remove_dir_all(base); +} + /// `copy` gives the copy the source's permissions: the copy of a read-only file is read-only. #[test] fn script_file_copy_keeps_the_source_read_only() { diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 0d8d997a91..7ebcc7bfae 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -220,14 +220,17 @@ fn is_open(i: &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. +/// after setting `error` when that could not be written; the file then stays open, so a later +/// `close` tries again. fn close_open(i: &mut Interp, o: ObjId) -> JsResult { let mut written = true; if let Some(h) = is_open(i, o)? { let r = host(i, "close", &[h])?; written = outcome(i, o, &r)?; } - set_slot(i, o, HANDLE, Value::Number(-1.0))?; + if written { + set_slot(i, o, HANDLE, Value::Number(-1.0))?; + } Ok(written) } diff --git a/docs/mcp.md b/docs/mcp.md index 8fefe75b07..1b642340cb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2300,7 +2300,8 @@ VectorCraft writes files by these rules of its own: `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 + that `close` could not write stays open, so a later `close` tries again, and is written again when the run ends; 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 From 3ef3ed568a0d97ee6e3c3d0f31fe3c43659baa26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 10:55:29 -0800 Subject: [PATCH 13/48] Scripts: script.grants.revoke does not look up a path outside the automation read roots --- crates/engine/src/cmd/scripts.rs | 13 +++++++++---- crates/engine/src/tests/script_io.rs | 19 +++++++++++++++++-- docs/mcp.md | 3 ++- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index a620d398c8..3af4f351f1 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "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}", + "{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 (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -358,9 +358,14 @@ 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()))) - } + // A path the request may not read (outside the automation read roots, a network path among + // them) is compared as written, without looking it up. + Some(Value::String(t)) if !t.is_empty() => Ok(Some( + crate::file_access::check_read(t) + .ok() + .and_then(|()| std::fs::canonicalize(t).ok()) + .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")?); diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 4fae8d33b8..39276d737f 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1492,8 +1492,23 @@ fn script_file_dialog_grants_are_kept_for_the_same_script_text() { 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); + // Under automation read roots, a path outside them is not looked up: a link there to the + // granted file does not name it. + #[cfg(unix)] + { + let link = base.join("link.txt"); + std::os::unix::fs::symlink(&out, &link).unwrap(); + let roots = AutomationRoots::new(&[&base.join("main")], &[]).unwrap(); + let r = confine(roots.as_ref(), || s.execute("script.grants.revoke", &json!({"path": link.to_string_lossy()}))).unwrap(); + assert_eq!(r["removed"], 0, "{r}"); + let r = s.execute("script.grants.revoke", &json!({"path": link.to_string_lossy()})).unwrap(); + assert_eq!(r["removed"], 1, "without roots the link is followed: {r}"); + } + #[cfg(not(unix))] + { + 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()); diff --git a/docs/mcp.md b/docs/mcp.md index 1b642340cb..2e8843ce07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2348,7 +2348,8 @@ grant, which covers everything in the folder (a file's grant covers its own path takes its place), and `file` the grants file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them is given as its file name alone. `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 +a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is +matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script cannot run either command. From 0300f7095079cdfaa8dd4e49363bc0783e7ffc41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 14:45:05 -0800 Subject: [PATCH 14/48] Scripts: file and folder dialogs are native functions that pause the script File.openDialog, File.saveDialog, Folder.selectDialog and the openDlg, saveDlg and selectDlg methods are now built-ins written in Rust instead of JavaScript source compiled when File and Folder are installed. The interpreter gains a native function form that asks the host for a value: it gives the host call to make and a function that takes the answer. When the host waits, the run pauses at the call, and the answer goes to that function before the next instruction, so a filter function or an exception it throws runs at the dialog's call. Arguments, filters, multiSelect, the start folder and the null and error answers work as before. --- crates/js/src/builtins.rs | 11 +- crates/js/src/file_classes.rs | 297 ++++++++++++++++++++++++---------- crates/js/src/heap.rs | 4 +- crates/js/src/interp.rs | 83 ++++++++++ crates/js/src/realm.rs | 6 +- 5 files changed, 313 insertions(+), 88 deletions(-) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 92db4e6502..98327a2b61 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -38,6 +38,15 @@ pub(crate) fn native(interp: &mut Interp, name: &'static str, f: NativeFn, lengt Ok(o) } +/// A built-in function object that may wait for the host ([`crate::interp::Pause`]), defined as +/// `name` on `on` the way [`method`] defines one. +pub(crate) fn pausable_method(interp: &mut Interp, on: ObjId, name: &'static str, f: crate::interp::PausableFn, length: u32) -> JsResult<()> { + let proto = interp.intrinsics.function_proto; + let m = alloc(interp, Class::Function(Func::Pausable { f, name }), Some(proto)); + interp.define(m, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) +} + pub(crate) fn method(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn, length: u32) -> JsResult<()> { let m = native(interp, name, f, length, NativeKind::Plain, false)?; interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) @@ -514,7 +523,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); return Ok(Value::String(Str::from_units(units.to_vec()))); } - Some(Func::Native { name, .. }) => format!("function {name}() {{ [native code] }}"), + Some(Func::Native { name, .. } | Func::Pausable { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Host { name, .. } | Func::Data { name, .. } | Func::Eval { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Bound { .. }) => "function () { [native code] }".to_string(), None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")), diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 7ebcc7bfae..f1bba51291 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -14,8 +14,8 @@ //! //! `write` and `writeln` join their values as `String(value)` gives them, and `writeln` adds the //! line end `lineFeed` names: CRLF for `Windows`, CR for `Macintosh` and LF otherwise. The file -//! dialogs are functions of script code that call the host's `pick`, so that a run can wait there -//! for the person's answer; they give a `File`, a `Folder`, an array of `File`s or `null`. +//! dialogs are built-ins that ask the host's `pick` and may pause the run until the person answers +//! ([`crate::interp::Pause`]); they give a `File`, a `Folder`, an array of `File`s or `null`. //! //! A method whose host call fails sets `error` and returns `false`, `null` or an empty string. A //! count or position that is not a finite number, a negative count and a seek mode other than 0, 1 @@ -24,11 +24,10 @@ //! true value for; every entry takes fuel. use crate::HostItem; -use crate::builtins::{arg, constructor, data, method, native, put_at}; -use crate::bytecode::CodeKind; +use crate::builtins::{arg, constructor, data, method, native, pausable_method, put_at}; use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; -use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; -use crate::value::Value; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; +use crate::value::{Value, index_key}; /// The objects of `File` and `Folder`, kept by the realm, and `Folder.current`. #[derive(Clone, Debug)] @@ -579,69 +578,79 @@ fn writeln(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { - let kind = arg(args, 0); - let start = match arg(args, 1) { - Value::Null => Value::str(""), - s => this_path(i, &s, "dialog")?.1, +/// Asks the host's `pick` for the dialog `kind` (`open`, `save` or `folder`), with the arguments +/// `[kind, prompt, multi, start, types]`. `me` is the `File` or `Folder` whose `openDlg`, `saveDlg` +/// or `selectDlg` was called, or `None` for the class's own dialog: the dialog starts at its path, +/// and an `{error}` answer sets its `error`. The prompt is `String(prompt)`, or `""` for +/// `undefined` and `null`. A `filter` that is a string gives the file types; one that is a function +/// is called with each file picked ([`picked`]). The run may pause at `pick` until the person +/// answers. +fn ask_pick(i: &mut Interp, kind: &'static str, me: Option<&Value>, prompt: &Value, multi: bool, filter: &Value) -> JsResult { + let start = match me { + None => Value::str(""), + Some(me) => this_path(i, me, "dialog")?.1, }; - let prompt = match arg(args, 2) { + let prompt = match prompt { Value::Undefined | Value::Null => Value::str(""), - p => Value::String(i.to_str(&p)?), + 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, + let types = match filter { + f @ Value::String(_) => f.clone(), _ => 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))); + let pick = host_value(i, "pick")?; + Ok(Pause { + host: pick, + args: vec![Value::str(kind), prompt, Value::Bool(multi), start, types], + keep: vec![Value::Bool(kind == "folder"), me.cloned().unwrap_or(Value::Null), filter.clone()], + resume: picked, + }) +} + +/// What a file dialog gives for `pick`'s `answer`, with `[folder, me, filter]` kept from +/// [`ask_pick`]: the objects [`wrap`] makes, of which a `filter` that is a function keeps the +/// files it gives a true value for, or `null` when it keeps none. +fn picked(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { + let files = wrap(i, arg(keep, 0).truthy(), &arg(keep, 1), answer)?; + let filter = arg(keep, 2); + if !i.is_callable(&filter) { + return Ok(files); + } + let Some(o) = files.as_object() else { return Ok(files) }; + let length = match &i.object(o)?.class { + Class::Array { length, .. } => Some(*length), + _ => None, + }; + let Some(length) = length else { + let kept = i.rooted(std::slice::from_ref(&files), |i| i.call(&filter, &Value::Undefined, std::slice::from_ref(&files)))?; + return Ok(if kept.truthy() { files } else { Value::Null }); + }; + i.rooted(std::slice::from_ref(&files), |i| { + 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| { - 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)?; + let mut n = 0.0; + for at in 0..length { + i.use_fuel()?; + let file = i.get_value(&files, &index_key(at))?; + let kept = i.rooted(std::slice::from_ref(&file), |i| i.call(&filter, &Value::Undefined, std::slice::from_ref(&file)))?; + if kept.truthy() { + put_at(i, out, n, file)?; + n += 1.0; + } } - Ok(Value::Object(out)) + Ok(if n > 0.0 { Value::Object(out) } else { Value::Null }) }) }) } -/// `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 { +/// The `File` (a `Folder` for a `folder` dialog) for each path `pick` gave in `answer`, an array of +/// them for a list, `null` for `null`, and `null` after setting the `error` of `me`, when it is a +/// `File` or `Folder`, for `{error}`. +fn wrap(i: &mut Interp, folder: bool, me: &Value, answer: Value) -> 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); + let proto = if folder { c.folder_proto } else { c.file_proto }; match &answer { Value::String(_) => return instance(i, proto, answer.clone()), Value::Object(_) => {} @@ -649,7 +658,7 @@ fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { } 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() + if let Some(o) = me.as_object() && matches!(slot(i, o, PATH)?, Value::String(_)) { set_slot(i, o, ERROR, error)?; @@ -676,33 +685,44 @@ fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { }) } +/// `File.openDialog(prompt, filter, multiSelect)`. +fn open_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult { + ask_pick(i, "open", None, &arg(args, 0), arg(args, 2).truthy(), &arg(args, 1)) +} + +/// `File.saveDialog(prompt, filter)`. +fn save_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult { + ask_pick(i, "save", None, &arg(args, 0), false, &arg(args, 1)) +} + +/// `File.prototype.openDlg(prompt, filter, multiSelect)`. +fn open_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult { + ask_pick(i, "open", Some(&this), &arg(args, 0), arg(args, 2).truthy(), &arg(args, 1)) +} + +/// `File.prototype.saveDlg(prompt, filter)`. +fn save_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult { + ask_pick(i, "save", Some(&this), &arg(args, 0), false, &arg(args, 1)) +} + +/// `Folder.selectDialog(prompt)`. +fn select_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult { + ask_pick(i, "folder", None, &arg(args, 0), false, &Value::Null) +} + +/// `Folder.prototype.selectDlg(prompt)`. +fn select_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult { + ask_pick(i, "folder", Some(&this), &arg(args, 0), false, &Value::Null) +} + /// 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(()) - }) + pausable_method(i, file, "openDialog", open_dialog, 3)?; + pausable_method(i, file, "saveDialog", save_dialog, 2)?; + pausable_method(i, file_proto, "openDlg", open_dlg, 3)?; + pausable_method(i, file_proto, "saveDlg", save_dlg, 2)?; + pausable_method(i, folder, "selectDialog", select_dialog, 1)?; + pausable_method(i, folder_proto, "selectDlg", select_dlg, 1) } fn text_static(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { @@ -1084,13 +1104,51 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul #[cfg(test)] mod tests { + use std::cell::RefCell; use std::rc::Rc; - use crate::{Data, HostItem, JsValue, Realm}; + use crate::{Data, HostError, HostItem, JsValue, Progress, Realm}; /// A host whose paths are `/` and a name, where `/d` is a folder holding `a` and `b` and every /// other path is missing. fn realm() -> Realm { + realm_with(|_| Vec::new()) + } + + /// [`realm`] with a `pick` that waits where it can and throws where it cannot. → the arguments + /// of each call, joined with `|`. + fn dialog_realm() -> (Realm, Rc>>) { + let asked: Rc>> = Rc::default(); + let calls = asked.clone(); + let r = realm_with(move |r| { + let can_wait = r.wait_flag(); + let pick = move |a: Vec| -> Result { + let text = |d: &Data| match d { + Data::String(s) => s.clone(), + Data::Bool(b) => b.to_string(), + other => format!("{other:?}"), + }; + calls.borrow_mut().push(a.iter().map(text).collect::>().join("|")); + if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) } + }; + vec![("pick".into(), HostItem::Function(Rc::new(pick)))] + }); + (r, asked) + } + + /// Advances the run until it waits or ends. → its value when it ended. + fn until_wait(r: &mut Realm) -> Option { + for _ in 0..10_000 { + match r.advance(1_000).unwrap() { + Progress::Done(v) => return Some(v), + Progress::Paused if r.waits() => return None, + Progress::Paused => {} + } + } + panic!("the run neither waited nor ended") + } + + fn realm_with(more: impl FnOnce(&Realm) -> Vec<(String, HostItem)>) -> Realm { let f = |g: fn(&[Data]) -> Data| HostItem::Function(Rc::new(move |a: Vec| Ok(g(&a)))); let text = |a: &[Data], i: usize| match a.get(i) { Some(Data::String(s)) => s.clone(), @@ -1120,7 +1178,7 @@ mod tests { Ok(obj(vec![("entries", Data::Array(vec![e("a"), e("b")]))])) }; let mut r = Realm::new(); - let items: Vec<(String, HostItem)> = vec![ + let mut items: Vec<(String, HostItem)> = vec![ ("text".into(), HostItem::Object(messages.to_vec())), ("system".into(), HostItem::Value(Data::String("Unix".into()))), ("lineFeed".into(), HostItem::Value(Data::String("Unix".into()))), @@ -1131,10 +1189,79 @@ mod tests { ("tempName".into(), f(|_| Data::String("/tmp1".into()))), ("locations".into(), f(|_| Data::Object(vec![]))), ]; + items.extend(more(&r)); r.define_file_classes(items).unwrap(); r } + #[test] + fn a_dialog_pauses_the_run_and_its_answer_becomes_files() { + let (mut r, asked) = dialog_realm(); + let v = r.run("[File.openDialog.length, File.prototype.saveDlg.length, String(Folder.selectDialog).indexOf('[native code]') > 0].join()"); + assert_eq!(v.unwrap(), JsValue::String("3,2,true".into()), "the dialogs are built-ins"); + r.start("var f = File.openDialog('Pick', 'Text:*.txt', 1); [f.length, f[0].name, f[1].fsName, f[1] instanceof File].join()").unwrap(); + assert_eq!(until_wait(&mut r), None); + assert_eq!(*asked.borrow(), ["open|Pick|true||Text:*.txt"]); + r.answer(Data::Array(vec![Data::String("/a".into()), Data::String("/b".into())])).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("2,a,/b,true".into()))); + r.start("var g = new Folder('d').selectDlg(5); [g.name, g instanceof Folder].join()").unwrap(); + assert_eq!(until_wait(&mut r), None); + assert_eq!(asked.borrow()[1], "folder|5|false|/d|", "the folder's own dialog starts at its path"); + r.answer(Data::String("/e".into())).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("e,true".into()))); + } + + #[test] + fn a_canceled_dialog_gives_null_and_an_error_answer_sets_error() { + let (mut r, asked) = dialog_realm(); + r.start( + "var d = new File('x'); var a = File.saveDialog(); var b = d.saveDlg('Save', function () { return true; }); [a, b, d.error].join('|')", + ) + .unwrap(); + assert_eq!(until_wait(&mut r), None); + r.answer(Data::Null).unwrap(); + assert_eq!(until_wait(&mut r), None, "a canceled dialog lets the run go on to the next one"); + assert_eq!(asked.borrow()[1], "save|Save|false|/x|", "a filter that is not a string gives no file types"); + r.answer(Data::Object(vec![("error".into(), Data::String("denied".into()))])).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("||denied".into()))); + r.start("File.openDialog(); 'went on'").unwrap(); + assert_eq!(until_wait(&mut r), None); + r.end(); + assert!(!r.waits() && !r.is_running(), "a run ended at a dialog drops it"); + assert_eq!(r.run("'next'").unwrap(), JsValue::String("next".into())); + let e = r.run("File.openDialog()").unwrap_err(); + assert!(e.message.contains("cannot wait here"), "a run that cannot pause does not wait: {e:?}"); + let e = r.run("File.prototype.openDlg.call({})").unwrap_err(); + assert!(e.message.contains("is not a File or a Folder"), "{e:?}"); + } + + #[test] + fn a_dialog_in_a_function_or_a_loop_resumes_where_it_was_called() { + let (mut r, asked) = dialog_realm(); + let script = "var seen = []; + function pickOne(n) { + try { var f = File.openDialog('n' + n, function (f) { return f.name !== 'skip'; }); return f === null ? 'none' : f.name; } + finally { seen.push('f' + n); } + } + for (var k = 0; k < 3; k++) seen.push(pickOne(k)); + var many = File.openDialog('m', function (f) { return f.name !== 'b'; }, true); + var thrown; + try { File.openDialog('t', function () { throw new Error('no'); }); } catch (e) { thrown = e.message; } + seen.concat([many.length, many[1].name, thrown]).join()"; + r.start(script).unwrap(); + for answer in ["/a", "/skip", "/c"] { + assert_eq!(until_wait(&mut r), None); + r.answer(Data::String(answer.into())).unwrap(); + } + assert_eq!(until_wait(&mut r), None); + r.answer(Data::Array(["/a", "/b", "/c"].map(|p| Data::String(p.into())).to_vec())).unwrap(); + assert_eq!(until_wait(&mut r), None); + r.collect_garbage(); + r.answer(Data::String("/a".into())).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("f0,a,f1,none,f2,c,2,c,no".into()))); + assert_eq!(asked.borrow().len(), 5, "each dialog asked once"); + } + #[test] fn objects_keep_their_classes_through_collections() { let mut r = realm(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index dea53c557f..3b96953e8d 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -177,11 +177,13 @@ pub(crate) enum NativeKind { /// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given. /// `Data` is a host function given [`crate::Data`], its arguments read as `read` says. `Eval` is a /// host function that gives source to run as global code ([`crate::HostItem::Evaluator`]); `end` -/// is called when that code ends. +/// is called when that code ends. `Pausable` is a built-in that may ask the host for a value the +/// run to wait for ([`crate::interp::Pause`]). #[derive(Clone)] pub(crate) enum Func { Closure { code: Rc, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, + Pausable { f: crate::interp::PausableFn, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b6bf85bfcc..bb1de36694 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -165,6 +165,31 @@ type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; +/// A built-in function that may wait for the host ([`crate::heap::Func::Pausable`]): it is given +/// `this` and the arguments, and gives the host call it makes. +pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult; + +/// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the +/// answer, and gives the result of its call. +pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; + +/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to +/// `resume` with `keep`, at once when the host answers at once. When the host waits +/// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on +/// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it. +pub(crate) struct Pause { + pub(crate) host: Value, + pub(crate) args: Vec, + pub(crate) keep: Vec, + pub(crate) resume: ResumeFn, +} + +/// A [`Pause`] whose host call waits for its answer. +pub(crate) struct Resumption { + resume: ResumeFn, + keep: Vec, +} + pub(crate) struct Interp { pub(crate) heap: Heap, pub(crate) stack: Vec, @@ -225,6 +250,9 @@ pub(crate) struct Interp { pub(crate) can_wait: Rc>, /// A host function's call waits for its result: the value on top of the stack stands in for it. pub(crate) waiting: bool, + /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before + /// the next instruction runs. + pub(crate) resuming: Option, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. @@ -472,6 +500,7 @@ impl Interp { in_slice: false, can_wait: Rc::default(), waiting: false, + resuming: None, host_abort: None, data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, @@ -682,6 +711,7 @@ impl Interp { let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); + roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter())); roots.values.push(&self.last_thrown); roots.values.push(&self.last_error); roots.values.push(&self.passing); @@ -746,6 +776,14 @@ impl Interp { fn step(&mut self) -> JsResult> { self.tick()?; + // A built-in that waited for the host takes the answer on top of the stack before the + // instruction after its call runs; what it throws is thrown at that call. + if let Some(r) = self.resuming.take() { + let answer = self.pop()?; + let v = self.resume(r, answer)?; + self.push(v)?; + return Ok(None); + } let frame = self.frame_mut()?; let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") }; frame.pc += 1; @@ -2159,6 +2197,16 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } + Func::Pausable { f: native, .. } => { + let mark = self.temp_roots.len(); + self.temp_roots.push(this.clone()); + self.temp_roots.extend(args.iter().cloned()); + let held = self.held_bytes; + let r = native(self, this, &args).and_then(|p| self.ask(p)); + self.held_bytes = held; + self.temp_roots.truncate(mark); + return Ok(Prepared::Done(r?)); + } Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. @@ -2384,6 +2432,41 @@ impl Interp { Ok(a) } + /// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host + /// function is called as the script's own code calls it, so it may wait; then the resume + /// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands + /// in for that answer is the call's result for now. + fn ask(&mut self, p: Pause) -> JsResult { + let Pause { host, args, keep, resume } = p; + let mark = self.temp_roots.len(); + self.temp_roots.push(host.clone()); + self.temp_roots.extend(args.iter().cloned()); + self.temp_roots.extend(keep.iter().cloned()); + let was_waiting = self.waiting; + let answer = match self.func_of(&host) { + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + _ => self.call(&host, &Value::Undefined, &args), + }; + self.temp_roots.truncate(mark); + let answer = answer?; + let r = Resumption { resume, keep }; + if self.waiting && !was_waiting { + self.resuming = Some(r); + return Ok(answer); + } + self.resume(r, answer) + } + + /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function. + fn resume(&mut self, r: Resumption, answer: Value) -> JsResult { + let mark = self.temp_roots.len(); + self.temp_roots.push(answer.clone()); + self.temp_roots.extend(r.keep.iter().cloned()); + let v = (r.resume)(self, &r.keep, answer); + self.temp_roots.truncate(mark); + v + } + /// Calls `f` from Rust and returns its result, running the loop again for a function written /// in JavaScript. pub(crate) fn call(&mut self, f: &Value, this: &Value, args: &[Value]) -> JsResult { diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 72a85fb66f..0a1006a23c 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -251,6 +251,7 @@ impl Realm { interp.last_error = Value::Null; interp.host_abort = None; interp.waiting = false; + interp.resuming = None; interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); @@ -286,6 +287,7 @@ impl Realm { interp.temp_roots.clear(); interp.join_stack.clear(); interp.waiting = false; + interp.resuming = None; interp.passing = Value::Undefined; match result { Ok(v) => Ok(interp.to_js_value(&v)), @@ -375,7 +377,9 @@ impl Realm { } /// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next - /// [`Realm::advance`] goes on from there. A result past the heap limit ends the run with that + /// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the + /// call, the built-in takes `d` first and gives its own result, and what it throws is thrown + /// at its call. A result past the heap limit ends the run with that /// limit, and with no call waiting this gives an internal error. pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { let interp = &mut self.interp; From fb12ddb7598d3570d6c95b9c1fc7fd98e477fe4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 15:06:11 -0800 Subject: [PATCH 15/48] Scripts: a renamed file's old path is named in the report's written rename named only the new path in written, so a run that renamed a file an earlier run wrote did not name the path it emptied. It now names both, as remove names the path it deletes. --- crates/engine/src/script/files.rs | 2 ++ crates/engine/src/tests/script_io.rs | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ddc574ee71..ba2f5ec4dc 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1763,6 +1763,8 @@ fn rename(host: &Host, a: &[Data]) -> Result { file.target = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } } + // The old path no longer holds the file, so the report names it as well as the new one. + disk.wrote(&from); disk.wrote(&to); Ok(Data::Object(vec![("fs".into(), Data::String(new))])) } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 39276d737f..75abff6956 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -513,6 +513,29 @@ fn script_files_write_in_the_temporary_and_data_folders() { let _ = std::fs::remove_dir_all(base); } +/// `rename` of a file an earlier run wrote names both its old and its new path in `written`. +#[test] +fn a_renamed_file_names_its_old_and_new_paths_in_written() { + let base = folder("renamed"); + let mut s = with_data(&base); + let first = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/old.txt'); u.open('w'); u.write('x'); vc.log(u.close());"); + assert_eq!(first.unwrap()["log"], json!([true])); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/old.txt'); var before = u.fsName;\n\ + vc.log(u.rename('new.txt')); vc.log(before); vc.log(u.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!(true)); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + for at in [1, 2] { + let path = r["log"][at].as_str().unwrap(); + assert!(written.contains(&path), "{path} in {written:?}"); + } + 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`. From 9811cafc25bc27f07de793413ea0872556bb506d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 15:39:59 -0800 Subject: [PATCH 16/48] Scripts: copy reads its source under the rules for reading copy read the source's real path as it was when looked up, so a file replaced by a link before the read could copy a file from outside the script's places, and a link given as the source that was pointed elsewhere copied the old target. copy now reads the path as given through the same checks open uses and refuses the copy with Script file access denied when the path no longer leads to the file it was looked up as. --- crates/engine/src/script/files.rs | 29 ++++++++++--- crates/engine/src/tests/script_io.rs | 63 ++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ba2f5ec4dc..6340912cb8 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1663,12 +1663,19 @@ fn copy(host: &Host, a: &[Data]) -> Result { if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { return Ok(error(m)); } - // The bytes are read once, no more than the limit, and those bytes are what is charged and - // written: a source that grows after it is read does not copy more. - let copied = match read_head(&source, MAX_FILE_BYTES) { - Ok(bytes) if bytes.len() > MAX_FILE_BYTES => return Ok(error(TOO_LARGE)), - Ok(bytes) => bytes, - Err(_) => return Ok(error(READ_FAILED)), + #[cfg(test)] + if let Some(hook) = BEFORE_COPY_READ.with(|h| h.borrow_mut().take()) { + hook(Path::new(&from), &source); + } + // The bytes are read once, no more than the limit, under the rules for reading, and those bytes + // are what is charged and written: a source that grows after it is read does not copy more, + // and a path that leads somewhere else than when it was looked up is refused. + let copied = match disk.scope.read(Path::new(&from), MAX_FILE_BYTES) { + Ok((at, bytes)) if at == source => bytes, + Ok(_) | Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)), + Err(ScriptRead::TooLarge) => return Ok(error(TOO_LARGE)), + Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)), + Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)), }; // 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. @@ -2195,6 +2202,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr realm.define_file_classes(items) } +/// Tests: what the next `copy` does with its source's path, as given and as its real path, after +/// looking it up and before reading it. +#[cfg(test)] +pub(crate) type CopyHook = Box; + +#[cfg(test)] +thread_local! { + pub(crate) static BEFORE_COPY_READ: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 75abff6956..fdd75c8c57 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -513,6 +513,69 @@ fn script_files_write_in_the_temporary_and_data_folders() { let _ = std::fs::remove_dir_all(base); } +/// `copy` reads its source under the rules for reading: a source that a link to a file outside the +/// script's places replaced after it was looked up is refused, and nothing is copied. +#[cfg(unix)] +#[test] +fn a_copy_whose_source_becomes_a_link_outside_copies_nothing() { + let base = folder("copy-link"); + let mut s = with_data(&base); + let secret = base.join("secret.txt"); + write(&secret, b"secret"); + crate::script::files::BEFORE_COPY_READ.with(|h| { + *h.borrow_mut() = Some(Box::new(move |_: &Path, source: &Path| { + std::fs::remove_file(source).unwrap(); + std::os::unix::fs::symlink(&secret, source).unwrap(); + })); + }); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, a = new File(d + '/a.txt'); a.open('w'); a.write('mine'); a.close();\n\ + vc.log([a.copy(d + '/b.txt'), a.error, new File(d + '/b.txt').exists]);", + ) + .unwrap(); + crate::script::files::BEFORE_COPY_READ.with(|h| h.borrow_mut().take()); + assert_eq!(r["log"], json!([[false, "Script file access denied", false]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` of a link whose target changes after it was looked up is refused, also when both files +/// are in the script's places. +#[cfg(unix)] +#[test] +fn a_copy_of_a_link_that_leads_elsewhere_after_it_was_looked_up_copies_nothing() { + let base = folder("copy-relink"); + let mut s = with_data(&base); + let first = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName;\n\ + ['a', 'c'].forEach(function (n) { var f = new File(d + '/' + n + '.txt'); f.open('w'); f.write(n); f.close(); });\n\ + vc.log(d);", + ) + .unwrap(); + let data = PathBuf::from(first["log"][0].as_str().unwrap()); + std::os::unix::fs::symlink(data.join("a.txt"), data.join("link.txt")).unwrap(); + let other = data.join("c.txt"); + crate::script::files::BEFORE_COPY_READ.with(|h| { + *h.borrow_mut() = Some(Box::new(move |given: &Path, _: &Path| { + std::fs::remove_file(given).unwrap(); + std::os::unix::fs::symlink(&other, given).unwrap(); + })); + }); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, l = new File(d + '/link.txt');\n\ + vc.log([l.copy(d + '/b.txt'), l.error, new File(d + '/b.txt').exists]);", + ) + .unwrap(); + crate::script::files::BEFORE_COPY_READ.with(|h| h.borrow_mut().take()); + assert_eq!(r["log"], json!([[false, "Script file access denied", false]])); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { From e9baf43e1a893bf2c658edb1f487e1eba8e77494 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 16:04:00 -0800 Subject: [PATCH 17/48] Tests: a script in the settings Scripts folder reads the files beside it The settings folder is closed to scripts except for a script's own folder inside it. The test runs a script from settings/Scripts, reads a file beside it and is refused a file elsewhere in the settings folder. --- crates/engine/src/tests/script_io.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index fdd75c8c57..2f2d7fe6f5 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1850,6 +1850,21 @@ fn script_file_grants_never_reach_the_settings_folder() { let _ = std::fs::remove_dir_all(base); } +/// A script in the Scripts folder inside the settings folder reads the files beside it, while the +/// rest of the settings folder stays closed to it. +#[test] +fn a_script_in_the_settings_scripts_folder_reads_its_own_folder() { + let base = folder("installed"); + let mut s = with_data(&base); + write(&base.join("settings/Scripts/x.txt"), b"beside"); + write(&base.join("settings/other.txt"), b"settings"); + let main = base.join("settings/Scripts/main.jsx"); + write(&main, b"var f = new File('x.txt'), g = new File(f.parent.parent.fsName + '/other.txt'); vc.log([f.open('r'), f.read(), g.open('r')]);"); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!([[true, "beside", false]])); + 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() { From b73c9834c816cc90908e73ca77fc4c5270c3369e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 19:08:44 -0800 Subject: [PATCH 18/48] Scripts: grants file changes take turns and use a file of their own Two processes that changed Script Grants.json at once both wrote Script Grants.json.part, so one could overwrite the other's file or fail on it. Each write now goes to a new file named for its process and write, passing over a name an earlier write left behind, and only that file is removed when the write fails. Changes hold a lock on Script Grants.lock beside the grants file and are not made when it cannot be taken; reads take it when they can. --- crates/engine/src/script/files.rs | 57 +++++++++++++++++++++++++--- crates/engine/src/tests/script_io.rs | 37 ++++++++++++++++++ 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 6340912cb8..ba1bc60827 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -431,6 +431,7 @@ impl Disk { } let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return }; let (script, code) = (shown(script), self.ran.iter().cloned().collect::>()); + let Ok(_lock) = lock_store(&store) else { return }; let Ok(mut grants) = try_read_store(&store) else { return }; for g in &mut grants { let ours = g["script"] == *script @@ -566,6 +567,7 @@ impl Disk { 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) }; // A grants file that is there but cannot be read is left as it is. + let _lock = lock_store(&store).map_err(|_| NOT_SAVED)?; let mut grants = try_read_store(&store).map_err(|_| NOT_SAVED)?; let script = shown(script); let code: Vec<&String> = self.ran.iter().collect(); @@ -882,8 +884,10 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { } /// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant -/// that is not well formed is left out. +/// that is not well formed is left out. It is read under [`lock_store`]'s lock when that can be +/// taken, so it is read between two changes. fn read_store(store: &Path) -> Vec { + let _lock = lock_store(store).ok(); load_store(store, false).unwrap_or_default() } @@ -928,8 +932,13 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result) -> 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 { @@ -938,14 +947,49 @@ fn write_store(store: &Path, grants: Vec) -> std::io::Result< if let Some(dir) = store.parent() { std::fs::create_dir_all(dir)?; } - let part = store.with_extension("json.part"); - std::fs::write(&part, text)?; + // A name an earlier write left behind is passed over, up to 64 times, and only the file made here + // is removed. + let mut tries = 0; + let (part, mut file) = loop { + let n = NEXT_PART.fetch_add(1, Ordering::Relaxed); + let part = store.with_extension(format!("json.{}-{n}.part", std::process::id())); + match std::fs::File::options().write(true).create_new(true).open(&part) { + Ok(file) => break (part, file), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && tries < 63 => tries += 1, + Err(e) => return Err(e), + } + }; + let written = std::io::Write::write_all(&mut file, &text); + drop(file); // `rename` replaces a grants file that is there, on Windows too (`MOVEFILE_REPLACE_EXISTING`). - std::fs::rename(&part, store).inspect_err(|_| { + written.and_then(|()| std::fs::rename(&part, store)).inspect_err(|_| { let _ = std::fs::remove_file(&part); }) } +/// The lock file beside the grants file at `store` (`Script Grants.lock`), locked until it is +/// dropped and waiting while another process holds it, so that processes that read and change the +/// grants file take turns. A change is not made when the lock cannot be taken. +#[cfg(not(target_arch = "wasm32"))] +fn lock_store(store: &Path) -> std::io::Result { + let lock = store.with_extension("lock"); + let opened = store + .parent() + .map_or(Ok(()), std::fs::create_dir_all) + .and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(&lock)); + let file = opened.and_then(|f| f.lock().map(|()| f)); + if let Err(e) = &file { + log::warn!("can't lock {}: {e}", lock.display()); + } + file +} + +/// The browser has no folders to keep anything in. +#[cfg(target_arch = "wasm32")] +fn lock_store(_: &Path) -> std::io::Result { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) +} + /// 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 { @@ -957,6 +1001,7 @@ pub(crate) fn stored_grants(data_dir: &Path) -> Vec { /// → 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 _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); let kept: Vec = diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 2f2d7fe6f5..9b9cee9439 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -576,6 +576,43 @@ fn a_copy_of_a_link_that_leads_elsewhere_after_it_was_looked_up_copies_nothing() let _ = std::fs::remove_dir_all(base); } +/// The grants file is written through a temporary file of its own, so a temporary file another +/// process left beside it, or one an earlier write left under the name this write takes first, +/// does not stop a change and is left where it is. +#[test] +fn a_grants_change_does_not_use_another_writers_temporary_file() { + let base = folder("grants-part"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + std::fs::create_dir_all(base.join("settings/Script Grants.json.part/held")).unwrap(); + let next = crate::script::files::NEXT_PART.load(std::sync::atomic::Ordering::Relaxed); + let left_behind: Vec = + (next..next + 8).map(|n| base.join(format!("settings/Script Grants.json.{}-{n}.part", std::process::id()))).collect(); + for p in &left_behind { + write(p, b"earlier"); + } + assert_eq!(crate::script::files::revoke_grants(&data, None, None).unwrap(), 1); + let left: Value = serde_json::from_slice(&std::fs::read(base.join("settings/Script Grants.json")).unwrap()).unwrap(); + assert_eq!(left["grants"], json!([])); + assert!(left_behind.iter().all(|p| std::fs::read(p).is_ok_and(|b| b == b"earlier")), "files this write did not make stay"); + let _ = std::fs::remove_dir_all(base); +} + +/// A change to the grants file is not made when its lock cannot be taken. +#[test] +fn a_grants_change_without_its_lock_changes_nothing() { + let base = folder("grants-lock"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + std::fs::create_dir_all(base.join("settings/Script Grants.lock/held")).unwrap(); + assert!(crate::script::files::revoke_grants(&data, None, None).is_err()); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), text); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { From 64662b435b545bd6d6f47553f92032bba38a9055 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:32:04 -0800 Subject: [PATCH 19/48] Scripts: a file opened under a withdrawn grant is not read When a run evaluated code that withdrew a kept grant, a File opened under that grant still gave the bytes it held to read, readln and readch, and seek to the end showed its length. Those calls now give Script file access denied and set error, and eof is true. docs/mcp.md says so. --- crates/engine/src/script/files.rs | 37 +++++++++++++++++++++++----- crates/engine/src/tests/script_io.rs | 24 ++++++++++++++++++ crates/js/src/file_classes.rs | 7 +++++- docs/mcp.md | 3 ++- 4 files changed, 63 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ba1bc60827..be813e3a74 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -420,6 +420,12 @@ impl Disk { } } } + // Objects that hold a file the run may no longer read give none of it. + for o in self.open.values_mut() { + if o.read_from.as_deref().is_some_and(|p| !self.scope.allows(p)) { + o.unreadable = true; + } + } } /// Writes the evaluated code this run ran into the grants it kept with Always, so a later run @@ -1391,6 +1397,9 @@ struct Open { /// 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, + /// The run may no longer read the file the object holds: `read`, `readln`, `readch` and `seek` + /// give [`ACCESS_DENIED`], and `eof` is true. + unreadable: bool, } impl Open { @@ -1410,7 +1419,17 @@ impl Open { } else { (Encoding::Cp1252, 0) }; - Some(Self { bytes, pos, encoding, name: encoding.name().to_string(), target: None, read_from: None, dirty: false, withdrawn: false }) + Some(Self { + bytes, + pos, + encoding, + name: encoding.name().to_string(), + target: None, + read_from: None, + dirty: false, + withdrawn: false, + unreadable: false, + }) } /// Writes `text` at the position, over what is there and past the end, when it takes at most @@ -1593,6 +1612,12 @@ fn with_open(host: &Host, a: &[Data], f: impl FnOnce(&mut Open) -> Data) -> Data } } +/// [`with_open`] for a call that reads what the file holds: `{error}` [`ACCESS_DENIED`] when the +/// run may no longer read it. +fn with_readable(host: &Host, a: &[Data], f: impl FnOnce(&mut Open) -> Data) -> Data { + with_open(host, a, |file| if file.unreadable { error(ACCESS_DENIED) } else { f(file) }) +} + /// The first two arguments as path text, refused with a `RangeError` when either is too long. fn two_paths(a: &[Data]) -> Result<(String, String), HostError> { let (path, base) = (arg_text(a, 0), arg_text(a, 1)); @@ -2031,20 +2056,20 @@ pub(crate) fn dialog_filters(filter: &str) -> Vec<(String, Vec)> { fn read(host: &Host, a: &[Data]) -> Result { let max = arg_number(a, 1).filter(|n| *n >= 0.0).map(|n| n as usize); - Ok(with_open(host, a, |f| text_result(f.read(max)))) + Ok(with_readable(host, a, |f| text_result(f.read(max)))) } fn readln(host: &Host, a: &[Data]) -> Result { - Ok(with_open(host, a, |f| text_result(f.read_line()))) + Ok(with_readable(host, a, |f| text_result(f.read_line()))) } fn readch(host: &Host, a: &[Data]) -> Result { - Ok(with_open(host, a, |f| text_result(f.read_char()))) + Ok(with_readable(host, a, |f| text_result(f.read_char()))) } fn seek(host: &Host, a: &[Data]) -> Result { let (Some(pos), Some(mode)) = (arg_number(a, 1), arg_number(a, 2)) else { return Err(HostError::Type(BAD_SEEK.into())) }; - Ok(with_open(host, a, |f| { + Ok(with_readable(host, a, |f| { let base = match mode as u8 { 1 => f.pos as f64, 2 => f.bytes.len() as f64, @@ -2066,7 +2091,7 @@ fn tell(host: &Host, a: &[Data]) -> Result { } fn eof(host: &Host, a: &[Data]) -> Result { - Ok(Data::Bool(host.disk.borrow().open.get(&handle(a)).is_none_or(|f| f.pos >= f.bytes.len()))) + Ok(Data::Bool(host.disk.borrow().open.get(&handle(a)).is_none_or(|f| f.unreadable || f.pos >= f.bytes.len()))) } fn encoding(host: &Host, a: &[Data]) -> Result { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 9b9cee9439..ae782692f3 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1854,6 +1854,30 @@ fn script_files_open_under_a_withdrawn_grant_keep_their_unwritten_changes() { let _ = std::fs::remove_dir_all(base); } +/// A file opened for reading under a kept grant that new code withdraws gives no more of what it +/// holds. +#[test] +fn script_files_open_under_a_withdrawn_grant_are_not_read() { + let base = folder("grantwithdrawnread"); + let dir = base.join("picked"); + write(&dir.join("in.txt"), b"secret"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('r')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ var a = f.readch(); eval('1'); var r = f.read(), e = f.error; f.error = ''; vc.log([a, r, e, f.eof, f.seek(0, 2), f.error, f.tell()]); }}", + dir.join("in.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![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().unwrap(); + assert_eq!(r["log"], json!([["s", "", DENIED, true, false, DENIED, 1]])); + 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. diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index f1bba51291..c962bf9679 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -887,7 +887,12 @@ fn seek(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult return Err(i.throw(ErrorType::Range, "File.seek: the mode must be 0, 1 or 2")); } let Some(h) = opened(i, o)? else { return Ok(Value::Bool(false)) }; - host(i, "seek", &[h, Value::Number(pos.floor()), Value::Number(mode)]) + let r = host(i, "seek", &[h, Value::Number(pos.floor()), Value::Number(mode)])?; + // A seek the host refuses sets `error` and gives `false`. + if !outcome(i, o, &r)? { + return Ok(Value::Bool(false)); + } + Ok(r) } fn tell(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { diff --git a/docs/mcp.md b/docs/mcp.md index 1c49dde6c9..4562889e7e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2458,7 +2458,8 @@ VectorCraft writes files by these rules of its own: 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 + `#targetengine` engine holds code the grant does not list, such as another script's. A file opened under a + grant the run loses gives `Script file access denied` when it is read or `seek` is called after that. 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 From 1bf936defa9465d3f60d82ad2d2b8edbe17f00b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:05:20 -0800 Subject: [PATCH 20/48] Tests: the Enter-denies test removes its temporary folder --- crates/ui-egui/src/tests/script_run.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 202ac35c6f..882799385e 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -540,7 +540,8 @@ fn enter_in_a_scripts_file_dialog_denies() { 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 dir = folder("enterdeny"); + app.script_picked = vec![dir.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 }; @@ -551,6 +552,7 @@ fn enter_in_a_scripts_file_dialog_denies() { 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])); + let _ = std::fs::remove_dir_all(&dir); } /// Enter on the file dialog's focused Choose… button goes to that button, which opens the folder From 6864086cda15fa4fad3f3c920550bf7b39cb3f80 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 02:50:41 -0800 Subject: [PATCH 21/48] i18n: keep bracketed field names untranslated in fr rows --- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6fc56e60cb..83effda4cc 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7593,7 +7593,7 @@ breakText Glyphs Glyphes @msg `alignOn` must be a string `alignOn` doit être une chaîne @msg `align` is start, center or end `align` vaut start, center ou end @msg `align` must be a string `align` doit être une chaîne -@msg `anchors` must be an array of [subpath, anchor] pairs `anchors` doit être une liste de paires [sous-tracé, point d’ancrage] +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors` doit être une liste de paires [subpath, anchor] @msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {k} @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pour cette boîte de dialogue {kind} doit valoir l’une de ces valeurs : {_1} @@ -7657,7 +7657,7 @@ breakText Glyphs Glyphes @msg `fidelity` must be from {lo} to {hi} pt `fidelity` doit être compris entre {lo} et {hi} pt @msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files` doit contenir de 1 à 1000 chemins de fichiers de police trouvés par la dernière recherche text.findFontFiles @msg `focal` and `radius` cannot be used together `focal` et `radius` ne peuvent pas être utilisés ensemble -@msg `focal` must be an array of [subpath, anchor] pairs `focal` doit être une liste de paires [sous-tracé, point d’ancrage] +@msg `focal` must be an array of [subpath, anchor] pairs `focal` doit être une liste de paires [subpath, anchor] @msg `focal` names [{si}, {ai}], which is not an anchor of the path `focal` désigne [{si}, {ai}], qui n’est pas un point d’ancrage du tracé @msg `folder` must be an absolute folder path `folder` doit être le chemin absolu d’un dossier @msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes` doit être un objet de balises d’axe et de valeurs, comme {"wght"} From cefaeefca942b8978110dc79193ae10730c8991d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:38:25 -0800 Subject: [PATCH 22/48] Scripts: grants kept earlier in a run keep the code evaluated before a later one Keeping a second grant with Always marked all the code the run had evaluated as recorded, so the run's end skipped the grants kept before it, and they kept the code list from when they were kept. The next run that evaluated that code withdrew them. Keeping a grant now writes the current code list into the grants the run kept before it as well. --- crates/engine/src/script/files.rs | 12 +++++++++- crates/engine/src/tests/script_io.rs | 35 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index be813e3a74..216e27f677 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -569,7 +569,7 @@ impl Disk { /// 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. + /// takes its place. The grants the run kept before are given the same code. 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) }; // A grants file that is there but cannot be read is left as it is. @@ -577,6 +577,16 @@ impl Disk { let mut grants = try_read_store(&store).map_err(|_| NOT_SAVED)?; let script = shown(script); let code: Vec<&String> = self.ran.iter().collect(); + // The grants this run kept before take the code evaluated since, as the run's end would + // have given them. + for g in &mut grants { + if g["script"] == *script + && g["sha256"] == *hash + && self.kept.iter().any(|(p, w, f)| g["path"] == *shown(p) && g["write"] == *w && g["folder"] == *f) + { + g["code"] = serde_json::json!(code); + } + } for p in paths { let path = shown(p); grants diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index ae782692f3..4463c19e97 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1766,6 +1766,41 @@ fn script_file_grants_keep_the_code_evaluated_after_the_dialog() { let _ = std::fs::remove_dir_all(base); } +/// A grant kept with Always before a second one is kept in the same run also keeps the code the +/// run evaluated between the two, so the next run that evaluates it keeps both grants. +#[test] +fn script_file_grants_kept_earlier_in_a_run_keep_the_code_evaluated_before_a_later_grant() { + let base = folder("grantbetween"); + let first = base.join("picked/a.txt"); + let second = base.join("picked/b.txt"); + write(&first, b"a"); + write(&second, b"b"); + let text = format!( + "var a = new File({:?}); var ka = a.open('r');\n\ + if (!ka) File.openDialog('a');\n\ + var between = eval('new File(a.fsName).open(\"r\")');\n\ + var b = new File({:?}); var kb = b.open('r');\n\ + if (!kb) File.openDialog('b');\n\ + vc.log([ka, between, kb, new File(a.fsName).open('r')]);", + first.to_string_lossy(), + second.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![first.to_string_lossy().into_owned()], always: true })); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![second.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[false, true, false, true]])); + start_framed(&mut s, &base, &text); + assert_eq!( + pump_to_picker(&mut s).unwrap().unwrap()["log"], + json!([[true, true, true, true]]), + "the first grant keeps the code evaluated before the second" + ); + 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() { From d435ae1a27abf9b9efdd01ab771663d9ef22e3a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:32:26 -0800 Subject: [PATCH 23/48] Scripts: an open file that is renamed is read under its new path's rules `rename` moved the write path of open File objects but left the path they were read from at the old name. When new code then withdrew the kept grant for the folder, a grant the run still held for the old path let the object go on giving the file's bytes. The read path now moves with the write path. --- crates/engine/src/script/files.rs | 13 +++++++++---- crates/engine/src/tests/script_io.rs | 29 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 216e27f677..19c1a37409 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1844,11 +1844,16 @@ fn rename(host: &Host, a: &[Data]) -> Result { 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) }); + // Open objects of the file, or of files in the folder, write to the new path, and the rules for + // reading apply to them there. + let moved = |p: &mut Option| { + if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + *p = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } + }; + for file in disk.open.values_mut() { + moved(&mut file.target); + moved(&mut file.read_from); } // The old path no longer holds the file, so the report names it as well as the new one. disk.wrote(&from); diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 4463c19e97..1943a11bab 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1913,6 +1913,35 @@ fn script_files_open_under_a_withdrawn_grant_are_not_read() { let _ = std::fs::remove_dir_all(base); } +/// A file opened for reading and then renamed is read under the rules for its new path: when new code +/// withdraws the kept grant for its folder, a grant the run still holds for its old path does not let +/// the object give more of it. +#[test] +fn script_files_renamed_while_open_are_read_under_their_new_path() { + let base = folder("grantwithdrawnrenamed"); + let dir = base.join("picked"); + let file = dir.join("in.txt"); + write(&file, b"secret"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('r')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ var a = f.readch(); File.openDialog('p'); var n = new File(f.fsName).rename('r.txt'); eval('1');\n\ + var r = f.read(), e = f.error; vc.log([a, n, r, e]); }}", + file.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); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![file.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["s", true, "", DENIED]])); + 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. From 1ae70095ccc33735bf52c198abe68d3340c56f47 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:47:48 -0800 Subject: [PATCH 24/48] Scripts: the grants-file lock waits a bounded time Taking the lock on Script Grants.lock blocked until the holder let go, so another process that stalled while holding it stopped listing, loading, keeping and revoking grants for good. The lock is now tried 20 times, 50 ms apart, and then fails with TimedOut: a change is not made and a read gives no grants rather than reading without the lock. --- crates/engine/src/script/files.rs | 50 ++++++++++++++++++++++++---- crates/engine/src/tests/script_io.rs | 36 ++++++++++++++++++++ 2 files changed, 80 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 19c1a37409..0e863fa03d 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -900,10 +900,10 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { } /// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant -/// that is not well formed is left out. It is read under [`lock_store`]'s lock when that can be -/// taken, so it is read between two changes. +/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read +/// between two changes, and none are read when the lock cannot be taken. fn read_store(store: &Path) -> Vec { - let _lock = lock_store(store).ok(); + let Ok(_lock) = lock_store(store) else { return Vec::new() }; load_store(store, false).unwrap_or_default() } @@ -983,9 +983,20 @@ fn write_store(store: &Path, grants: Vec) -> std::io::Result< }) } +/// How many times [`lock_store`] tries to take the grants file's lock, [`LOCK_PAUSE`] apart, before +/// it gives up. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const LOCK_TRIES: u32 = 20; + +/// The wait between two tries of [`lock_store`]. +#[cfg(not(target_arch = "wasm32"))] +const LOCK_PAUSE: std::time::Duration = std::time::Duration::from_millis(50); + /// The lock file beside the grants file at `store` (`Script Grants.lock`), locked until it is -/// dropped and waiting while another process holds it, so that processes that read and change the -/// grants file take turns. A change is not made when the lock cannot be taken. +/// dropped, so that processes that read and change the grants file take turns. While another +/// process or handle holds it, the lock is tried [`LOCK_TRIES`] times, [`LOCK_PAUSE`] apart, and +/// then the result is `Err` with [`std::io::ErrorKind::TimedOut`]. A change is not made when the +/// lock cannot be taken. #[cfg(not(target_arch = "wasm32"))] fn lock_store(store: &Path) -> std::io::Result { let lock = store.with_extension("lock"); @@ -993,13 +1004,40 @@ fn lock_store(store: &Path) -> std::io::Result { .parent() .map_or(Ok(()), std::fs::create_dir_all) .and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(&lock)); - let file = opened.and_then(|f| f.lock().map(|()| f)); + let file = opened.and_then(take_lock); if let Err(e) = &file { log::warn!("can't lock {}: {e}", lock.display()); } file } +/// `file`, locked within [`lock_store`]'s tries. +#[cfg(not(target_arch = "wasm32"))] +fn take_lock(file: std::fs::File) -> std::io::Result { + let mut tries = 1; + loop { + match file.try_lock() { + Ok(()) => return Ok(file), + Err(std::fs::TryLockError::Error(e)) => return Err(e), + Err(std::fs::TryLockError::WouldBlock) if tries >= LOCK_TRIES => { + return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "another process holds the lock")); + } + Err(std::fs::TryLockError::WouldBlock) => tries += 1, + } + #[cfg(test)] + if WHILE_GRANTS_LOCKED.with_borrow_mut(|w| w.as_mut().map(|waiting| waiting()).is_some()) { + continue; + } + std::thread::sleep(LOCK_PAUSE); + } +} + +#[cfg(test)] +thread_local! { + /// Tests: runs on this thread in place of each wait of [`lock_store`] for a lock that is held. + pub(crate) static WHILE_GRANTS_LOCKED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] fn lock_store(_: &Path) -> std::io::Result { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 1943a11bab..7b5db047ef 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -613,6 +613,42 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// Reading and changing the grants file wait for a lock another handle holds only for a bounded +/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock +/// released while it waits is taken. +#[test] +fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { + use crate::script::files::{LOCK_TRIES, WHILE_GRANTS_LOCKED, revoke_grants, stored_grants}; + let base = folder("grants-lock-held"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + let held = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(base.join("settings/Script Grants.lock")).unwrap(); + held.lock().unwrap(); + let waits = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = waits.clone(); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); + assert_eq!(stored_grants(&data), Vec::::new(), "grants are not read without the lock"); + assert_eq!(waits.get(), LOCK_TRIES - 1); + waits.set(0); + let refused = revoke_grants(&data, None, None); + assert_eq!(refused.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut)); + assert_eq!(waits.get(), LOCK_TRIES - 1, "it waits between tries and gives up after the last"); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), text); + let mut released = Some(held); + let counted = waits.clone(); + waits.set(0); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || { + counted.set(counted.get() + 1); + drop(released.take()); + }))); + assert_eq!(revoke_grants(&data, None, None).unwrap(), 1, "a lock released while it waits is taken"); + assert_eq!(waits.get(), 1); + WHILE_GRANTS_LOCKED.set(None); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { From 82620a1b27aaed84b3f01fcb9c341274eb995034 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:58:51 -0800 Subject: [PATCH 25/48] Scripts: copy and length reach files open for reading A file opened with open('r') kept its old bytes after copy wrote over it or length changed it, while an object open for writing took the new bytes. Both now update every object that holds the file. An object that holds a renamed file is found at the new path, and an object whose file was removed is not taken for a file made later at its path. --- crates/engine/src/script/files.rs | 34 +++++++++++++++++++--------- crates/engine/src/tests/script_io.rs | 29 ++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 0e863fa03d..559b660d08 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1448,6 +1448,9 @@ struct Open { /// The run may no longer read the file the object holds: `read`, `readln`, `readch` and `seek` /// give [`ACCESS_DENIED`], and `eof` is true. unreadable: bool, + /// The file the object holds was removed, so a file made later at its path is not the one it + /// holds. + removed: bool, } impl Open { @@ -1477,9 +1480,19 @@ impl Open { dirty: false, withdrawn: false, unreadable: false, + removed: false, }) } + /// Does the object hold the bytes of the file at the real path `real`: the file it writes to, or, + /// when it writes to none, the file it was opened on while that file was not removed? + fn holds(&self, real: &Path) -> bool { + match self.target.as_deref() { + Some(t) => t == real, + None => !self.removed && self.read_from.as_deref() == Some(real), + } + } + /// 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 { @@ -1797,7 +1810,7 @@ fn copy(host: &Host, a: &[Data]) -> Result { }; // 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(); + let holders = disk.open.values().filter(|o| o.holds(&target)).count(); disk.charge_write(copied.len().saturating_mul(holders.saturating_add(usize::from(!itself))))?; // The copy takes the source's permissions, as `std::fs::copy` gives them. let permissions = std::fs::metadata(&source).map(|m| m.permissions()); @@ -1806,9 +1819,10 @@ fn copy(host: &Host, a: &[Data]) -> Result { 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. + // Open objects of the target hold the copy, so those opened for reading read it and closing the + // others does not write their older bytes. if r.is_ok() { - for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { file.bytes.clone_from(&copied); file.pos = file.pos.min(copied.len()); file.dirty = false; @@ -1843,10 +1857,12 @@ fn remove(host: &Host, a: &[Data]) -> Result { }; 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())) { + // their close nor the run's end makes the file again, and no object holds a file made later + // at its path. + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { file.dirty = false; file.target = None; + file.removed = true; } disk.wrote(&target); } @@ -1952,11 +1968,7 @@ fn set_length(host: &Host, a: &[Data]) -> Result { 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()))); + let held = disk.open.values().filter(|o| o.holds(&target)).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(); @@ -1967,7 +1979,7 @@ fn set_length(host: &Host, a: &[Data]) -> Result { }; 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())) { + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { file.bytes.resize(len, 0); file.pos = file.pos.min(len); } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 7b5db047ef..62f031528b 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -889,6 +889,35 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// An object that has a file open for reading holds what `copy` writes over the file and the length +/// `length` sets, as an object open for writing does, also after the file is renamed, and not after +/// it is removed. +#[test] +fn script_file_open_for_reading_holds_a_copy_and_a_new_length() { + let base = folder("copyreader"); + 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'); t.close(); t.open('r');\n\ + var out = [s.copy(t.fsName), t.read()]; t.close();\n\ + var u = new File(d + '/u.txt'); u.open('w'); u.write('abcdef'); u.close(); u.open('r');\n\ + new File(u.fsName).length = 2; out.push(u.read()); u.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, "copied", "ab"]])); + // A renamed file is held at its new path; a removed one is not held by a file made at its path. + 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 v = new File(d + '/v.txt'); v.open('w'); v.write('old'); v.close(); v.open('r');\n\ + var w = new File(d + '/v.txt'); var out = [w.rename('w.txt'), s.copy(d + '/v.txt'), v.read()];\n\ + v.seek(0); out.push(s.copy(w.fsName), v.read()); v.close();\n\ + var x = new File(d + '/x.txt'); x.open('w'); x.write('kept'); x.close(); x.open('r');\n\ + out.push(new File(x.fsName).remove(), s.copy(d + '/x.txt'), x.read()); x.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, true, "old", true, "copied", true, true, "kept"]])); + let _ = std::fs::remove_dir_all(base); +} + /// A file whose `close` could not write it stays open, so a later `close` writes it. #[test] fn script_file_close_that_fails_can_be_tried_again() { From 9971b39c6dc37fa2e7122502420ee15cbe6b6ede Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:50:47 -0800 Subject: [PATCH 26/48] i18n: Danish rows for script file messages Adds Danish rows for the script File and Folder messages, now that Danish is a complete-message language, and removes the two Danish rows for messages the scripts no longer give. --- crates/ui-egui/src/i18n/da.tsv | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 80fb5d9ab8..b3c1a1a86e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -75,14 +75,33 @@ @msg Script file could not be read Scriptfilen kunne ikke læses @msg Script folder has more than 2,048 entries Scriptmappen har mere end 2.048 elementer @msg Script file open mode must be r, w, e or a Scriptfilens åbningstilstand skal være r, w, e eller a -@msg Script file writing is not available Skrivning af scriptfiler er ikke tilgængelig -@msg Script file dialogs are not available Scriptfildialoger er ikke tilgængelige @msg Script files cannot be opened in another application Scriptfiler kan ikke åbnes i et andet program @msg Script file access is unavailable on the web Scriptets filadgang er ikke tilgængelig på nettet @msg Script has 256 files open Scriptet har 256 filer åbne @msg Script file path exceeds 32,767 characters Scriptfilens sti er længere end 32.767 tegn @msg Script folder mask takes too many steps to match Scriptmappens maske kræver for mange trin at matche @msg the script opened more file data than one run may open (32 MiB) scriptet åbnede flere fildata, end én kørsel må åbne (32 MiB) +@msg Script file access denied: {path} Scriptets filadgang blev nægtet: {path} +@msg Script file access to the app's own folders is not allowed Scripts må ikke få adgang til programmets egne mapper +@msg Script file cannot encode the text Scriptfilen kan ikke kode teksten +@msg Script file could not be written Scriptfilen kunne ikke skrives +@msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person +@msg Script file is not open for writing Scriptfilen er ikke åben for skrivning +@msg Script file name is already in use Scriptfilens navn er allerede i brug +@msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe +@msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil +@msg Script file permission could not be saved Scriptets filtilladelse kunne ikke gemmes +@msg Script folder is not empty Scriptmappen er ikke tom +@msg Script files cannot make aliases Scriptfiler kan ikke oprette aliasser +@msg Script file hidden setting cannot be changed Scriptfilens indstilling for skjult kan ikke ændres +@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 ikke åbnes i et callback fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode +@msg the script wrote more file data than one run may write (32 MiB) scriptet skrev flere fildata, end én kørsel må skrive (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` for et scripts fildialog skal være en af: once, always, deny, stop +@msg choose a file or folder first, or deny vælg først en fil eller mappe, eller afvis +@msg the script file permissions could not be saved: {e} scriptets filtilladelser kunne ikke gemmes: {e} +@msg this script's file access can be allowed only once dette scripts filadgang kan kun tillades én gang +@msg Only the person at the keyboard can allow a script's file access Kun personen ved tastaturet kan tillade et scripts filadgang +@msg A script is given at most 2,048 files: the files picked after them were left out Et script får højst 2.048 filer: de filer, der blev valgt derefter, blev udeladt @msg File.seek: takes a position and a mode File.seek: tager en position og en tilstand @msg vc.run: give a command id, as a string vc.run: angiv et kommando-id som en streng @msg vc.run: takes a command id and an object of parameters vc.run: tager et kommando-id og et objekt med parametre From b173bd7b4048679a3fed38a0ecf103754342f29f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:45:16 -0800 Subject: [PATCH 27/48] Scripts: a folder renamed under another case of its name moves its open files `rename` matched open File objects by the path as given, while the objects hold the names the file system keeps. Where case does not matter, a folder named in another case was renamed but its open files kept the old path, so their changes could not be written and they stayed under the old path's rules for reading. The objects are now matched by the kept name, and a rename whose kept name cannot be learned is refused. --- crates/engine/src/script/files.rs | 14 +++++++++++++- crates/engine/src/tests/script_io.rs | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 559b660d08..7f4052dfb8 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1895,13 +1895,25 @@ fn rename(host: &Host, a: &[Data]) -> Result { { return Ok(error(NAME_TAKEN)); } + // Open objects hold real paths with the names the file system keeps, and `from` keeps the last + // name as given, which where case does not matter can differ in case: they are matched by the + // kept name. A link is renamed itself, and no object holds a path through it. When the kept + // name cannot be learned, nothing is renamed, so no object goes on under the old path's rules. + let kept = if was.file_type().is_symlink() { + from.clone() + } else { + match std::fs::canonicalize(&from) { + Ok(kept) => kept, + Err(_) => return Ok(error(WRITE_FAILED)), + } + }; 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, and the rules for // reading apply to them there. let moved = |p: &mut Option| { - if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&kept).ok()) { *p = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } }; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 62f031528b..9fc69e080f 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1192,6 +1192,28 @@ fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() let _ = std::fs::remove_dir_all(base); } +/// Where case does not matter, a folder renamed under its name in another case still moves the open +/// objects of the files in it: changes are written under the new name, not lost at the old one. +#[cfg(any(windows, target_os = "macos"))] +#[test] +fn script_file_rename_of_a_folder_named_in_another_case_moves_its_open_files() { + let base = folder("renamecase"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName; new Folder(d + '/sub').create();\n\ + var f = new File(d + '/sub/f.txt'); f.open('w'); f.write('kept');\n\ + var out = [new Folder(d + '/SUB').rename('moved'), f.close(), f.error]; vc.log(out); vc.log(d);", + ) + .unwrap(); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + assert_eq!(r["log"][0], json!([true, true, ""])); + assert_eq!(std::fs::read(d.join("moved/f.txt")).unwrap(), b"kept"); + assert!(!d.join("sub").exists()); + 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] From fd2baa04225c214e911dc26f2e3e0c76615a1da9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:51:22 -0800 Subject: [PATCH 28/48] Tests: the data folder write test expects Windows line ends and paths on Windows `writeln` uses CRLF by default on Windows, and the script reports paths without the `\?\` prefix that canonicalize adds there. The test expected LF and compared with the prefixed path, so it failed on Windows. It now expects the platform's default line end and compares plain paths. --- crates/engine/src/tests/script_io.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 9fc69e080f..6637d3fe8d 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -500,16 +500,18 @@ fn script_files_write_in_the_temporary_and_data_folders() { 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])); + // The first `writeln` uses the default line end, which is the platform's. + let text = if cfg!(windows) { "a1trueb\r\nc\r\n" } else { "a1trueb\nc\r\n" }; + assert_eq!(r["log"][0], json!([true, true, true, true, true, true, true, text, 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_eq!(std::fs::read(¬es).unwrap(), text.as_bytes()); + assert!(notes.starts_with(crate::cmd::findfiles::plain(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"); + assert_eq!(again["log"], json!([text]), "a script's data folder is kept between runs"); let _ = std::fs::remove_dir_all(base); } From 8620f0611cfb02ea1e5ef7a7522c4dcf939ce8fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:37:25 -0800 Subject: [PATCH 29/48] Scripts: a file whose write fails after it was emptied is named as written Writing an open file's bytes empties the file first. When the write then failed, for example on a full disk, the file had lost its old bytes but was left out of the files the run names as written. It is now named as soon as it has been opened for the write. --- crates/engine/src/script/files.rs | 16 ++++++++++++---- crates/engine/src/tests/script_io.rs | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 7f4052dfb8..05f148e714 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -762,11 +762,17 @@ impl Disk { 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; + // The file stays changed until its bytes are written, so the run's end tries it again. Once + // it is opened its old bytes are gone, so a write that then fails names it in the report too. + let mut out = std::fs::File::create(&real).map_err(|_| WRITE_FAILED)?; + let written = std::io::Write::write_all(&mut out, &file.bytes).is_ok(); + #[cfg(test)] + let written = written && !FLUSH_WRITE_FAILS.with(std::cell::Cell::get); + if written { + file.dirty = false; + } self.wrote(&real); - Ok(()) + if written { Ok(()) } else { Err(WRITE_FAILED) } } /// Writes every open file that has changed: at the end of the run. → the files that could not @@ -2357,6 +2363,8 @@ pub(crate) type CopyHook = Box; #[cfg(test)] thread_local! { pub(crate) static BEFORE_COPY_READ: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Tests: while set, the bytes `flush` writes fail after the file was opened for them. + pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; } #[cfg(test)] diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 6637d3fe8d..eca6dd5638 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -515,6 +515,23 @@ fn script_files_write_in_the_temporary_and_data_folders() { let _ = std::fs::remove_dir_all(base); } +/// A file whose bytes fail to be written after it was opened for them has lost its old bytes, so the +/// failed run names it among the files that stay written. +#[test] +fn script_file_whose_write_fails_partway_is_named_as_written() { + let base = folder("flushfails"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var f = new File(Folder.userData.fsName + '/f.txt'); f.open('w'); f.write('old'); f.close(); vc.log(f.fsName);") + .unwrap(); + let path = r["log"][0].as_str().unwrap().to_string(); + crate::script::files::FLUSH_WRITE_FAILS.with(|f| f.set(true)); + let r = run_in(&mut s, &base, "var f = new File(Folder.userData.fsName + '/f.txt'); f.open('e'); f.write('new'); f.close();"); + crate::script::files::FLUSH_WRITE_FAILS.with(|f| f.set(false)); + let e = format!("{}", r.unwrap_err()); + assert!(e.split("these files stay written:").nth(1).is_some_and(|w| w.contains(&path)), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + /// `copy` reads its source under the rules for reading: a source that a link to a file outside the /// script's places replaced after it was looked up is refused, and nothing is copied. #[cfg(unix)] From b7d85212961739db08326e6dd69a94ddf660aaf4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:32:49 -0800 Subject: [PATCH 30/48] Window: Arrange Documents tiles the documents side by side, stacked or 2-Up to 6-Up Tile laid the open documents out in one grid only, and the application bar had no Arrange Documents button. Window > Arrange now also has Tile All Vertically (side by side in one row), Tile All Horizontally (stacked in one column) and 2-Up, 3-Up, 4-Up and 6-Up layouts, which show that many documents and leave the others under their tabs. Those layouts show the first documents in tab order, and the current document takes the last pane when it is not among them. An Arrange Documents button on the application bar, beside the workspace switcher, lists Consolidate All Windows and the Tile layouts. The item for the layout the panes show is checked. window.arrange.tile takes `layout` (grid, vertical, horizontal, 2up, 3up, 4up or 6up; grid when omitted), refuses any other value, and returns it with {tiled, panes}. ui.inspect reports tileLayout. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/panes.rs | 149 ++++++++++-- crates/ui-egui/src/canvas/panes/tests.rs | 282 ++++++++++++++++++++++- crates/ui-egui/src/chrome.rs | 47 +++- crates/ui-egui/src/control.rs | 7 +- crates/ui-egui/src/doc_windows/tests.rs | 4 +- crates/ui-egui/src/i18n/bg.tsv | 7 + crates/ui-egui/src/i18n/bs.tsv | 7 + crates/ui-egui/src/i18n/ca.tsv | 7 + crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/da.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 7 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fi.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/gu.tsv | 7 + crates/ui-egui/src/i18n/hi.tsv | 7 + crates/ui-egui/src/i18n/hu.tsv | 7 + crates/ui-egui/src/i18n/id.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 7 + crates/ui-egui/src/i18n/ka.tsv | 7 + crates/ui-egui/src/i18n/ko.tsv | 7 + crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 7 + crates/ui-egui/src/i18n/sv.tsv | 7 + crates/ui-egui/src/i18n/tests.rs | 11 + crates/ui-egui/src/i18n/tr.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 7 + crates/ui-egui/src/i18n/zh-hant.tsv | 7 + crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/menus/run.rs | 2 +- crates/ui-egui/src/menus/state.rs | 2 + crates/ui-egui/src/menus/tree.rs | 35 ++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/state.rs | 5 + docs/mcp.md | 22 +- docs/target-app-parity.md | 1 + 44 files changed, 716 insertions(+), 54 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 1bc2d14442..0429a7af31 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -768,7 +768,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + "{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}", ), ( "window.arrange.floatInWindow", diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5c30f96246..1cc1abd5ca 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -63,7 +63,7 @@ use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; #[cfg(test)] use overlays::selected_anchor; use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; -pub use panes::Panes; +pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, pane, tile, tiled_area}; use raster::{changed_pixels, pixel_region, upload}; pub(crate) use raster::{color_image, color_image_owned, render_job}; diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 0a26f26843..6b8eea9440 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -1,5 +1,6 @@ //! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document -//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its +//! area, in a grid, side by side or stacked; the 2-up to 6-up layouts show that many and leave the +//! rest under their tabs ([`Layout`]). The current document's pane is the canvas ([`super::show`]). Each other pane draws its //! document from a render of its own, with its artboards, guides and selected objects, and a press //! in it makes its document the current one. Each view Window › New Window opened has a pane of //! its own ([`crate::doc_windows`]). @@ -38,6 +39,9 @@ pub struct Panes { pending: HashMap, /// The panes the last frame drew, as (window, pane rect). pub(crate) last: Vec<(Win, egui::Rect)>, + /// The slots of `last`'s windows, in the same order: which windows they were, as document + /// indices shift when a document closes. + last_slots: Vec>, /// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and /// center the fit gave. fits: HashMap, @@ -49,6 +53,7 @@ impl Panes { self.shown.clear(); self.pending.clear(); self.last.clear(); + self.last_slots.clear(); self.fits.clear(); } @@ -158,37 +163,123 @@ fn render_pane( img } -/// The grid of `n` panes in `area`, filled row by row: as many columns as the square root of `n` -/// rounded up, and as many rows as those columns need. The panes meet edge to edge and cover -/// `area`; the spare cells of the last row stay empty. -pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec { - if n == 0 { - return vec![]; +/// How Tile lays out the panes (`window.arrange.tile`'s `layout`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Layout { + /// A grid: as many columns as the square root of the number of panes rounded up. + #[default] + Grid, + /// Side by side in one row, each pane as tall as the document area. + Vertical, + /// Stacked in one column, each pane as wide as the document area. + Horizontal, + /// At most this many panes (2, 3, 4 or 6); the other windows stay under their tabs. + Up(usize), +} + +impl Layout { + /// Each layout with its name in `layout`, in the order the menus list them. + pub(crate) const ALL: [(&'static str, Layout); 7] = [ + ("grid", Layout::Grid), + ("vertical", Layout::Vertical), + ("horizontal", Layout::Horizontal), + ("2up", Layout::Up(2)), + ("3up", Layout::Up(3)), + ("4up", Layout::Up(4)), + ("6up", Layout::Up(6)), + ]; + + /// The layout's name in `layout`. + pub(crate) fn name(self) -> &'static str { + Self::ALL.iter().find(|(_, l)| *l == self).map_or("grid", |(n, _)| n) } + + /// The layout `p`'s `layout` names, the grid without one. Any other value is an error. + pub(crate) fn from_params(p: &serde_json::Value) -> Result { + let key = "layout"; + match p.get(key) { + None => Ok(Layout::Grid), + Some(v) => v + .as_str() + .and_then(|s| Self::ALL.iter().find(|(n, _)| *n == s)) + .map(|(_, l)| *l) + .ok_or_else(|| format!("`{key}` must be one of {}", Self::ALL.map(|(n, _)| n).join(", "))), + } + } + + /// How many of `n` windows the layout gives a pane. + fn panes(self, n: usize) -> usize { + match self { + Layout::Up(k) => n.min(k), + _ => n, + } + } + + /// How many columns the layout puts `n` panes in. + fn columns(self, n: usize) -> usize { + match self { + Layout::Grid => grid_columns(n), + Layout::Vertical => n, + Layout::Horizontal => 1, + Layout::Up(k) if k <= 3 => n, + Layout::Up(k) => grid_columns(k).min(n), + } + } +} + +/// The square root of `n` rounded up. +fn grid_columns(n: usize) -> usize { let mut cols = 1; while cols * cols < n { cols += 1; } + cols +} + +/// The `n` panes `layout` places in `area`, filled row by row, in as many rows as its columns +/// need (the grid: as many columns as the square root of `n` rounded up). The panes meet edge to +/// edge and cover `area`; the spare cells of the last row stay empty. +pub(crate) fn layout_cells(layout: Layout, n: usize, area: egui::Rect) -> Vec { + if n == 0 { + return vec![]; + } + let cols = layout.columns(n).clamp(1, n); let rows = n.div_ceil(cols); let x = |c: usize| if c == cols { area.right() } else { area.left() + area.width() * c as f32 / cols as f32 }; let y = |r: usize| if r == rows { area.bottom() } else { area.top() + area.height() * r as f32 / rows as f32 }; (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } -/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own, -/// each fitted to its pane. With fewer than two windows open (when the menu item is grayed out) it -/// leaves the view and `tiled` as they are. The windows floating come back under the tabs for it. -pub(crate) fn tile(app: &mut VectorcraftApp) -> Result { +/// The windows of `docked` (in tab order) that `layout` gives a pane: all of them, or as many of +/// the first ones as it shows, with the current window `active` in the last pane when it is not +/// among them. +pub(crate) fn shown_windows(layout: Layout, docked: &[Win], active: Option) -> Vec { + let k = layout.panes(docked.len()); + let mut shown = docked[..k].to_vec(); + if let (Some(a), Some(last)) = (active.filter(|a| !shown.contains(a) && docked.contains(a)), shown.last_mut()) { + *last = a; + } + shown +} + +/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own +/// as `layout` places them (the grid without one), each fitted to its pane. With fewer than two +/// windows open (when the menu item is grayed out) it leaves the view, `tiled` and the layout as +/// they are. The windows floating come back under the tabs for it. A `layout` that is not one of +/// [`Layout::ALL`]'s names is an error. +pub(crate) fn tile(app: &mut VectorcraftApp, p: &serde_json::Value) -> Result { + let layout = Layout::from_params(p)?; app.sync_views(); let n = crate::doc_windows::windows(app).len(); if n < 2 { - return Ok(json!({"tiled": app.ui.tiled, "panes": n})); + return Ok(json!({"tiled": app.ui.tiled, "panes": n, "layout": app.ui.tile_layout.name()})); } crate::doc_windows::dock_all(app); app.ui.tiled = true; + app.ui.tile_layout = layout; app.ui.home = None; crate::doc_windows::unfit_all(app); - Ok(json!({"tiled": app.ui.tiled, "panes": n})) + Ok(json!({"tiled": app.ui.tiled, "panes": layout.panes(n), "layout": layout.name()})) } /// `window.arrange.consolidateAllWindows`: one document at a time again, under its tab, the @@ -216,27 +307,41 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.clear(); } app.canvas.panes.last.clear(); + app.canvas.panes.last_slots.clear(); return false; } // The current window's pane is the canvas, unless it is a floating one. let active = crate::doc_windows::current(app).filter(|a| docked.contains(a)); + // The 2-up to 6-up layouts leave the windows past their panes under the tabs. + let layout = app.ui.tile_layout; + let shown = shown_windows(layout, &docked, active); app.sync_views(); - let live: Vec = crate::doc_windows::windows(app).into_iter().filter_map(|w| slot(app, w)).collect(); + // The renders of the panes and the floating windows stay; a window under its tab has none. + let live: Vec = + crate::doc_windows::windows(app).into_iter().filter(|w| shown.contains(w) || !docked.contains(w)).filter_map(|w| slot(app, w)).collect(); app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); - // A window opened, closed, floated or docked changes the grid, and so does coming back to the - // panes from one window: each window fits its new pane. - if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) { - for w in &docked { - if let Some(v) = crate::doc_windows::view_mut(app, *w) { - v.fitted = false; - } + // A window opened, closed, floated or docked changes the panes, and so does coming back to the + // panes from one window: each window fits its new pane. With as many panes as before, only a + // window that moved to another pane fits it, as when a tab brings its window into the last pane + // of a 2-up to 6-up layout: the others keep their zoom and scroll. Windows are compared by + // their slots, since a closed document shifts the indices of the documents after it. + let before = std::mem::take(&mut app.canvas.panes.last_slots); + let now: Vec> = shown.iter().map(|w| slot(app, *w)).collect(); + let same_panes = before.len() == now.len(); + for (i, (w, s)) in shown.iter().zip(&now).enumerate() { + if same_panes && s.is_some() && before.get(i) == Some(s) { + continue; + } + if let Some(v) = crate::doc_windows::view_mut(app, *w) { + v.fitted = false; } } + app.canvas.panes.last_slots = now; let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); - let cells: Vec<(Win, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect(); + let cells: Vec<(Win, egui::Rect)> = shown.iter().copied().zip(layout_cells(layout, shown.len(), ui.available_rect_before_wrap())).collect(); let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect(); let unfitted = refit_resized(app, &areas); let mut activate = None; diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 005b930d01..2ad0af3dc1 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -43,6 +43,11 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event { egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } } +/// Tile's grid of `n` panes in `area`. +fn cells(n: usize, area: egui::Rect) -> Vec { + layout_cells(Layout::Grid, n, area) +} + /// The documents' indices in the panes the last frame drew, and the panes. fn panes(app: &VectorcraftApp) -> (Vec, Vec) { app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip() @@ -84,6 +89,279 @@ fn cells_tile_the_area_edge_to_edge() { } } +/// The distinct left and top edges of `c`: how many columns and rows its panes take. +fn columns_and_rows(c: &[egui::Rect]) -> (usize, usize) { + let lefts: BTreeSet = c.iter().map(|r| r.left().to_bits()).collect(); + let tops: BTreeSet = c.iter().map(|r| r.top().to_bits()).collect(); + (lefts.len(), tops.len()) +} + +#[test] +fn each_tile_layout_places_its_panes_edge_to_edge() { + let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1001.0, 703.0)); + let cases = [ + (Layout::Vertical, 3, (3, 1)), + (Layout::Vertical, 7, (7, 1)), + (Layout::Horizontal, 3, (1, 3)), + (Layout::Up(2), 2, (2, 1)), + (Layout::Up(3), 3, (3, 1)), + (Layout::Up(3), 2, (2, 1)), + (Layout::Up(4), 4, (2, 2)), + (Layout::Up(4), 3, (2, 2)), + (Layout::Up(6), 6, (3, 2)), + (Layout::Up(6), 4, (3, 2)), + (Layout::Up(6), 2, (2, 1)), + ]; + for (layout, n, shape) in cases { + let c = layout_cells(layout, n, area); + assert_eq!(c.len(), n); + assert_eq!(columns_and_rows(&c), shape, "{layout:?} with {n} panes: columns and rows"); + assert_eq!(c[0].min, area.min, "{layout:?}: the first pane starts at the corner"); + let right = c.iter().map(|r| r.right()).fold(f32::MIN, f32::max); + let bottom = c.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max); + assert_eq!((right, bottom), (area.right(), area.bottom()), "{layout:?} with {n} panes reaches the far edges"); + for (i, r) in c.iter().enumerate() { + assert!(r.width() > 0.0 && r.height() > 0.0 && area.contains_rect(*r), "{layout:?}: {r:?}"); + for o in &c[i + 1..] { + assert!(r.intersect(*o).area() <= 0.0, "{layout:?} panes overlap: {r:?} {o:?}"); + } + } + } + assert!(layout_cells(Layout::Up(2), 0, area).is_empty()); +} + +#[test] +fn tile_layouts_line_the_documents_up_side_by_side_or_stacked() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + let reply = app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "vertical"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].top() == p[1].top() && p[0].height() == p[1].height() && p[0].right() == p[1].left()), "{rects:?}"); + let reply = app.run("window.arrange.tile", json!({"layout": "horizontal"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "horizontal"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].left() == p[1].left() && p[0].width() == p[1].width() && p[0].bottom() == p[1].top()), "{rects:?}"); + // Each document fits its new pane. + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let canvas = app.canvas_rect.unwrap(); + for (i, r) in docs.iter().zip(&rects) { + let shown = if *i == 2 { canvas } else { view_rects(&app, *r, ctx.pixels_per_point()).1 }; + let v = app.views[*i]; + assert!(v.fitted && (v.zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its pane: {v:?}"); + } + assert_eq!(crate::control::inspect(&app, &ctx)["tileLayout"], json!("horizontal")); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap()["layout"], json!("grid"), "Tile without a layout is the grid"); +} + +#[test] +fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() { + let mut app = app_with(5); + let ctx = egui::Context::default(); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "2up"})); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 4], "the current document takes the last pane"); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1], "the first documents in tab order"); + let second = (app.session.documents()[1].uid, 1); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.shown.contains_key(&second), "the second document is rendered for its pane"); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 3], "a document chosen under its tab comes into the last pane"); + assert!(!app.canvas.panes.shown.contains_key(&second), "a document under its tab keeps no render"); + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let shown = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + assert!((app.views[0].zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9); + assert!(app.canvas_rect.is_some_and(|c| rects[1].contains_rect(c)), "the current document's pane is the canvas"); + // A document brought into the last pane leaves the first pane's zoom as it is. + app.views[0].zoom *= 2.0; + let zoomed = app.views[0].zoom; + app.run("document.activate", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 2]); + assert_eq!(app.views[0].zoom, zoomed, "the document that stayed in its pane keeps its zoom"); + let last = app.canvas_rect.unwrap(); + assert!((app.views[2].zoom - fit_zoom(last, artboard, 0.0, 1.0)).abs() < 1e-9, "the document brought in fits its pane"); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap()["panes"], json!(4)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3], (2, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap()["panes"], json!(5), "6-Up with five documents shows them all"); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "3up"})).unwrap()["panes"], json!(3)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2], (3, 1))); + app.run("document.activate", json!({"index": 4})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 4]); +} + +/// A document closed before the panes shifts the indices of the ones after it: the document that +/// moves into another pane fits it. +#[test] +fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() { + let mut app = app_with(4); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 3]); + let moving = app.session.documents()[1].uid; + // The second document's view, under its tab, is zoomed away from its fit. + app.views[1].zoom *= 3.0; + app.run("file.close", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 2], "the former second document is first now, the current one stays last"); + assert_eq!(app.session.documents()[0].uid, moving); + let area = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + let v = app.views[0]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}"); +} + +#[test] +fn tile_refuses_a_layout_it_does_not_have() { + let mut app = app_with(3); + for bad in [json!("5up"), json!("Vertical"), json!(3), json!(null), json!({})] { + let err = app.run("window.arrange.tile", json!({"layout": bad})).unwrap_err(); + assert_eq!(err, "`layout` must be one of grid, vertical, horizontal, 2up, 3up, 4up, 6up", "{bad}"); + assert!(!app.ui.tiled && app.ui.tile_layout == Layout::Grid, "{bad}: the view stays as it is"); + } + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert!(app.run("window.arrange.tile", json!({"layout": "diagonal"})).is_err()); + assert_eq!(app.ui.tile_layout, Layout::Vertical, "a refused layout leaves the tiled one"); + // With one document the layout is still checked, and nothing changes. + let mut one = app_with(1); + assert!(one.run("window.arrange.tile", json!({"layout": "7up"})).is_err()); + assert_eq!(one.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); +} + +#[test] +fn the_tile_items_check_the_layout_the_panes_show() { + let mut app = app_with(3); + let checked = |app: &VectorcraftApp, layout: Option<&str>| { + let p = layout.map_or(serde_json::Value::Null, |l| json!({"layout": l})); + crate::menus::checked(app, "window.arrange.tile", &p) + }; + assert_eq!(checked(&app, None), Some(false), "not tiled"); + app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap(); + assert_eq!(checked(&app, Some("4up")), Some(true)); + assert_eq!(checked(&app, None), Some(false)); + assert_eq!(checked(&app, Some("2up")), Some(false)); + app.run("window.arrange.tile", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(true), "Tile is the grid"); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(false)); + // Window › Arrange lists every layout, after Cascade and before Float in Window. + let window = crate::menus::menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, items)| items).unwrap(); + let arrange = window + .into_iter() + .find_map(|i| match i { + crate::menus::Item::Sub("Arrange", items) => Some(items), + _ => None, + }) + .unwrap(); + let labels: Vec<&str> = arrange + .iter() + .filter_map(|i| match i { + crate::menus::Item::Cmd(l, ..) => Some(*l), + _ => None, + }) + .collect(); + assert_eq!( + labels, + [ + "Cascade", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + "Float in Window", + "Float All in Windows", + "Consolidate All Windows" + ] + ); + // Each item's params run, as the menu sends them. + for item in &arrange { + if let crate::menus::Item::Cmd(_, "window.arrange.tile", p) = item { + let p = if p.is_null() { json!({}) } else { p.clone() }; + assert!(app.run("window.arrange.tile", p.clone()).is_ok(), "{p}"); + } + } +} + +/// One frame of the application bar with screen-reader nodes on → the nodes. +fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 800.0)); + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() +} + +/// The center of the application bar's node whose label, without its leading spaces, is `name` +/// (or starts with it and a shortcut in parentheses). +fn app_bar_node(nodes: &[egui::accesskit::Node], name: &str) -> Option { + let named = |l: &str| l.trim_start().strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.trim_start().starts_with('(')); + let b = nodes.iter().find(|n| n.label().is_some_and(named))?.bounds()?; + Some(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)) +} + +/// Click the application bar's node labeled `name`. +fn click_app_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let at = app_bar_node(&app_bar_frame(app, ctx, vec![]), name).unwrap_or_else(|| panic!("{name} is drawn")); + app_bar_frame(app, ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); + app_bar_frame(app, ctx, vec![button(at, false)]); +} + +#[test] +fn the_arrange_documents_button_tiles_and_consolidates() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + app_bar_frame(&mut app, &ctx, vec![]); + let nodes = app_bar_frame(&mut app, &ctx, vec![]); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands and tools")); + let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search icon shows")); + assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search icon: {arrange:?}, {search:?}"); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + let menu = app_bar_frame(&mut app, &ctx, vec![]); + for item in [ + "Consolidate All Windows", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + ] { + assert!(app_bar_node(&menu, item).is_some(), "the menu lists {item}"); + } + click_app_bar(&mut app, &ctx, "Tile All Vertically"); + assert!(app.ui.tiled && app.ui.tile_layout == Layout::Vertical, "{}", app.ui.status); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + click_app_bar(&mut app, &ctx, "Consolidate All Windows"); + assert!(!app.ui.tiled); +} + #[test] fn tile_shows_a_pane_for_each_document_fitted_to_it() { let mut app = app_with(3); @@ -91,7 +369,7 @@ fn tile_shows_a_pane_for_each_document_fitted_to_it() { frame(&mut app, &ctx, vec![]); assert!(panes(&app).0.is_empty(), "documents open under their tabs"); let tabbed = app.canvas_rect.unwrap(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); let (docs, rects) = panes(&app); assert_eq!(docs, [0, 1, 2]); @@ -206,7 +484,7 @@ fn arrange_items_follow_the_open_documents() { fn tile_with_one_document_leaves_the_next_one_under_its_tab() { let mut app = app_with(1); let ctx = egui::Context::default(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); assert!(!app.ui.tiled); assert!(!enabled(&app, "window.arrange.consolidateAllWindows")); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index fc0234885b..96b4d12965 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -85,7 +85,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // The right-side group fills the space after the menus from the right; when it runs // short, Discord goes first (it is also under Help), then Explore tutorials (also // Window › Learn), then the search icon (the palette stays under its shortcut), then - // the workspace switcher narrows. + // Arrange Documents (also Window › Arrange), then the workspace switcher narrows. let full = ui.max_rect(); let right_edge = if captions_right > 0.0 { full.right() - captions_right - 10.0 } else { full.right() }; let right = egui::Rect::from_min_max(egui::pos2(menus_end + 8.0, full.top()), egui::pos2(right_edge, full.bottom())); @@ -105,13 +105,16 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let ws = ui.painter().layout_no_wrap(ws_name, egui::FontId::proportional(12.0), t.text); let ws_w = (ws.size().x + 36.0).clamp(112.0, 190.0); let gap = ui.spacing().item_spacing.x; - // The search icon, as in PhotoCraft: shown while a minimal switcher fits beside it. + // Arrange Documents, beside the switcher, then the search icon, as in PhotoCraft: each + // shown while a minimal switcher fits beside it. let icon = 28.0; - let search = switcher && room >= 64.0 + 8.0 + gap + icon; - let ws_w = ws_w.min(room - 8.0 - gap - if search { icon } else { 0.0 }).max(64.0); + let arrange = switcher && room >= 64.0 + 8.0 + gap + icon; + let search = arrange && room >= 64.0 + 8.0 + 2.0 * (gap + icon); + let icons = f32::from(u8::from(arrange) + u8::from(search)); + let ws_w = ws_w.min(room - 8.0 - icons * (gap + icon)).max(64.0); // Explore tutorials, beside the search icon, opens the Learn panel. - let learn = search && room >= ws_w + 8.0 + 2.0 * (gap + icon); - let discord = learn && room >= ws_w + 8.0 + 2.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); + let learn = search && room >= ws_w + 8.0 + 3.0 * (gap + icon); + let discord = learn && room >= ws_w + 8.0 + 3.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center))); let ui = &mut rui; // Workspace switcher: shows the current workspace, opens Window → Workspace. @@ -130,6 +133,11 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.add_space(8.0); } + // Arrange Documents: Consolidate All Windows and the Tile layouts. + if arrange { + let resp = widgets::icon_button(ui, "layout-grid", tl!("Arrange Documents"), app.ui.tiled, icon); + egui::Popup::menu(&resp).show(|ui| arrange_documents_popup(app, ui)); + } // Search → command palette (its shortcut opens it too). if search { let tip = match menus::shortcut_of("help.commandPalette") { @@ -168,6 +176,33 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The Arrange Documents menu ([`menus::arrange_documents_items`]): each item as the Window menu +/// shows it, grayed out while its command can't run, the Tile layout the panes show checked. +fn arrange_documents_popup(app: &mut VectorcraftApp, ui: &mut Ui) { + ui.set_min_width(200.0); + let mut clicked = None; + for it in menus::arrange_documents_items() { + match it { + menus::Item::Sep => { + ui.separator(); + } + menus::Item::Cmd(label, id, p) => { + let Some((enabled, checked)) = menus::shown_state(app, id, &p) else { continue }; + let label = crate::i18n::t_id(id, label); + let text = if checked == Some(true) { format!("✓ {label}") } else { format!(" {label}") }; + if ui.add_enabled(enabled, egui::Button::new(text).min_size(vec2(200.0, 0.0))).clicked() { + clicked = Some((id, if p.is_null() { json!({}) } else { p })); + ui.close(); + } + } + _ => {} + } + } + if let Some((id, p)) = clicked { + menus::invoke(app, id, p); + } +} + /// Whether the window shows the system's title bar instead of the app drawing its own /// ([`VectorcraftApp::desktop_frame`]): Windows with Preferences › User Interface › System Title /// Bar, and Linux whenever the desktop draws the frame, with or without the preference. The diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 26f67a0365..461b352c4e 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -273,11 +273,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // The display profile the canvas is drawn through, or why none (Preferences › // Performance › Use Monitor Profile for Canvas). "displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display), - // Window › Arrange › Tile (not saved, so not in `ui`) and the panes the last frame drew: - // each one's document index, view number (Window › New Window) and rect. Canvas - // coordinates map to the current window's pane, inside its rulers and scroll bars + // Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the + // last frame drew: each one's document index, view number (Window › New Window) and rect. + // Canvas coordinates map to the current window's pane, inside its rulers and scroll bars // (`canvasRect`). "tiled": app.ui.tiled, + "tileLayout": app.ui.tile_layout.name(), "panes": app.canvas.panes.last.iter().map(|(w, c)| json!({ "document": w.0, "view": w.1, diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 64a693a09b..91a0ef23e4 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -259,7 +259,7 @@ fn tile_brings_floating_documents_back_into_the_grid() { frame(&mut app, &ctx, vec![]); let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1], "a floating document leaves the grid; the tabbed ones share it"); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1, 2]); @@ -844,7 +844,7 @@ fn arrange_treats_each_view_as_a_window() { assert!(!enabled(&app, "window.arrange.tile") && !enabled(&app, "window.arrange.cascade"), "one window"); app.run("window.newWindow", json!({})).unwrap(); assert!(enabled(&app, "window.arrange.tile") && enabled(&app, "window.arrange.cascade"), "two views of one document"); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "grid"})); app.run("window.arrange.cascade", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); let uid = app.session.documents()[0].uid; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d0a770b2b1..ffeacfc3f5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3643,6 +3643,13 @@ digits Malayalam Малаялам Thumbnail View Изглед с миниатюри Thumbnails: Миниатюри: Tile Мозайка + Tile All Vertically Всички в мозайка вертикално + Tile All Horizontally Всички в мозайка хоризонтално + 2-Up Layout Подредба по 2 + 3-Up Layout Подредба по 3 + 4-Up Layout Подредба по 4 + 6-Up Layout Подредба по 6 + Arrange Documents Подреждане на документите Tile Edge Color Цвят на ръба на плочката Tile Edge Color… Цвят на ръба на плочката… Tile Full Pages Покриване на цели страници diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5fca937f98..916a3e6b5f 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -689,6 +689,13 @@ Previous Document Prethodni dokument Cascade Kaskadno Tile Popločaj + Tile All Vertically Popločaj sve okomito + Tile All Horizontally Popločaj sve vodoravno + 2-Up Layout Raspored po 2 + 3-Up Layout Raspored po 3 + 4-Up Layout Raspored po 4 + 6-Up Layout Raspored po 6 + Arrange Documents Rasporedi dokumente Float in Window Odvoji u prozor Float All in Windows Odvoji sve u prozore Consolidate All Windows Objedini sve prozore diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b6fdc2a6a6..7fe0977ead 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4740,6 +4740,13 @@ digits Malayalam Malaiàlam TIFF (8-bit Color) TIFF (color de 8 bits) TIFF (Black & White) TIFF (blanc i negre) Tile Mosaic + Tile All Vertically Mosaic vertical de tot + Tile All Horizontally Mosaic horitzontal de tot + 2-Up Layout Disposició de 2 + 3-Up Layout Disposició de 3 + 4-Up Layout Disposició de 4 + 6-Up Layout Disposició de 6 + Arrange Documents Organitza els documents Tile Edge Color Color de la vora del mosaic Tile Edge Color… Color de la vora del mosaic… Tile Full Pages Mosaic de pàgines senceres diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 47ca092cc0..d9fa87f2bf 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -702,6 +702,13 @@ Previous Document Předchozí dokument Cascade Do kaskády Tile Vedle sebe + Tile All Vertically Vše vedle sebe svisle + Tile All Horizontally Vše vedle sebe vodorovně + 2-Up Layout Rozvržení po 2 + 3-Up Layout Rozvržení po 3 + 4-Up Layout Rozvržení po 4 + 6-Up Layout Rozvržení po 6 + Arrange Documents Uspořádat dokumenty Float in Window Uvolnit do samostatného okna Float All in Windows Uvolnit vše do samostatných oken Consolidate All Windows Sloučit všechna okna diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ca27bdd2f9..57322a818e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1257,6 +1257,13 @@ Previous Document Forrige dokument Cascade Kaskade Tile Fliselæg + Tile All Vertically Fliselæg alle lodret + Tile All Horizontally Fliselæg alle vandret + 2-Up Layout Layout med 2 + 3-Up Layout Layout med 3 + 4-Up Layout Layout med 4 + 6-Up Layout Layout med 6 + Arrange Documents Arrangér dokumenter Float in Window Flyd i vindue Float All in Windows Flyd alle i vinduer Consolidate All Windows Saml alle vinduer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index df4d5df82e..3da18ee5ba 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3686,6 +3686,13 @@ effect Points Punkte Thumbnail View Miniaturansicht Thumbnails: Miniaturen: Tile Nebeneinander + Tile All Vertically Alle vertikal nebeneinander + Tile All Horizontally Alle horizontal nebeneinander + 2-Up Layout Layout mit 2 + 3-Up Layout Layout mit 3 + 4-Up Layout Layout mit 4 + 6-Up Layout Layout mit 6 + Arrange Documents Dokumente anordnen Tile Edge Color Farbe der Kachelkante Tile Edge Color… Farbe der Kachelkante… Tile Full Pages Ganze Seiten aufteilen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9f3ee177e5..739d63f664 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2171,6 +2171,13 @@ font-technology Variable Μεταβλητές Templates Πρότυπα Threshold Κατώφλι Tile Παράθεση + Tile All Vertically Παράθεση όλων κατακόρυφα + Tile All Horizontally Παράθεση όλων οριζόντια + 2-Up Layout Διάταξη ανά 2 + 3-Up Layout Διάταξη ανά 3 + 4-Up Layout Διάταξη ανά 4 + 6-Up Layout Διάταξη ανά 6 + Arrange Documents Διάταξη εγγράφων Tint Χρωματική απόχρωση Fill Tint Χρωματική απόχρωση γεμίσματος Stroke Tint Χρωματική απόχρωση περιγράμματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 555e51b8c7..8244d1fee3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3734,6 +3734,13 @@ digits Malayalam Malayálam Thumbnail View Vista de miniaturas Thumbnails: Miniaturas: Tile Mosaico + Tile All Vertically Mosaico vertical de todo + Tile All Horizontally Mosaico horizontal de todo + 2-Up Layout Disposición de 2 + 3-Up Layout Disposición de 3 + 4-Up Layout Disposición de 4 + 6-Up Layout Disposición de 6 + Arrange Documents Organizar documentos Tile Edge Color Color del borde del mosaico Tile Edge Color… Color del borde del mosaico… Tile Full Pages Mosaico de páginas completas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 363042b43d..85043309b2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -693,6 +693,13 @@ Previous Document Edellinen asiakirja Cascade Porrasta Tile Vierekkäin + Tile All Vertically Kaikki vierekkäin pystysuunnassa + Tile All Horizontally Kaikki vierekkäin vaakasuunnassa + 2-Up Layout 2 ikkunan asettelu + 3-Up Layout 3 ikkunan asettelu + 4-Up Layout 4 ikkunan asettelu + 6-Up Layout 6 ikkunan asettelu + Arrange Documents Järjestä asiakirjat Float in Window Kelluta ikkunassa Float All in Windows Kelluta kaikki ikkunoissa Consolidate All Windows Yhdistä kaikki ikkunat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 494a2d944a..6ea29e0c88 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3726,6 +3726,13 @@ digits Malayalam Malayalam Thumbnail View Vignettes Thumbnails: Vignettes : Tile Mosaïque + Tile All Vertically Tout en mosaïque verticale + Tile All Horizontally Tout en mosaïque horizontale + 2-Up Layout Disposition par 2 + 3-Up Layout Disposition par 3 + 4-Up Layout Disposition par 4 + 6-Up Layout Disposition par 6 + Arrange Documents Disposer les documents Tile Edge Color Couleur du bord du carreau Tile Edge Color… Couleur du bord du carreau… Tile Full Pages Mosaïque de pages entières diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 7382b4fe9e..f7d8b1c2a9 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3837,6 +3837,13 @@ Three Point Perspective Preset 5 ત્રણ બિંદુ પર્સ્પેક્ટિવ પ્રીસેટ 5 Thumbnails: થંબનેલ: Tile ટાઇલ + Tile All Vertically બધું ઊભી રીતે ટાઇલ કરો + Tile All Horizontally બધું આડી રીતે ટાઇલ કરો + 2-Up Layout 2 નું લેઆઉટ + 3-Up Layout 3 નું લેઆઉટ + 4-Up Layout 4 નું લેઆઉટ + 6-Up Layout 6 નું લેઆઉટ + Arrange Documents દસ્તાવેજો ગોઠવો Tile Edge Color ટાઇલ કિનારીનો રંગ Tile Edge Color… ટાઇલ કિનારીનો રંગ… Tile Range: ટાઇલ શ્રેણી: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index edfbe0818f..a1bbffcb84 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5130,6 +5130,13 @@ antiAlias Sharp शार्प TIFF (8-bit Color) TIFF (8-बिट रंग) TIFF (Black & White) TIFF (ब्लैक एंड व्हाइट) Tile टाइल + Tile All Vertically सभी को लंबवत टाइल करें + Tile All Horizontally सभी को क्षैतिज टाइल करें + 2-Up Layout 2 का लेआउट + 3-Up Layout 3 का लेआउट + 4-Up Layout 4 का लेआउट + 6-Up Layout 6 का लेआउट + Arrange Documents दस्तावेज़ व्यवस्थित करें tile {number} टाइल {number} Tile Edge Color टाइल एज रंग Tile Edge Color… टाइल एज रंग… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 27dda10840..b57ce2d524 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4420,6 +4420,13 @@ mark-style Japanese Japán TIFF (8-bit Color) TIFF (8 bites színes) TIFF (Black & White) TIFF (fekete-fehér) Tile Mozaikelrendezés + Tile All Vertically Összes mozaikelrendezése függőlegesen + Tile All Horizontally Összes mozaikelrendezése vízszintesen + 2-Up Layout 2-es elrendezés + 3-Up Layout 3-as elrendezés + 4-Up Layout 4-es elrendezés + 6-Up Layout 6-os elrendezés + Arrange Documents Dokumentumok elrendezése Tile Edge Color Csempeszél színe Tile Edge Color… Csempeszél színe… Tile Full Pages Teljes oldalak csempézése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f870492477..d323f3fb3d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -648,6 +648,13 @@ Previous Document Dokumen sebelumnya Cascade Bertingkat Tile Ubin + Tile All Vertically Ubin semua secara vertikal + Tile All Horizontally Ubin semua secara horizontal + 2-Up Layout Tata letak 2 + 3-Up Layout Tata letak 3 + 4-Up Layout Tata letak 4 + 6-Up Layout Tata letak 6 + Arrange Documents Susun dokumen Float in Window Mengambang di jendela Float All in Windows Mengambangkan semua di jendela Consolidate All Windows Konsolidasikan semua jendela diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7ef7dedc00..be1847efa5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3780,6 +3780,13 @@ digits Malayalam Malayalam Thumbnail View Vista miniature Thumbnails: Miniature: Tile Affianca + Tile All Vertically Affianca tutto verticalmente + Tile All Horizontally Affianca tutto orizzontalmente + 2-Up Layout Layout a 2 + 3-Up Layout Layout a 3 + 4-Up Layout Layout a 4 + 6-Up Layout Layout a 6 + Arrange Documents Disponi documenti Tile Edge Color Colore bordo tassello Tile Edge Color… Colore bordo tassello… Tile Full Pages Affianca pagine intere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c18d4c55ca..aabea31a78 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -725,6 +725,13 @@ digits Malayalam マラヤーラム数字 Previous Document 前のドキュメント Cascade 重ねて表示 Tile 並べて表示 + Tile All Vertically すべてを左右に並べて表示 + Tile All Horizontally すべてを上下に並べて表示 + 2-Up Layout 2 分割レイアウト + 3-Up Layout 3 分割レイアウト + 4-Up Layout 4 分割レイアウト + 6-Up Layout 6 分割レイアウト + Arrange Documents ドキュメントの配置 Float in Window ウィンドウを分離 Float All in Windows すべてをウィンドウに分離 Consolidate All Windows すべてのウィンドウを統合 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5ab6945aec..33cafdc24e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -622,6 +622,13 @@ Previous Document წინა დოკუმენტი Cascade კასკადად Tile ფილებად + Tile All Vertically ყველა ფილებად ვერტიკალურად + Tile All Horizontally ყველა ფილებად ჰორიზონტალურად + 2-Up Layout 2-იანი განლაგება + 3-Up Layout 3-იანი განლაგება + 4-Up Layout 4-იანი განლაგება + 6-Up Layout 6-იანი განლაგება + Arrange Documents დოკუმენტების დალაგება Float in Window ცალკე ფანჯარაში გამოტანა Float All in Windows ყველას ცალკე ფანჯრებში გამოტანა Consolidate All Windows ყველა ფანჯრის გაერთიანება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9ed9cd6a98..bbfc3bfed6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -718,6 +718,13 @@ digits Malayalam 말라얄람어 Previous Document 이전 문서 Cascade 계단식 배열 Tile 바둑판식 배열 + Tile All Vertically 모두 세로로 바둑판식 배열 + Tile All Horizontally 모두 가로로 바둑판식 배열 + 2-Up Layout 2분할 레이아웃 + 3-Up Layout 3분할 레이아웃 + 4-Up Layout 4분할 레이아웃 + 6-Up Layout 6분할 레이아웃 + Arrange Documents 문서 정렬 Float in Window 창에 플로팅 Float All in Windows 모두 창에 플로팅 Consolidate All Windows 모든 창 통합 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 711ce4c8a8..002aabacc0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1166,6 +1166,13 @@ Previous Document Vorig document Cascade Trapsgewijs schikken Tile Naast elkaar schikken + Tile All Vertically Alles verticaal naast elkaar schikken + Tile All Horizontally Alles horizontaal naast elkaar schikken + 2-Up Layout Indeling met 2 + 3-Up Layout Indeling met 3 + 4-Up Layout Indeling met 4 + 6-Up Layout Indeling met 6 + Arrange Documents Documenten schikken Float in Window In venster zweven Float All in Windows Alles in vensters zweven Consolidate All Windows Alle vensters samenvoegen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7e29ed89c5..cde65748c8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -659,6 +659,13 @@ Previous Document Poprzedni dokument Cascade Kaskadowo Tile Sąsiadująco + Tile All Vertically Wszystkie sąsiadująco w pionie + Tile All Horizontally Wszystkie sąsiadująco w poziomie + 2-Up Layout Układ po 2 + 3-Up Layout Układ po 3 + 4-Up Layout Układ po 4 + 6-Up Layout Układ po 6 + Arrange Documents Rozmieść dokumenty Float in Window Pływające w oknie Float All in Windows Wszystkie pływające w oknach Consolidate All Windows Scal wszystkie okna diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b9d233f1c9..8867015300 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3088,6 +3088,13 @@ digits Malayalam Malaiala Threshold Limite Thumbnail View Exibição em Miniatura Tile Bloco + Tile All Vertically Todos em Bloco na Vertical + Tile All Horizontally Todos em Bloco na Horizontal + 2-Up Layout Layout de 2 + 3-Up Layout Layout de 3 + 4-Up Layout Layout de 4 + 6-Up Layout Layout de 6 + Arrange Documents Organizar Documentos Tile Edge Color Cor da Borda do Bloco Tile Edge Color… Cor da Borda do Bloco… Tile Range: Intervalo de Blocos: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 5845c34c1d..3940cb892d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3766,6 +3766,13 @@ digits Malayalam Малаялам Thumbnail View Миниатюры Thumbnails: Миниатюры: Tile Плитка + Tile All Vertically Все плиткой по вертикали + Tile All Horizontally Все плиткой по горизонтали + 2-Up Layout Макет на 2 + 3-Up Layout Макет на 3 + 4-Up Layout Макет на 4 + 6-Up Layout Макет на 6 + Arrange Documents Упорядочить документы Tile Edge Color Цвет края плитки Tile Edge Color… Цвет края плитки… Tile Full Pages Плитка целых страниц diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9e37b924b0..b070c937a1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3656,6 +3656,13 @@ digits Malayalam Malayalam Thumbnail View Miniatyrvy Thumbnails: Miniatyrer: Tile Sida vid sida + Tile All Vertically Alla sida vid sida lodrätt + Tile All Horizontally Alla sida vid sida vågrätt + 2-Up Layout Layout med 2 + 3-Up Layout Layout med 3 + 4-Up Layout Layout med 4 + 6-Up Layout Layout med 6 + Arrange Documents Ordna dokument Tile Edge Color Rutkantsfärg Tile Edge Color… Rutkantsfärg… Tile Full Pages Dela upp i hela sidor diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b23fc994a9..7f86184a60 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -421,6 +421,17 @@ fn built_in_library_brush_names_are_in_complete_catalogs() { assert!(bad.is_empty(), "{}", bad.join("\n")); } +/// Window › Arrange's Tile layouts and the application bar's Arrange Documents button. +#[test] +fn tile_layout_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Tile All Vertically", "Tile All Horizontally", "2-Up Layout", "3-Up Layout", "4-Up Layout", "6-Up Layout", "Arrange Documents"] + { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// Preference choices and the marquee's E hint share the same translated labels. #[test] fn marquee_selection_labels_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e5278e58c6..9096a2d401 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3519,6 +3519,13 @@ digits Malayalam Malayalam Thumbnail View Küçük Resim Görünümü Thumbnails: Küçük resimler: Tile Fayans + Tile All Vertically Tümünü Dikey Fayans + Tile All Horizontally Tümünü Yatay Fayans + 2-Up Layout 2'li Düzen + 3-Up Layout 3'lü Düzen + 4-Up Layout 4'lü Düzen + 6-Up Layout 6'lı Düzen + Arrange Documents Belgeleri Düzenle Tile Edge Color Döşeme Kenar Rengi Tile Edge Color… Döşeme Kenar Rengi… Tile Full Pages Tam Sayfaları Döşe diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 160d9a2c09..c01d0a2141 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3773,6 +3773,13 @@ effect Points Точки Thumbnail View Мініатюри Thumbnails: Мініатюри: Tile Плитка + Tile All Vertically Усі плиткою вертикально + Tile All Horizontally Усі плиткою горизонтально + 2-Up Layout Макет на 2 + 3-Up Layout Макет на 3 + 4-Up Layout Макет на 4 + 6-Up Layout Макет на 6 + Arrange Documents Упорядкувати документи Tile Edge Color Колір краю плитки Tile Edge Color… Колір краю плитки… Tile Full Pages Плитка цілих сторінок diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 45312793f3..66942a71d3 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4130,6 +4130,13 @@ mark-style Japanese Kiểu Nhật Thumbnail View Dạng xem hình thu nhỏ Thumbnails: Hình thu nhỏ: Tile Ô + Tile All Vertically Xếp tất cả theo chiều dọc + Tile All Horizontally Xếp tất cả theo chiều ngang + 2-Up Layout Bố cục 2 + 3-Up Layout Bố cục 3 + 4-Up Layout Bố cục 4 + 6-Up Layout Bố cục 6 + Arrange Documents Sắp xếp tài liệu Tile Edge Color Màu cạnh ô Tile Edge Color… Màu cạnh ô… Tile Full Pages Ô toàn trang diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 0b3c38c9ca..a9f4e1d7e0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3594,6 +3594,13 @@ digits Malayalam 马拉雅拉姆数字 Threshold 阈值 Thumbnail View 缩略图视图 Tile 平铺 + Tile All Vertically 全部垂直平铺 + Tile All Horizontally 全部水平平铺 + 2-Up Layout 双联布局 + 3-Up Layout 三联布局 + 4-Up Layout 四联布局 + 6-Up Layout 六联布局 + Arrange Documents 排列文档 Tile Edge Color 拼贴边缘颜色 Tile Edge Color… 拼贴边缘颜色… Tile Full Pages 并排完整页面 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4c8b7f2d3e..d63d2a05fc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4853,6 +4853,13 @@ digits Malayalam 馬來亞拉姆數字 Thumbnail View 縮圖檢視 Thumbnails: 縮圖: Tile 並排顯示 + Tile All Vertically 全部垂直並排顯示 + Tile All Horizontally 全部水平並排顯示 + 2-Up Layout 雙聯版面 + 3-Up Layout 三聯版面 + 4-Up Layout 四聯版面 + 6-Up Layout 六聯版面 + Arrange Documents 排列文件 Tile Edge Color 拼貼邊緣顏色 Tile Edge Color… 拼貼邊緣顏色… Tile Full Pages 並排完整頁面 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4e2d80bb45..8cb75fdae9 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -80,6 +80,7 @@ pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; use slots::RECENT_FONT_IDS; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; pub(crate) use submenus::PATH_EFFECTS; +pub(crate) use tree::arrange_documents_items; pub use tree::{menu_tree, menu_tree_named}; pub use ui_commands::UI_COMMANDS; diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 7b7f7a6b21..4be65589c9 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -671,7 +671,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::doc_windows::new_window(app), "window.arrange.cascade" => crate::doc_windows::cascade(app), - "window.arrange.tile" => crate::canvas::tile(app), + "window.arrange.tile" => crate::canvas::tile(app, p), "window.arrange.floatInWindow" => crate::doc_windows::float_in_window(app, p), "window.arrange.floatAllInWindows" => crate::doc_windows::float_all(app), "window.arrange.consolidateAllWindows" if p.get("index").is_some_and(|i| !i.is_null()) => crate::doc_windows::dock(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 0d5775ffe9..5f76ce6efd 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -98,6 +98,8 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { } "window.collapseDock" => crate::panel_docking::dock_collapsed(&app.ui), "window.workspace" => p.get("name").and_then(Value::as_str) == Some(app.ui.workspace.as_str()), + // The Tile layout the panes show. + "window.arrange.tile" => app.ui.tiled && crate::canvas::TileLayout::from_params(p) == Ok(app.ui.tile_layout), "window.brightness" => p.get("brightness").and_then(Value::as_str).and_then(Brightness::parse) == Some(app.ui.brightness), "view.slices.lock" => app.session.slices_locked(), "object.slice.clipToArtboard" => app.session.active().is_some_and(|d| d.doc.slices_clip_to_artboard), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 4b86b4152d..2f93db6520 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -631,16 +631,16 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ("Window", { let mut window_items = vec![ c("New Window", "window.newWindow"), - sub( - "Arrange", - vec![ - c("Cascade", "window.arrange.cascade"), - c("Tile", "window.arrange.tile"), + sub("Arrange", { + let mut arrange = vec![c("Cascade", "window.arrange.cascade")]; + arrange.extend(tile_items()); + arrange.extend([ c("Float in Window", "window.arrange.floatInWindow"), c("Float All in Windows", "window.arrange.floatAllInWindows"), c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), - ], - ), + ]); + arrange + }), sub("Workspace", crate::workspaces::menu_items()), Sep, c("Control", "window.control"), @@ -755,6 +755,27 @@ pub(super) fn transform_items() -> Vec { ] } +/// Window → Arrange's Tile layouts, one `window.arrange.tile` `layout` each (also under the +/// application bar's Arrange Documents button). +fn tile_items() -> Vec { + vec![ + c("Tile", "window.arrange.tile"), + cp("Tile All Vertically", "window.arrange.tile", json!({"layout": "vertical"})), + cp("Tile All Horizontally", "window.arrange.tile", json!({"layout": "horizontal"})), + cp("2-Up Layout", "window.arrange.tile", json!({"layout": "2up"})), + cp("3-Up Layout", "window.arrange.tile", json!({"layout": "3up"})), + cp("4-Up Layout", "window.arrange.tile", json!({"layout": "4up"})), + cp("6-Up Layout", "window.arrange.tile", json!({"layout": "6up"})), + ] +} + +/// The application bar's Arrange Documents menu: Consolidate All Windows, then the Tile layouts. +pub(crate) fn arrange_documents_items() -> Vec { + let mut items = vec![c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), Sep]; + items.extend(tile_items()); + items +} + /// Object → Arrange (also in the canvas context menu). pub(super) fn arrange_items() -> Vec { vec![ diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 21b8795662..e54b366be3 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -769,7 +769,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + "{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}", ), ( "window.arrange.floatInWindow", diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 80a87b4563..97ffd12af0 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -598,6 +598,10 @@ pub struct UiState { /// Consolidate All Windows. Not saved: the reference app does not save windows with a document. #[serde(skip)] pub tiled: bool, + /// How Tile lays the panes out: in a grid, side by side, stacked, or 2-up to 6-up. Not saved, + /// as `tiled` is not. + #[serde(skip)] + pub tile_layout: crate::canvas::TileLayout, /// Window › Arrange › Float in Window, Float All in Windows and Cascade: the documents in /// floating windows of their own, out of the tab strip, until Consolidate All Windows. Not /// saved, as `tiled` is not. @@ -1176,6 +1180,7 @@ impl Default for UiState { palette_query: String::new(), screen_mode: 0, tiled: false, + tile_layout: crate::canvas::TileLayout::Grid, floating: Vec::new(), tab_document: None, draw_mode: 0, diff --git a/docs/mcp.md b/docs/mcp.md index fc03d070b6..550e2249dd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6606,14 +6606,20 @@ current, or the one before it when it was the last tab. In the desktop app a mod to ask whether to save it. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to -its pane; with fewer than two documents open it leaves the view and `tiled` as they are. It returns `{tiled, panes}`. -The current document's pane is the canvas, and a press in another pane makes its document the current one. -`window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one document under its tab -again and returns `{tiled: false}`. The arrangement is not saved. `ui.inspect` reports `tiled` and `panes` (each pane's -`document` index, `rect` and whether it is `active`); canvas coordinates map to the current document's pane -(`canvasRect`). -its pane; it returns `{tiled, panes}`. The current document's pane is the canvas, and a press in another pane makes its -document the current one. `window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document +its pane; with fewer than two documents open it leaves the view, `tiled` and the layout as they are. It returns +`{tiled, panes, layout}`. `window.arrange.tile {layout}` picks another layout, as the other Tile items of Window › +Arrange and of the application bar's Arrange Documents button do: `grid` (the default), `vertical` (Tile All +Vertically: side by side in one row), `horizontal` (Tile All Horizontally: stacked in one column), and `2up`, `3up`, +`4up` and `6up`, which show at most that many documents (2-Up and 3-Up side by side, 4-Up two by two, 6-Up three by +two) and leave the others under their tabs. Those layouts show the first documents in tab order, and the current +document takes the last pane when it is not among them, so a click on another tab brings that document into the last +pane. Any other `layout` is an error, and the view stays as it is. The set of layouts and how each one places the panes +are VectorCraft's own. The current document's pane is the canvas, and a press in another pane makes its document the +current one. `window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows, also first in Arrange +Documents) shows one document under its tab again and returns `{tiled: false}`. The arrangement is not saved. +`ui.inspect` reports `tiled`, `tileLayout` and `panes` (each pane's `document` index, `rect` and whether it is +`active`); canvas coordinates map to the current document's pane (`canvasRect`). +`window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document out of the tab strip into a floating window of its own, `window.arrange.floatAllInWindows` (Float All in Windows) does so for every tabbed document, and `window.arrange.cascade` (Cascade) floats every document and stacks the windows 30 pt apart from the upper left of the document area; each returns `{floating}`, the floating documents' indices. On the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a1f7c81b8..51d04da8c8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -724,6 +724,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Fade Region Outside Artboard:** Artboard Options' Global checkboxes Fade Region Outside Artboard and Update While Dragging ([user guide, Artboard options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) are application preferences (`fadeRegionOutsideArtboard`, `artboardUpdateWhileDragging`), both on by default. While the Artboard tool is active the canvas draws everything outside the artboards, the pasteboard and the art on it, with each color channel at 60% of its value (VectorCraft's own amount), or only outside the box around all the artboards when crossing artboards would leave more than 4,096 rectangles in view; with Update While Dragging off it draws as usual during an artboard move or resize. Presentation Mode, exports and print do not change. Regression tests: `canvas::tests` (`the_artboard_tool_fades_the_pasteboard`, `presentation_mode_draws_no_fade`, `the_fade_darkens_art_on_the_pasteboard_and_not_on_the_artboard`, `outside_rects_cover_the_bounds_minus_the_boards`, `outside_rects_of_a_row_of_boards_stay_few`, `the_fade_of_crossing_boards_stays_bounded`, `update_while_dragging_keeps_or_drops_the_fade_during_an_artboard_drag`, `the_pasteboard_fade_leaves_exports_unchanged`), `dialogs/tests.rs` (`artboard_options_global_checkboxes_set_the_preferences`, `artboard_options_error_leaves_the_global_preferences_unchanged`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. +- **Arrange Documents (G7):** the application bar's Arrange Documents button arranges the open documents in grid and tile layouts ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). Its menu, and Window › Arrange, have Consolidate All Windows, Tile (the grid), Tile All Vertically (side by side), Tile All Horizontally (stacked) and the 2-Up, 3-Up, 4-Up and 6-Up layouts, which show that many documents and leave the others under their tabs, the current one in the last pane (`window.arrange.tile {layout}`). The set of layouts and how each places the panes are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`. From 40e1a80d5cdfce1feb7a1c1a8d8c8ed49b40180f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:26:11 -0800 Subject: [PATCH 31/48] Window: a document that keeps its pane keeps its zoom when another closes Panes refit a view when its slot or its place in the layout changes, not when the number of panes changes. Closing the sixth document in 6-Up leaves the other five in their panes with their zoom and scroll; side by side and stacked, every pane changes size and each document fits its new pane. --- crates/ui-egui/src/canvas/panes.rs | 16 +++++++----- crates/ui-egui/src/canvas/panes/tests.rs | 33 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 6b8eea9440..703c6b46bd 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -322,16 +322,18 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); - // A window opened, closed, floated or docked changes the panes, and so does coming back to the - // panes from one window: each window fits its new pane. With as many panes as before, only a - // window that moved to another pane fits it, as when a tab brings its window into the last pane - // of a 2-up to 6-up layout: the others keep their zoom and scroll. Windows are compared by - // their slots, since a closed document shifts the indices of the documents after it. + // A window that moved to another pane fits it, and so does a window whose pane changed place or + // size because a window opened, closed, floated or docked, or because the panes came back from + // one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its + // window into the last pane of a 2-up to 6-up layout, or when 6-Up loses its sixth document. + // Windows are compared by their slots, since a closed document shifts the indices of the + // documents after it, and panes by their place in the layout. let before = std::mem::take(&mut app.canvas.panes.last_slots); let now: Vec> = shown.iter().map(|w| slot(app, *w)).collect(); - let same_panes = before.len() == now.len(); + let unit = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(1.0, 1.0)); + let (cells_before, cells_now) = (layout_cells(layout, before.len(), unit), layout_cells(layout, now.len(), unit)); for (i, (w, s)) in shown.iter().zip(&now).enumerate() { - if same_panes && s.is_some() && before.get(i) == Some(s) { + if s.is_some() && before.get(i) == Some(s) && cells_before.get(i) == cells_now.get(i) { continue; } if let Some(v) = crate::doc_windows::view_mut(app, *w) { diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 2ad0af3dc1..1fcbd7cc61 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -232,6 +232,39 @@ fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() { assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}"); } +/// 6-Up keeps its three columns and two rows with five documents: closing the sixth leaves the +/// others in their panes with the zoom they had. Side by side, closing one widens every pane, and +/// each document fits its new pane. +#[test] +fn closing_a_document_keeps_the_zoom_of_the_documents_whose_panes_stay() { + let mut app = app_with(6); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 2, 3, 4, 5]); + app.views[1].zoom *= 2.0; + let zoomed = app.views[1].zoom; + app.run("file.close", json!({"index": 5})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.views[1].zoom, zoomed, "the document that kept its pane keeps its zoom"); + + let mut app = app_with(3); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.views[1].zoom *= 2.0; + app.run("file.close", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1]); + let area = view_rects(&app, rects[1], ctx.pixels_per_point()).1; + let v = app.views[1]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its wider pane: {v:?}"); +} + #[test] fn tile_refuses_a_layout_it_does_not_have() { let mut app = app_with(3); From 02351b0105c30c98d9e6e1122b49abd9769cfb12 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:45:34 -0800 Subject: [PATCH 32/48] Window: a narrow application bar drops Arrange Documents before the search icon The search icon takes the first icon slot beside the workspace switcher, as before Arrange Documents was added; Arrange Documents shows only when a second slot fits. --- crates/ui-egui/src/canvas/panes/tests.rs | 26 +++++++++++++++++++++++- crates/ui-egui/src/chrome.rs | 14 ++++++------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 1fcbd7cc61..e3da1a6a60 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -341,7 +341,12 @@ fn the_tile_items_check_the_layout_the_panes_show() { /// One frame of the application bar with screen-reader nodes on → the nodes. fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { - let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 800.0)); + app_bar_frame_in(app, ctx, events, 1400.0) +} + +/// [`app_bar_frame`] on a window `width` points wide. +fn app_bar_frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, width: f32) -> Vec { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(width, 800.0)); let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui)); out.textures_delta.clear(); out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() @@ -395,6 +400,25 @@ fn the_arrange_documents_button_tiles_and_consolidates() { assert!(!app.ui.tiled); } +/// As the application bar narrows, Arrange Documents goes before the search icon. +#[test] +fn a_narrow_application_bar_keeps_search_before_arrange_documents() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut search_alone = false; + for width in (200..=1400).rev().step_by(4) { + app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands and tools").is_some()); + assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search icon"); + search_alone |= search && !arrange; + } + assert!(search_alone, "some width shows the search icon without Arrange Documents"); +} + #[test] fn tile_shows_a_pane_for_each_document_fitted_to_it() { let mut app = app_with(3); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 96b4d12965..989cebadc0 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -84,8 +84,8 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let menus_end = if app.services.native_menu.is_some() { ui.cursor().min.x } else { menus::menu_bar(app, ui) }; // The right-side group fills the space after the menus from the right; when it runs // short, Discord goes first (it is also under Help), then Explore tutorials (also - // Window › Learn), then the search icon (the palette stays under its shortcut), then - // Arrange Documents (also Window › Arrange), then the workspace switcher narrows. + // Window › Learn), then Arrange Documents (also Window › Arrange), then the search icon + // (the palette stays under its shortcut), then the workspace switcher narrows. let full = ui.max_rect(); let right_edge = if captions_right > 0.0 { full.right() - captions_right - 10.0 } else { full.right() }; let right = egui::Rect::from_min_max(egui::pos2(menus_end + 8.0, full.top()), egui::pos2(right_edge, full.bottom())); @@ -105,15 +105,15 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let ws = ui.painter().layout_no_wrap(ws_name, egui::FontId::proportional(12.0), t.text); let ws_w = (ws.size().x + 36.0).clamp(112.0, 190.0); let gap = ui.spacing().item_spacing.x; - // Arrange Documents, beside the switcher, then the search icon, as in PhotoCraft: each - // shown while a minimal switcher fits beside it. + // The search icon, as in PhotoCraft, then Arrange Documents between it and the switcher: + // each shown while a minimal switcher fits beside it. let icon = 28.0; - let arrange = switcher && room >= 64.0 + 8.0 + gap + icon; - let search = arrange && room >= 64.0 + 8.0 + 2.0 * (gap + icon); + let search = switcher && room >= 64.0 + 8.0 + gap + icon; + let arrange = search && room >= 64.0 + 8.0 + 2.0 * (gap + icon); let icons = f32::from(u8::from(arrange) + u8::from(search)); let ws_w = ws_w.min(room - 8.0 - icons * (gap + icon)).max(64.0); // Explore tutorials, beside the search icon, opens the Learn panel. - let learn = search && room >= ws_w + 8.0 + 3.0 * (gap + icon); + let learn = arrange && room >= ws_w + 8.0 + 3.0 * (gap + icon); let discord = learn && room >= ws_w + 8.0 + 3.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center))); let ui = &mut rui; From cf3eac7d6f1946aecf56bf182eb00f2ecd3a9154 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:49:33 -0800 Subject: [PATCH 33/48] Docs: one Hindi row in the localization table --- docs/localization-parity.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 6774685176..e392e4df32 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -31,8 +31,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | English | `en` | source, 100% | all | Latin | — | full | — | | Simplified Chinese (Mandarin) | `zh-hans` | 5,102 rows, 791 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | all (3,554 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (604 messages) | Latin | no | full | — (review) | -| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review, layout and web font | -| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | +| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | | Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | From c643f9f5e12ffd222d301d3b91173d491d768f5c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:16:03 -0800 Subject: [PATCH 34/48] Text Import Options: Character Set offers the other documented encodings The Character Set menu of Text Import Options now lists Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European beside Unicode and ANSI, and `file.place {text: {characterSet}}` takes "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" and "centralEuropean". Each set decodes with its WHATWG Encoding Standard decoder from encoding_rs, which the workspace already locks: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic with platform "mac"), and Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both platforms. A byte-order mark is read as ordinary bytes and a malformed sequence as U+FFFD. Unicode and ANSI read as before. An unknown character set is an error that lists the sets, and nothing is placed. A `text` option of the wrong type (`characterSet: 3`, `removeLineReturns: "yes"`) is now an error instead of the default. The dialog remembers the last set confirmed, and Show Import Options off places with it. --- Cargo.lock | 1 + crates/engine/Cargo.toml | 3 + crates/engine/src/cmd/place.rs | 2 +- crates/engine/src/cmd/place/text.rs | 163 +++++++++++++++++++--- crates/engine/src/tests/textimport.rs | 30 ++++ crates/engine/tests/text_import_fuzz.rs | 6 +- crates/ui-egui/src/dialogs/text_import.rs | 55 +++++++- crates/ui-egui/src/i18n/bg.tsv | 6 + crates/ui-egui/src/i18n/bs.tsv | 6 + crates/ui-egui/src/i18n/ca.tsv | 7 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fi.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tests.rs | 16 +++ crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + docs/control-protocol.md | 2 +- docs/file-format-parity.md | 2 +- docs/mcp.md | 11 +- docs/target-app-parity.md | 1 + 40 files changed, 427 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 81946466b5..1104b51217 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6672,6 +6672,7 @@ dependencies = [ "craft-proof", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "crc32fast", + "encoding_rs", "flate2", "hayro-jpeg2000", "heic-rs", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b46678804b..9e80c0ef73 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -56,6 +56,9 @@ chrono = { workspace = true } craft-xml = { workspace = true } # The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). cfb = "0.15" +# The Text Import Options character sets other than Unicode and ANSI (place/text.rs). Already in +# Cargo.lock (vectorcraft-eps), so this adds no new crate. +encoding_rs = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 250642285d..3daa26bd6e 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), diff --git a/crates/engine/src/cmd/place/text.rs b/crates/engine/src/cmd/place/text.rs index 7d8afc92d4..78261a8804 100644 --- a/crates/engine/src/cmd/place/text.rs +++ b/crates/engine/src/cmd/place/text.rs @@ -3,8 +3,8 @@ use serde_json::Value; -use super::super::utf16_order_without_mark; -use super::{Point, Rect, Result, bad, bool_or, fileio, shapes, str_param}; +use super::super::{text_param, utf16_order_without_mark}; +use super::{Point, Rect, Result, bad, fileio, shapes, switch_or}; /// Text files as `file.place` reports them (not a format `document.open` reads). pub(super) const FORMAT: fileio::Format = fileio::Format { @@ -22,13 +22,68 @@ pub(super) const FORMAT: fileio::Format = fileio::Format { /// document may give. pub(super) const MAX_TEXT: usize = 4 << 20; +/// A character set of Text Import Options (`text.characterSet`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum CharacterSet { + /// UTF-8, or UTF-16 with or without a byte-order mark ([`decode`]). + #[default] + Unicode, + /// The platform's 8-bit character set: Windows-1252, or Mac Roman on a Mac. + Ansi, + ShiftJis, + Gb2312, + ChineseBig5, + Cyrillic, + Gb18030, + Greek, + Turkish, + Baltic, + CentralEuropean, +} + +/// Each character set by its `text.characterSet` value. +const CHARACTER_SETS: [(&str, CharacterSet); 11] = [ + ("unicode", CharacterSet::Unicode), + ("ansi", CharacterSet::Ansi), + ("shiftJis", CharacterSet::ShiftJis), + ("gb2312", CharacterSet::Gb2312), + ("chineseBig5", CharacterSet::ChineseBig5), + ("cyrillic", CharacterSet::Cyrillic), + ("gb18030", CharacterSet::Gb18030), + ("greek", CharacterSet::Greek), + ("turkish", CharacterSet::Turkish), + ("baltic", CharacterSet::Baltic), + ("centralEuropean", CharacterSet::CentralEuropean), +]; + +impl CharacterSet { + /// The Encoding Standard decoder of a set other than Unicode and ANSI, for a file from a Mac + /// when `mac`: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic on a Mac), and + /// Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both + /// platforms. + fn encoding(self, mac: bool) -> Option<&'static encoding_rs::Encoding> { + Some(match self { + Self::Unicode | Self::Ansi => return None, + Self::ShiftJis => encoding_rs::SHIFT_JIS, + Self::Gb2312 => encoding_rs::GBK, + Self::ChineseBig5 => encoding_rs::BIG5, + Self::Cyrillic if mac => encoding_rs::X_MAC_CYRILLIC, + Self::Cyrillic => encoding_rs::WINDOWS_1251, + Self::Gb18030 => encoding_rs::GB18030, + Self::Greek => encoding_rs::WINDOWS_1253, + Self::Turkish => encoding_rs::WINDOWS_1254, + Self::Baltic => encoding_rs::WINDOWS_1257, + Self::CentralEuropean => encoding_rs::WINDOWS_1250, + }) + } +} + /// Text Import Options (`file.place`'s `text` param). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(super) struct TextOptions { - /// Decode as the platform's 8-bit character set (Windows-1252 or Mac Roman) instead of - /// Unicode. - ansi: bool, - /// The file comes from a Mac (its 8-bit character set is Mac Roman). + /// The character set the file's bytes are decoded as. + character_set: CharacterSet, + /// The file comes from a Mac (its ANSI set is Mac Roman, its Cyrillic set x-mac-cyrillic). mac: bool, /// Join the lines of each block of text (blank lines end paragraphs). remove_line_returns: bool, @@ -45,11 +100,13 @@ impl TextOptions { if !t.is_object() { return Err(bad(cmd, "text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?}")); } - let choice = |key: &str, values: [&str; 2]| match str_param(t, key) { - None => Ok(false), - Some(v) if v == values[0] => Ok(false), - Some(v) if v == values[1] => Ok(true), - Some(v) => Err(bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", values[0], values[1]))), + // The index of `text[key]` in `values`; 0 when it is omitted or null. + let choice = |key: &str, values: &[&str]| -> Result { + let Some(v) = text_param(t, key, cmd)? else { return Ok(0) }; + values.iter().position(|x| *x == v).ok_or_else(|| { + let (last, rest) = values.split_last().map_or(("", &[][..]), |(last, rest)| (*last, rest)); + bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", rest.join("\", \""), last)) + }) }; let spaces_to_tab = match t.get("replaceSpaces") { None | Some(Value::Null) => None, @@ -58,11 +115,12 @@ impl TextOptions { as usize, ), }; + let set = choice("characterSet", &CHARACTER_SETS.map(|(name, _)| name))?; Ok(Self { - ansi: choice("characterSet", ["unicode", "ansi"])?, - mac: choice("platform", ["windows", "mac"])?, - remove_line_returns: bool_or(t, "removeLineReturns", false), - remove_paragraph_returns: bool_or(t, "removeParagraphReturns", false), + character_set: CHARACTER_SETS.get(set).map_or(CharacterSet::Unicode, |(_, s)| *s), + mac: choice("platform", &["windows", "mac"])? == 1, + remove_line_returns: switch_or(t, "removeLineReturns", false, cmd)?, + remove_paragraph_returns: switch_or(t, "removeParagraphReturns", false, cmd)?, spaces_to_tab, }) } @@ -80,10 +138,15 @@ pub(super) fn import(bytes: &[u8], o: TextOptions, cmd: &str) -> Result /// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark, or without one when the /// file has an even length, reads as valid UTF-16 with no NUL character in the byte order /// [`utf16_order_without_mark`] gives; bytes that aren't UTF-8 are read as the platform's 8-bit -/// set), or the platform's 8-bit character set. +/// set), the platform's 8-bit character set, or another set's decoder +/// ([`CharacterSet::encoding`]), which reads a byte-order mark as ordinary bytes and a malformed +/// sequence as U+FFFD. fn decode(bytes: &[u8], o: TextOptions) -> String { + if let Some(encoding) = o.character_set.encoding(o.mac) { + return encoding.decode_without_bom_handling(bytes).0.into_owned(); + } let eight_bit = |b: &[u8]| -> String { b.iter().map(|&c| if o.mac { mac_roman(c) } else { windows_1252(c) }).collect() }; - if o.ansi { + if o.character_set == CharacterSet::Ansi { return eight_bit(bytes); } let utf16 = |rest: &[u8], le: bool| { @@ -278,22 +341,76 @@ mod tests { assert_eq!(decode(&[0xFF, 0xFE, b'h', 0, 0xE9, 0], unicode), "hé", "UTF-16 LE"); assert_eq!(decode(&[0xFE, 0xFF, 0, b'h', 0x20, 0xAC], unicode), "h€", "UTF-16 BE"); assert_eq!(decode(&[b'c', b'a', b'f', 0xE9, 0x80], unicode), "café€", "not UTF-8: Windows-1252"); - let ansi = TextOptions { ansi: true, ..TextOptions::default() }; + let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() }; assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é"); - let mac = TextOptions { ansi: true, mac: true, ..TextOptions::default() }; + let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() }; assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€"); } + /// The other character sets decode by their Encoding Standard decoders: the platform matters + /// for Cyrillic alone, a byte-order mark is read as ordinary bytes, and a malformed sequence + /// reads as U+FFFD. + #[test] + fn decodes_the_other_character_sets() { + let cases: [(CharacterSet, &[u8], &str); 9] = [ + (CharacterSet::ShiftJis, &[0x93, 0xFA, 0x96, 0x7B], "日本"), + (CharacterSet::Gb2312, &[0xD6, 0xD0, 0xCE, 0xC4], "中文"), + (CharacterSet::ChineseBig5, &[0xA4, 0xA4, 0xA4, 0xE5], "中文"), + (CharacterSet::Cyrillic, &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + (CharacterSet::Gb18030, &[0x95, 0x32, 0x82, 0x36], "\u{20000}"), + (CharacterSet::Greek, &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"), + (CharacterSet::Turkish, &[0xDD, 0x73, 0x74], "İst"), + (CharacterSet::Baltic, &[0x52, 0xEE, 0x67, 0x61], "Rīga"), + (CharacterSet::CentralEuropean, &[0xA3, 0xF3, 0x64, 0x9F], "Łódź"), + ]; + for (set, bytes, text) in cases { + let windows = TextOptions { character_set: set, ..TextOptions::default() }; + assert_eq!(decode(bytes, windows), text, "{set:?}"); + if set != CharacterSet::Cyrillic { + assert_eq!(decode(bytes, TextOptions { mac: true, ..windows }), text, "{set:?} from a Mac"); + } + } + let mac_cyrillic = TextOptions { character_set: CharacterSet::Cyrillic, mac: true, ..TextOptions::default() }; + assert_eq!(decode(&[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], mac_cyrillic), "Привет"); + let shift_jis = TextOptions { character_set: CharacterSet::ShiftJis, ..TextOptions::default() }; + assert_eq!(decode(&[0x82, 0x22], shift_jis), "\u{FFFD}\"", "a lead byte before ASCII"); + assert_eq!(decode(&[b'a', 0x82], shift_jis), "a\u{FFFD}", "a lead byte at the end"); + let central = TextOptions { character_set: CharacterSet::CentralEuropean, ..TextOptions::default() }; + assert_eq!(decode(&[0xEF, 0xBB, 0xBF, b'A'], central), "A", "a UTF-8 byte-order mark is read as windows-1250"); + assert_eq!(decode(&[0xFF, 0xFE, b'A', 0], shift_jis), "\u{FFFD}\u{FFFD}A\0", "a UTF-16 byte-order mark is read as Shift JIS"); + } + #[test] fn options_parse_and_reject_bad_values() { let p = serde_json::json!({"text": {"characterSet": "ansi", "platform": "mac", "removeLineReturns": true, "replaceSpaces": 4}}); let o = TextOptions::parse(&p, "file.place").unwrap(); - assert_eq!(o, TextOptions { ansi: true, mac: true, remove_line_returns: true, remove_paragraph_returns: false, spaces_to_tab: Some(4) }); + assert_eq!( + o, + TextOptions { + character_set: CharacterSet::Ansi, + mac: true, + remove_line_returns: true, + remove_paragraph_returns: false, + spaces_to_tab: Some(4) + } + ); + for (name, set) in CHARACTER_SETS { + let o = TextOptions::parse(&serde_json::json!({"text": {"characterSet": name}}), "file.place").unwrap(); + assert_eq!(o.character_set, set, "{name}"); + } assert_eq!(TextOptions::parse(&serde_json::json!({}), "file.place").unwrap(), TextOptions::default()); - for bad in - [serde_json::json!({"text": 3}), serde_json::json!({"text": {"platform": "amiga"}}), serde_json::json!({"text": {"replaceSpaces": 1}})] - { + for bad in [ + serde_json::json!({"text": 3}), + serde_json::json!({"text": {"platform": "amiga"}}), + serde_json::json!({"text": {"replaceSpaces": 1}}), + serde_json::json!({"text": {"characterSet": 3}}), + serde_json::json!({"text": {"platform": true}}), + serde_json::json!({"text": {"removeLineReturns": "yes"}}), + serde_json::json!({"text": {"removeParagraphReturns": 1}}), + ] { assert!(TextOptions::parse(&bad, "file.place").is_err(), "{bad}"); } + let null = serde_json::json!({"text": {"characterSet": null, "platform": null, "removeLineReturns": null}}); + assert_eq!(TextOptions::parse(&null, "file.place").unwrap(), TextOptions::default(), "null leaves the default"); } } diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index cc89a8261b..980682f57e 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -135,6 +135,36 @@ fn text_files_report_and_queue_with_their_options() { assert!(close(frame, Rect::new(50.0, 60.0, 130.0, 100.0)), "{frame:?}"); } +/// Text Import Options' other character sets place their text as area type, and an unknown +/// character set is refused with the list of sets and places nothing. +#[test] +fn text_files_place_in_the_other_character_sets() { + let mut s = session(); + let cases: [(&str, &str, &[u8], &str); 11] = [ + ("shiftJis", "windows", &[0x93, 0xFA, 0x96, 0x7B], "日本"), + ("gb2312", "windows", &[0xD6, 0xD0, 0xCE, 0xC4], "中文"), + ("chineseBig5", "mac", &[0xA4, 0xA4, 0xA4, 0xE5], "中文"), + ("cyrillic", "windows", &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + ("cyrillic", "mac", &[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + ("gb18030", "windows", &[0x95, 0x32, 0x82, 0x36], "\u{20000}"), + ("greek", "windows", &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"), + ("turkish", "mac", &[0xDD, 0x73, 0x74], "İst"), + ("baltic", "windows", &[0x52, 0xEE, 0x67, 0x61], "Rīga"), + ("centralEuropean", "windows", &[0xA3, 0xF3, 0x64, 0x9F, b'\r', b'\n', 0xA3], "Łódź\nŁ"), + ("shiftJis", "windows", &[0x82, 0x22], "\u{FFFD}\""), + ]; + for (set, platform, bytes, text) in cases { + let r = place_text(&mut s, bytes, json!({"text": {"characterSet": set, "platform": platform}})); + assert_eq!(placed(&s, &r).0, text, "{set} on {platform}"); + } + let undo = s.doc().unwrap().history.undo.len(); + let bad = json!({"name": "a.txt", "dataBase64": "YQ==", "text": {"characterSet": "latin9"}}); + let err = s.execute("file.place", &bad).unwrap_err().to_string(); + let list = r#""unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" or "centralEuropean""#; + assert!(err.contains(&format!("text.characterSet `latin9`: use {list}")), "{err}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing placed"); +} + /// An RTF file with a font table, a color table, a bold run, an italic run, a superscript and a /// centered, indented second paragraph. const LETTER_RTF: &str = concat!( diff --git a/crates/engine/tests/text_import_fuzz.rs b/crates/engine/tests/text_import_fuzz.rs index 1ea656a158..c8417b73fc 100644 --- a/crates/engine/tests/text_import_fuzz.rs +++ b/crates/engine/tests/text_import_fuzz.rs @@ -17,7 +17,9 @@ proptest! { fn any_bytes_place_as_text_without_panics( bytes in prop::collection::vec(prop_oneof![any::(), Just(b'\r'), Just(b'\n'), Just(b' ')], 0..400), bom in prop::sample::select(vec![&b""[..], b"\xEF\xBB\xBF", b"\xFF\xFE", b"\xFE\xFF"]), - ansi in any::(), + set in prop::sample::select(vec![ + "unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean", + ]), mac in any::(), lines in any::(), paras in any::(), @@ -31,7 +33,7 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let text = json!({ - "characterSet": if ansi { "ansi" } else { "unicode" }, + "characterSet": set, "platform": if mac { "mac" } else { "windows" }, "removeLineReturns": lines, "removeParagraphReturns": paras, diff --git a/crates/ui-egui/src/dialogs/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index 99128cc321..f0fe62b40d 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -3,7 +3,7 @@ //! places it as area type (`file.place` with `text`) and remembers the options: the next text file //! starts from them, and is placed with them when Show Import Options is off. //! -//! Fields: `platform` (`windows` | `mac`), `characterSet` (`unicode` | `ansi`), +//! Fields: `platform` (`windows` | `mac`), `characterSet` (one of [`CHARACTER_SETS`]), //! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off), `spaces` (how many //! spaces make a tab, 2–100), and `__params` (the `file.place` params naming the file). @@ -22,6 +22,21 @@ pub(super) const SPEC: DialogSpec = /// The label column of the Encoding rows. const LABEL: f32 = 104.0; +/// The Character Set choices: `file.place`'s `text.characterSet` value and the menu label. +const CHARACTER_SETS: [(&str, &str); 11] = [ + ("unicode", "Unicode"), + ("ansi", "ANSI"), + ("shiftJis", "Shift JIS"), + ("gb2312", "GB2312"), + ("chineseBig5", "Chinese Big 5"), + ("cyrillic", "Cyrillic"), + ("gb18030", "GB18030"), + ("greek", "Greek"), + ("turkish", "Turkish"), + ("baltic", "Baltic"), + ("centralEuropean", "Central European"), +]; + /// Is the file `p` names (`path` or `name`) a text file? pub fn is_text(p: &Value) -> bool { let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default(); @@ -41,7 +56,8 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value { "__params": params, }); let last = &app.ui.text_import; - for (k, wanted) in [("platform", ["windows", "mac"]), ("characterSet", ["unicode", "ansi"])] { + let sets = CHARACTER_SETS.map(|(value, _)| value); + for (k, wanted) in [("platform", &["windows", "mac"][..]), ("characterSet", &sets[..])] { if let Some(v) = last.get(k).and_then(Value::as_str).filter(|v| wanted.contains(v)) { fields[k] = json!(v); } @@ -68,7 +84,7 @@ pub fn last_options(app: &VectorcraftApp) -> Value { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::subheader(ui, tl!("Encoding")); form::choice(ui, d, "platform", tl!("Platform:"), (LABEL, 180.0), &[("windows", "Windows"), ("mac", "Mac")]); - form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &[("unicode", "Unicode"), ("ansi", "ANSI")]); + form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &CHARACTER_SETS); ui.add_space(10.0); widgets::subheader(ui, tl!("Line Breaks")); for (key, label) in @@ -166,6 +182,39 @@ mod tests { assert_eq!(st.history.undo.len(), 1); } + /// Every character set is a choice: one confirmed last comes back on the next text file and + /// decodes it, an unknown remembered value falls back to Unicode, and with Show Import Options + /// off the remembered set is the one the file is placed with. + #[test] + fn a_remembered_character_set_comes_back_and_places_the_file() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(&[0x93, 0xFA, 0x96, 0x7B])}); + app.ui.text_import = json!({"characterSet": "shiftJis", "platform": "windows"}); + app.run("file.place", file.clone()).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("shiftJis")); + assert!(frame(&mut app).contains("Shift JIS"), "the remembered set is shown"); + let r = super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let n = st.doc.node(vectorcraft_engine::doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + let NodeKind::Text(t) = &n.kind else { panic!("type") }; + assert_eq!(t.plain_text(), "日本"); + assert_eq!(last_options(&app)["characterSet"], "shiftJis", "remembered for Show Import Options off"); + app.ui.text_import = json!({"characterSet": "latin9"}); + app.run("file.place", file).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("unicode")); + let values: Vec<&str> = CHARACTER_SETS.iter().map(|(v, _)| *v).collect(); + let labels: Vec<&str> = CHARACTER_SETS.iter().map(|(_, l)| *l).collect(); + assert_eq!( + values, + ["unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean"] + ); + assert_eq!( + labels, + ["Unicode", "ANSI", "Shift JIS", "GB2312", "Chinese Big 5", "Cyrillic", "GB18030", "Greek", "Turkish", "Baltic", "Central European"] + ); + } + /// A text file dropped on a canvas is placed by the dialog's OK in the document it was dropped /// on, even when another document became active meanwhile. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..349779992f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -404,6 +404,12 @@ font-technology Variable Променливи Character Alignment Подравняване на знаците Character / Paragraph Знак / Абзац Character Rotation Въртене на знак + Chinese Big 5 Китайски Big 5 + Cyrillic Кирилица + Greek Гръцки + Turkish Турски + Baltic Балтийски + Central European Централноевропейски Character Set: Набор от знаци: Character Style Стил на знак Character Style Options Опции за стил на знак diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..1ac0184ff6 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3273,6 +3273,12 @@ antiAlias Sharp Oštro LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opcije izvoza teksta + Chinese Big 5 Kineski Big 5 + Cyrillic Ćirilica + Greek Grčki + Turkish Turski + Baltic Baltički + Central European Srednjoevropski Character Set: Skup znakova: Join the lines of each paragraph Spoji redove svakog pasusa Line Breaks Prelomi reda diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..9587278ed4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -677,6 +677,12 @@ antiAlias Sharp Nítid Character options Opcions de caràcter Paragraph options Opcions de paràgraf Character Rotation Rotació de caràcters + Chinese Big 5 Xinès Big 5 + Cyrillic Ciríl·lic + Greek Grec + Turkish Turc + Baltic Bàltic + Central European Centreeuropeu Character Set: Joc de caràcters: Character Style Estil de caràcter Character Style Options Opcions de l’estil de caràcter @@ -7946,3 +7952,4 @@ breakText Glyphs Glifs Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. Remove Fold Line Role Elimina el tipus de línia @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: utilitzeu "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..f4991a3561 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3364,6 +3364,12 @@ antiAlias Sharp Ostré LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Možnosti exportu textu + Chinese Big 5 Čínština Big 5 + Cyrillic Cyrilice + Greek Řečtina + Turkish Turečtina + Baltic Baltské jazyky + Central European Středoevropské jazyky Character Set: Znaková sada: Join the lines of each paragraph Spojit řádky každého odstavce Line Breaks Zalomení řádků diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..8e7f7d807b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5776,6 +5776,12 @@ antiAlias Sharp Skarp LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Indstillinger for teksteksport + Chinese Big 5 Kinesisk Big 5 + Cyrillic Kyrillisk + Greek Græsk + Turkish Tyrkisk + Baltic Baltisk + Central European Centraleuropæisk Character Set: Tegnsæt: Join the lines of each paragraph Forbind linjerne i hvert afsnit Line Breaks Linjeskift diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..486117b13f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -392,6 +392,12 @@ font-technology Variable Variabel Character Alignment Zeichenausrichtung Character / Paragraph Zeichen / Absatz Character Rotation Zeichendrehung + Chinese Big 5 Chinesisch Big 5 + Cyrillic Kyrillisch + Greek Griechisch + Turkish Türkisch + Baltic Baltisch + Central European Mitteleuropäisch Character Set: Zeichensatz: Character Style Zeichenformat Character Style Options Zeichenformatoptionen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..2768017599 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -390,6 +390,12 @@ font-technology Variable Μεταβλητές Character Alignment Στοίχιση χαρακτήρων Character / Paragraph Χαρακτήρας / Παράγραφος Character Rotation Περιστροφή χαρακτήρων + Chinese Big 5 Κινεζικά Big 5 + Cyrillic Κυριλλικά + Greek Ελληνικά + Turkish Τουρκικά + Baltic Βαλτικά + Central European Κεντρικής Ευρώπης Character Set: Σύνολο χαρακτήρων: Character Style Στυλ χαρακτήρων Character Style Options Επιλογές στυλ χαρακτήρων @@ -7920,3 +7926,4 @@ breakText Glyphs Γλύφοι Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. Remove Fold Line Role Αφαίρεση τύπου γραμμής @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: χρησιμοποιήστε "{_1}" ή "{_2}" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..bc05249b72 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -417,6 +417,12 @@ font-technology Variable Variables Character Alignment Alineación de caracteres Character / Paragraph Carácter / Párrafo Character Rotation Rotación de caracteres + Chinese Big 5 Chino Big 5 + Cyrillic Cirílico + Greek Griego + Turkish Turco + Baltic Báltico + Central European Centroeuropeo Character Set: Juego de caracteres: Character Style Estilo de carácter Character Style Options Opciones de estilo de carácter @@ -7907,3 +7913,4 @@ breakText Glyphs Glifos Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. Remove Fold Line Role Quitar tipo de línea @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: use "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..f7f4bfb090 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3308,6 +3308,12 @@ antiAlias Sharp Terävä LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Tekstin vientiasetukset + Chinese Big 5 Kiina Big 5 + Cyrillic Kyrillinen + Greek Kreikka + Turkish Turkki + Baltic Balttilainen + Central European Keskieurooppalainen Character Set: Merkistö: Join the lines of each paragraph Yhdistä kunkin kappaleen rivit Line Breaks Rivinvaihdot @@ -8003,3 +8009,4 @@ breakText Glyphs Merkit Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. Remove Fold Line Role Poista viivatyyppi @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: käytä arvoa "{_1}" tai "{_2}" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..eedcaebcd5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -418,6 +418,12 @@ font-technology Variable Variables Character Alignment Alignement des caractères Character / Paragraph Caractère / Paragraphe Character Rotation Rotation des caractères + Chinese Big 5 Chinois Big 5 + Cyrillic Cyrillique + Greek Grec + Turkish Turc + Baltic Balte + Central European Europe centrale Character Set: Jeu de caractères : Character Style Style de caractère Character Style Options Options de style de caractère diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..679cd2800d 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -532,6 +532,11 @@ Character Color અક્ષર રંગ Character Direction અક્ષર દિશા Character Rotation અક્ષર પરિભ્રમણ + Chinese Big 5 ચાઇનીઝ Big 5 + Cyrillic સિરિલિક + Greek ગ્રીક + Baltic બાલ્ટિક + Central European મધ્ય યુરોપિયન Character Set: અક્ષર સેટ: Character Style Options અક્ષર સ્ટાઇલ વિકલ્પો Character Styles અક્ષર સ્ટાઇલ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..70e64f6264 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -793,6 +793,11 @@ antiAlias Sharp शार्प Character Direction कैरेक्टर दिशा Character options कैरेक्टर ऑप्शन्स Character Rotation कैरेक्टर रोटेशन + Chinese Big 5 चीनी Big 5 + Cyrillic सिरिलिक + Greek ग्रीक + Baltic बाल्टिक + Central European मध्य यूरोपीय Character Set: कैरेक्टर सेट: Character Style कैरेक्टर स्टाइल Character Style Options कैरेक्टर स्टाइल ऑप्शन्स diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..95c1ea102c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -576,6 +576,12 @@ font-technology Variable Változó Character options Karakterbeállítások Paragraph options Bekezdésbeállítások Character Rotation Karakterforgatás + Chinese Big 5 Kínai Big 5 + Cyrillic Cirill + Greek Görög + Turkish Török + Baltic Balti + Central European Közép-európai Character Set: Karakterkészlet: Character Style Karakterstílus Character Style Options Karakterstílus beállításai diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..65ebee437b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3053,6 +3053,12 @@ antiAlias Sharp Tajam LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opsi ekspor teks + Chinese Big 5 Tionghoa Big 5 + Cyrillic Sirilik + Greek Yunani + Turkish Turki + Baltic Baltik + Central European Eropa Tengah Character Set: Set karakter: Join the lines of each paragraph Gabungkan baris setiap paragraf Line Breaks Pemisah baris diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..e06e410f2e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -417,6 +417,12 @@ font-technology Variable Variabili Character Alignment Allineamento caratteri Character / Paragraph Carattere / Paragrafo Character Rotation Rotazione caratteri + Chinese Big 5 Cinese Big 5 + Cyrillic Cirillico + Greek Greco + Turkish Turco + Baltic Baltico + Central European Centroeuropeo Character Set: Set di caratteri: Character Style Stile carattere Character Style Options Opzioni stile carattere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..1863e9b064 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1232,6 +1232,12 @@ antiAlias Sharp シャープ Channel チャンネル Character / Paragraph 文字/段落 Character Rotation 文字回転 + Chinese Big 5 中国語 Big 5 + Cyrillic キリル文字 + Greek ギリシャ語 + Turkish トルコ語 + Baltic バルト言語 + Central European 中央ヨーロッパ言語 Character Set: 文字セット: Character Style Options 文字スタイルオプション Check Links リンクを確認 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..feeebed197 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5025,6 +5025,11 @@ antiAlias Sharp მკვეთრი Encoding: კოდირება: Line Endings: სტრიქონის დაბოლოებები: Text Export Options ტექსტის ექსპორტის პარამეტრები + Chinese Big 5 ჩინური Big 5 + Cyrillic კირილიცა + Greek ბერძნული + Baltic ბალტიური + Central European ცენტრალურევროპული Character Set: სიმბოლოთა ნაკრები: Join the lines of each paragraph თითოეული აბზაცის სტრიქონების შეერთება Line Breaks სტრიქონის წყვეტები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..ee80c7d4fc 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1222,6 +1222,12 @@ antiAlias Sharp 날카롭게 Channel 채널 Character / Paragraph 문자 / 단락 Character Rotation 문자 회전 + Chinese Big 5 중국어 Big 5 + Cyrillic 키릴 자모 + Greek 그리스어 + Turkish 터키어 + Baltic 발트어 + Central European 중앙 유럽어 Character Set: 문자 집합: Character Style Options 문자 스타일 옵션 Check Links 링크 확인 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..c36fb37196 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3670,6 +3670,12 @@ antiAlias Sharp Scherp LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opties tekstexport + Chinese Big 5 Chinees Big 5 + Cyrillic Cyrillisch + Greek Grieks + Turkish Turks + Baltic Baltisch + Central European Centraal-Europees Character Set: Tekenset: Join the lines of each paragraph De regels van elke alinea samenvoegen Line Breaks Regeleinden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..62bb45d2ce 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3245,6 +3245,12 @@ antiAlias Sharp Ostre Encoding: Kodowanie: Line Endings: Znaki końca wiersza: Text Export Options Opcje eksportu tekstu + Chinese Big 5 Chiński Big 5 + Cyrillic Cyrylica + Greek Grecki + Turkish Turecki + Baltic Bałtycki + Central European Środkowoeuropejski Character Set: Zestaw znaków: Join the lines of each paragraph Połącz wiersze każdego akapitu Line Breaks Podziały wierszy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..66747c9dd5 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -386,6 +386,12 @@ antiAlias Sharp Nítido Character Alignment Alinhamento de Caracteres Character / Paragraph Caractere / Parágrafo Character Rotation Rotação de Caractere + Chinese Big 5 Chinês Big 5 + Cyrillic Cirílico + Greek Grego + Turkish Turco + Baltic Báltico + Central European Europa Central Character Set: Conjunto de Caracteres: Character Style Options Opções de Estilo de Caractere Character Styles Estilos de Caractere diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..b0096dae74 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -415,6 +415,12 @@ font-technology Variable Вариативные Character Alignment Выравнивание символов Character / Paragraph Символ / Абзац Character Rotation Поворот символов + Chinese Big 5 Китайская Big 5 + Cyrillic Кириллица + Greek Греческая + Turkish Турецкая + Baltic Балтийская + Central European Центральноевропейская Character Set: Набор символов: Character Style Стиль символа Character Style Options Параметры стиля символа diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..b3f2518306 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -406,6 +406,11 @@ font-technology Variable Variabla Character Alignment Teckenjustering Character / Paragraph Tecken / stycke Character Rotation Teckenrotation + Chinese Big 5 Kinesisk Big 5 + Cyrillic Kyrillisk + Greek Grekisk + Baltic Baltisk + Central European Centraleuropeisk Character Set: Teckenuppsättning: Character Style Teckenstil Character Style Options Alternativ för teckenstil diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index d21a146585..65aed727cb 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -515,6 +515,22 @@ fn monitor_profile_labels_are_in_complete_catalogs() { } } +/// Text Import Options' Character Set choices that name a script or a region (Shift JIS, GB2312 +/// and GB18030 are names of their own), and the error for an unknown character set. +#[test] +fn text_import_character_sets_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Chinese Big 5", "Cyrillic", "Greek", "Turkish", "Baltic", "Central European"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let unknown = r#"text.characterSet `x`: use "unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" or "centralEuropean""#; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, unknown), unknown, "{code}"); + } +} + /// The Control bar panel menu's items, its groups of options and the edges, and the label of the /// command that turns a group on or off. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..e19f7108d9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -400,6 +400,12 @@ font-technology Variable Değişken Character Alignment Karakter Hizalaması Character / Paragraph Karakter / Paragraf Character Rotation Karakter Rotasyonu + Chinese Big 5 Çince Big 5 + Cyrillic Kiril + Greek Yunanca + Turkish Türkçe + Baltic Baltık + Central European Orta Avrupa Character Set: Karakter Seti: Character Style Karakter Stili Character Style Options Karakter Stili Seçenekleri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..6154afe63a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -411,6 +411,12 @@ font-technology Variable Варіативні Character Alignment Вирівнювання символів Character / Paragraph Символ / Абзац Character Rotation Поворот символів + Chinese Big 5 Китайська Big 5 + Cyrillic Кирилиця + Greek Грецька + Turkish Турецька + Baltic Балтійська + Central European Центральноєвропейська Character Set: Набір символів: Character Style Стиль символу Character Style Options Параметри стилю символу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..9934010d12 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -490,6 +490,12 @@ font-technology Variable Biến thiên Character options Tùy chọn ký tự Paragraph options Tùy chọn đoạn văn Character Rotation Xoay ký tự + Chinese Big 5 Tiếng Trung Big 5 + Cyrillic Chữ Kirin + Greek Tiếng Hy Lạp + Turkish Tiếng Thổ Nhĩ Kỳ + Baltic Vùng Baltic + Central European Trung Âu Character Set: Bộ ký tự: Character Style Kiểu ký tự Character Style Options Tùy chọn kiểu ký tự @@ -7577,3 +7583,4 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: hãy dùng "{_1}" hoặc "{_2}" diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..6c65c68298 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -364,6 +364,12 @@ antiAlias Sharp 锐利 Character Alignment 字符对齐 Character / Paragraph 字符/段落 Character Rotation 字符旋转 + Chinese Big 5 繁体中文 Big 5 + Cyrillic 西里尔文 + Greek 希腊文 + Turkish 土耳其文 + Baltic 波罗的海文 + Central European 中欧文 Character Set: 字符集: Character Style 字符样式 Character Style Options 字符样式选项 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..90d51f28f1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -379,6 +379,12 @@ font-technology Variable 可變 Character / Paragraph 字元/段落 Character Alignment 字元對齊 Character Rotation 字元旋轉 + Chinese Big 5 繁體中文 Big 5 + Cyrillic 西里爾文 + Greek 希臘文 + Turkish 土耳其文 + Baltic 波羅的海文 + Central European 中歐文 Character Set: 字元集: Character Style 字元樣式 Character Style Options 字元樣式選項 diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df83c6eb04..5125dc0cb9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -723,7 +723,7 @@ folder, then opens the dialog searching it. The web shows a status line instead disabled there. Text Import Options: placing a `.txt` file through the app (`file.place` with a file and no `text` options, the Place -dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: `unicode`/`ansi`, +dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: a `text.characterSet` value, `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces`, `spaces`). `ui.dialog.confirm` places the file as area type with those options (`file.place {text: {…}}`). diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9c46a01f77..cdeb60cfd8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -308,7 +308,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | CorelDRAW `.cdr` | open | no | no | | -| Text `.txt` | place, export | place (Text Import Options) | yes | | +| Text `.txt` | place, export | place (Text Import Options) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | | Word `.doc` | place | place (area type with the same formatting as `.docx`, from the style sheet's styles and direct formatting; Word 97 and later) | no | `tests/textimport.rs`, `place/doc.rs`; fuzzed (`text_import_fuzz.rs`); pictures, headers, footers, notes, comments and text boxes are left out with a warning; encrypted and fast-saved documents are refused | diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..731944110e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8055,10 +8055,15 @@ the document; so does `object.expand`. ``` Placing a text file (`.txt`) sets it as area type: `file.place {path | name+dataBase64, text?: {characterSet?: -"unicode" | "ansi", platform?: "windows" | "mac", removeLineReturns?, removeParagraphReturns?, replaceSpaces?: n}}` +"unicode" | "ansi" | "shiftJis" | "gb2312" | "chineseBig5" | "cyrillic" | "gb18030" | "greek" | "turkish" | "baltic" | +"centralEuropean", platform?: "windows" | "mac", removeLineReturns?, removeParagraphReturns?, replaceSpaces?: n}}` (Text Import Options). Unicode reads UTF-8, or UTF-16 with a byte-order mark; ANSI reads Windows-1252 (Mac Roman on -`mac`). Unicode reads a file without a byte-order mark as UTF-16 by the rule `dataset.import` uses: at least half of -its two-byte units hold a NUL byte, in the byte order that reads a line break, or for a file with one line, big-endian +`mac`). The other sets use the WHATWG Encoding Standard's decoders: `shiftJis` Shift_JIS, `gb2312` GBK, `chineseBig5` +Big5, `cyrillic` windows-1251 (x-mac-cyrillic on `mac`), `gb18030` gb18030, and `greek`, `turkish`, `baltic` and +`centralEuropean` windows-1253, 1254, 1257 and 1250 on both platforms. They read a byte-order mark as ordinary bytes +and a malformed sequence as U+FFFD. An unknown set, or an option of the wrong type (`characterSet: 3`, +`removeLineReturns: "yes"`), is an error, and nothing is placed. Unicode reads a file without a byte-order mark as +UTF-16 by the rule `dataset.import` uses: at least half of its two-byte units hold a NUL byte, in the byte order that reads a line break, or for a file with one line, big-endian when more of its units start with a NUL byte than end with one, and little-endian otherwise. Any other file is read as UTF-8, else as the platform's 8-bit set: one with fewer NUL bytes, one with an odd length, one where both byte orders read a line break, and one that isn't valid UTF-16 in that order or holds a NUL character. `removeLineReturns` joins diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..47e1e77af8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1967,6 +1967,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The place cursor keeps an encrypted PDF, `.ai` or `.ait` file, at a letter page's size (VectorCraft's own size) and without a thumbnail, and a click or drag on it asks for its password, with the Place dialog's Show Import Options on or off; such a file was left out of the cursor before (`crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`). - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). + - Text Import Options' Character Set offers Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European beside Unicode and ANSI, the plain-text encodings [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/import-and-export-text.html) lists for placed text. `file.place {text: {characterSet}}` decodes each with its WHATWG Encoding Standard decoder. The mapping is VectorCraft's own: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic with `platform: "mac"`), and Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both platforms. A byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD, and the last set confirmed is remembered (`crates/engine/src/tests/textimport.rs`, `crates/ui-egui/src/dialogs/text_import.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root ``. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). From edecf9bf4103faa42cbaf75d8d04d2e4d5237803 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 04:39:54 -0800 Subject: [PATCH 35/48] Shape Builder: the status bar says why a click or drag built nothing A Shape Builder gesture that builds nothing now says why when it is released: "select paths or compound paths" when nothing usable is selected, "select all paths you want to merge" when the pointer is over a path or compound path outside the selection, and "no region under the pointer" otherwise. The message changes nothing in the document, the selection or the undo history, and the next gesture that builds something clears it. A gesture made while a large selection's map is being built gives its message once, when it is replayed. Tools get Action::Status, which the session passes to the status bar; the new message has a row in every complete-message catalog. --- crates/engine/src/tests/build.rs | 33 +++++++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/builder.rs | 64 ++++++++++++++-- crates/tools/src/builder/tests.rs | 111 ++++++++++++++++++++++++++-- crates/tools/src/input.rs | 4 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 15 ++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/target-app-parity.md | 1 + 31 files changed, 241 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index cf56247042..75c11d7d80 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -582,6 +582,39 @@ fn shape_builder_tool_drives_the_command() { assert_eq!(layer_children(&s), 1); } +/// A Shape Builder click that builds nothing puts the reason in the status bar and leaves the +/// document, its undo history and the selection as they were; a click that merges shows no status. +#[test] +fn shape_builder_click_that_builds_nothing_shows_why() { + use vectorcraft_tools::builder::{NO_REGION, SELECT_ALL_PATHS, SELECT_PATHS}; + let mut s = session(); + let (a, _) = two(&mut s); + let v = ViewInfo::default(); + s.select_tool("shapeBuilder", v).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| { + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap() + }; + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.revision, st.history.undo.len(), st.history.redo.len(), st.selection.objects.clone(), st.is_dirty()) + }; + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let before = state(&s); + assert_eq!(click(&mut s, 125.0, 50.0), vec![UiRequest::Status(SELECT_ALL_PATHS.into())]); + assert_eq!(click(&mut s, 400.0, 400.0), vec![UiRequest::Status(NO_REGION.into())]); + assert_eq!(state(&s), before, "nothing changed"); + s.execute("select.none", &json!({})).unwrap(); + let before = state(&s); + assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(SELECT_PATHS.into())]); + assert_eq!(state(&s), before, "nothing changed"); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(String::new())], "a click that merges clears the status"); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge"); + assert!(click(&mut s, 25.0, 50.0).is_empty(), "the next merge shows no status"); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge"); +} + /// A click of the Shape Builder merges over the map the tool built for the hover, as does the /// command over the same inputs with the same gap; another gap needs a map of its own. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 9250cf8030..542ee871d3 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1530,6 +1530,7 @@ impl Session { } Action::Dialog(k, p) => ui.push(UiRequest::Dialog(k, p)), Action::SwitchTool(t) => ui.push(UiRequest::SwitchTool(t)), + Action::Status(msg) => ui.push(UiRequest::Status(msg)), Action::Notify(what) => { let view = self.last_view; self.with_tool_cx(view, |t, cx| t.notify(cx, &what)); diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 51617935f5..18825cdfe5 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -211,8 +211,26 @@ pub struct ShapeBuilderTool { prepared: Option<Arc<PreparedMerge>>, /// A gesture made while the map of a large selection is being built on another thread. deferred: Option<Deferred>, + /// The button went down with nothing selected: the release says what to select. + empty_press: bool, + /// The last gesture put one of [`SHAPE_BUILDER_STATUS`] in the status bar: the next gesture that + /// builds something clears it. + diagnosed: bool, } +/// The status a Shape Builder gesture gives when the selection holds no path or compound path. +pub const SELECT_PATHS: &str = "Shape Builder: select paths or compound paths"; + +/// The status a Shape Builder gesture that touched nothing gives when it ends over a path or +/// compound path that is not selected. +pub const SELECT_ALL_PATHS: &str = "Shape Builder: select all paths you want to merge"; + +/// The status a Shape Builder gesture that touched nothing gives anywhere else. +pub const NO_REGION: &str = "Shape Builder: no region under the pointer"; + +/// The status messages the Shape Builder tool gives. +pub const SHAPE_BUILDER_STATUS: [&str; 3] = [SELECT_PATHS, SELECT_ALL_PATHS, NO_REGION]; + /// A Shape Builder gesture made while the map of the selection was being built on another /// thread: the map key and the inputs it was made over, its pointer events, which [`Tool::poll`] /// replays once the map is there, and whether the release has come. @@ -455,6 +473,26 @@ impl ShapeBuilderTool { } } + /// Why a gesture released at `p` that touched nothing built nothing: the selection gives no path + /// or compound path ([`SELECT_PATHS`]); the pointer is over a path or compound path that a click + /// can pick and that is neither selected nor inside a selected object ([`SELECT_ALL_PATHS`]); or + /// neither ([`NO_REGION`]). + fn nothing_built(&mut self, cx: &ToolContext, p: Point) -> Action { + self.diagnosed = true; + if self.cache.get(cx, self.opts.open_filled_as_closed).shapes.is_empty() { + return Action::Status(SELECT_PATHS.into()); + } + let unselected = vectorcraft_doc::hit::hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| { + let chain: Vec<NodeId> = h.ancestry.iter().copied().chain([h.leaf]).collect(); + let path = chain + .iter() + .filter_map(|id| cx.doc.node(*id)) + .any(|n| matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })); + path && !chain.iter().any(|id| cx.selection.contains(*id)) + }); + Action::Status(if unselected { SELECT_ALL_PATHS } else { NO_REGION }.into()) + } + /// The cursor swatch preview: the swatch before the current fill, the current fill (ringed) /// and the swatch after it, side by side above the pointer. fn swatch_chips(&self, cx: &ToolContext) -> Vec<Overlay> { @@ -479,7 +517,9 @@ impl Tool for ShapeBuilderTool { vec![] } PointerKind::Down => { - // While a merge is being computed, a press starts no gesture. + // While a merge is being computed, a press starts no gesture. With nothing + // selected, the release says what to select. + self.empty_press = cx.selection.is_empty() && !self.editing(); if cx.selection.is_empty() || self.editing() { return vec![]; } @@ -564,7 +604,7 @@ impl Tool for ShapeBuilderTool { let press = points.first().copied().filter(|s| marquee.is_none() && !self.far && s.distance(p) <= cx.tol(CLICK_TOL_PX)); let split = press.filter(|q| self.stroke_at(cx, *q, erase).is_some()); if std::mem::take(&mut self.touched).is_empty() && split.is_none() { - return vec![]; + return vec![self.nothing_built(cx, p)]; } self.stroke = None; let roots = sorted_roots(cx.doc, &cx.selection.objects); @@ -590,11 +630,17 @@ impl Tool for ShapeBuilderTool { if self.opts.swatches { params["pickColorFrom"] = json!("swatches"); } + // The gesture builds something: the reason the last one built nothing goes. + let mut acts: Vec<Action> = std::mem::take(&mut self.diagnosed).then(|| Action::Status(String::new())).into_iter().collect(); // A large selection's merge is computed on another thread; `poll` applies it. - if self.start_merge(cx, ¶ms) { - return vec![]; + if !self.start_merge(cx, ¶ms) { + acts.push(Action::Exec("shapeBuilder.merge".into(), params)); } - vec![Action::Exec("shapeBuilder.merge".into(), params)] + acts + } + PointerKind::Up if std::mem::take(&mut self.empty_press) => { + self.diagnosed = true; + vec![Action::Status(SELECT_PATHS.into())] } _ => vec![], } @@ -693,6 +739,7 @@ impl Tool for ShapeBuilderTool { /// Choosing another tool or another document applies the merge being computed first. fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> { + self.empty_press = false; self.finish_edit(cx) } @@ -735,9 +782,11 @@ impl Tool for ShapeBuilderTool { /// With Pick Color From Color Swatches, the Left and Right arrow keys pick the color swatch /// before or after the current fill. Escape during a drag cancels it: the release after it - /// merges and deletes nothing. + /// merges and deletes nothing, and Escape while a press with nothing selected is held keeps its + /// release from showing a status. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { - (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) || (self.dragging && key == ToolKey::Escape) + (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) + || ((self.dragging || self.empty_press) && key == ToolKey::Escape) } /// The arrows pick swatches only without modifiers; Shift, Alt and Cmd/Ctrl arrows keep their @@ -753,6 +802,7 @@ impl Tool for ShapeBuilderTool { } if key == ToolKey::Escape { self.dragging = false; + self.empty_press = false; self.points.clear(); self.touched = Touched::default(); // A gesture recorded while the map is being built is canceled with it. diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index a88c14308b..84e686ccee 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -471,6 +471,106 @@ fn shape_builder_hover_builds_a_small_map_at_once() { assert_eq!((t.cache.builds, t.cache.background), (1, 0)); } +fn status(msg: &str) -> Vec<Action> { + vec![Action::Status(msg.into())] +} + +/// A click or drag with nothing selected shows what to select when it is released, and Escape +/// during the press keeps the release quiet. +#[test] +fn shape_builder_with_nothing_selected_says_what_to_select() { + let (d, _, _) = two_rects(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS), "a click"); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 25.0, 50.0)).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 125.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_PATHS), "a drag"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)).is_empty(), "a release without a press"); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)).is_empty(), "a canceled press"); + assert!(!t.claims_key(&cx, ToolKey::Escape)); +} + +/// With A of the overlapping squares A and B selected, a click on the part of B outside A builds +/// nothing and says to select every path to merge; a click on empty canvas says there is no +/// region; a click inside A still merges A alone and clears that status, and the click after it +/// gives the merge alone. +#[test] +fn shape_builder_names_the_unselected_path_under_a_release_that_built_nothing() { + let (d, a, _) = two_rects(); + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_ALL_PATHS)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION)); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!( + matches!(acts.as_slice(), [Action::Status(m), Action::Exec(id, v)] if m.is_empty() && id == "shapeBuilder.merge" && v["ids"] == json!([a.0])), + "{acts:?}" + ); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!(matches!(acts.as_slice(), [Action::Exec(id, _)] if id == "shapeBuilder.merge"), "{acts:?}"); + // A locked or hidden B cannot be picked, so the release says there is no region. + for hide in [false, true] { + let (mut d, a, b) = two_rects(); + let n = d.node_mut(b).unwrap(); + if hide { + n.visible = false; + } else { + n.locked = true; + } + let mut s = Selection::default(); + s.set([a]); + let cx = crate::testutil::cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(NO_REGION), "hidden: {hide}"); + } +} + +/// A selection that holds no path or compound path says to select one. +#[test] +fn shape_builder_with_no_path_selected_says_to_select_paths() { + let (mut d, a, _) = two_rects(); + d.node_mut(a).unwrap().locked = true; + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS)); +} + +/// A gesture made while the map of a large selection is being built and released over nothing +/// gives its status once, when it is replayed. +#[test] +fn shape_builder_replayed_gesture_over_nothing_gives_its_status_once() { + let (d, s) = square_row(200); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, 15.0, 10.0)); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 450.0, 450.0)).is_empty()); + assert_eq!(t.cache.builds, 0, "the gesture did not wait for the map"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 450.0, 450.0)).is_empty(), "the gesture waits for the map"); + assert!(t.editing()); + assert_eq!(t.finish_edit(&cx), status(NO_REGION)); + assert!(t.finish_edit(&cx).is_empty() && !t.editing()); +} + #[test] fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let (d, a, b) = two_rects(); @@ -485,7 +585,7 @@ fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let Action::Exec(_, v) = &acts[0] else { panic!() }; assert_eq!(v["erase"], true); t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION), "the release edits nothing and says why"); } /// Squares A (0..100) and B (50..150 both ways), overlapping at a corner, selected. @@ -998,9 +1098,9 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, 0.5, 27.0)); let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; assert_eq!((&v["splitStroke"], &v["points"]), (&json!(true), &json!([[-1.0, 25.0]]))); - // A release farther away is a drag, which splits nothing. + // A release farther away is a drag, which splits nothing and says it touched no region. t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)), status(NO_REGION)); // So is a Straight Line drag that goes away and ends back near the press. t.set_option("selection", &json!("straightLine")); t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); @@ -1008,11 +1108,12 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, -0.5, 25.5)); assert!(!acts.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("splitStroke").is_some())), "{acts:?}"); t.set_option("selection", &json!("freeform")); - // A drag merges as before and sends no switch. + // A drag merges as before and sends no switch; it clears the status the drag before it gave. t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0)); t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 75.0)); let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 75.0)); - let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + let [Action::Status(m), Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(m.is_empty(), "{m}"); assert!(v.get("splitStroke").is_none(), "{v}"); } diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 5362147b97..629970b066 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -218,4 +218,8 @@ pub enum Action { SwitchTool(String), /// Call the tool's `notify` after the preceding actions ran (e.g. to pick up a created object). Notify(String), + /// Show this English message in the status bar (e.g. why a Shape Builder gesture built + /// nothing); an empty message clears the status bar. It changes nothing in the document and + /// records no undo step. + Status(String), } diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..2a70892ce6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6392,6 +6392,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg shadings of more than 4096 patches or triangles were left out els ombrejats de més de 4096 pedaços o triangles s’han omès @msg shadings whose functions are of an unknown type are filled with their middle colour els ombrejats les funcions dels quals són d’un tipus desconegut s’omplen amb el seu color central @msg Shape Builder: no region under the pointer Constructor de formes: no hi ha cap regió sota el punter +@msg Shape Builder: select all paths you want to merge Constructor de formes: selecciona tots els traçats que vulguis combinar @msg Shape Builder: select paths or compound paths Constructor de formes: selecciona traçats o traçats compostos @msg shortcut for `{k}` must be a string la drecera de `{k}` ha de ser una cadena @msg Show All Hidden Attributes: nothing is hidden Mostra tots els atributs ocults: no hi ha res d’ocult diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..bf55ba52ee 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4972,6 +4972,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg Saved {path} Uloženo: {path} @msg Select text or click into text with the Type tool to insert glyphs Glyfy vložíte, když vyberete text nebo do něj kliknete nástrojem Text @msg Shape Builder: no region under the pointer Tvorba tvarů: pod ukazatelem není žádná oblast +@msg Shape Builder: select all paths you want to merge Tvorba tvarů: vyberte všechny cesty, které chcete sloučit @msg Shape Builder: select paths or compound paths Tvorba tvarů: vyberte cesty nebo složené cesty @msg Show All Hidden Attributes: nothing is hidden Zobrazit všechny skryté atributy: nic není skryto @msg Split Into Grid: select paths large enough for the grid Rozdělit do mřížky: vyberte cesty dost velké pro mřížku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..06d6b5b42c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7181,6 +7181,7 @@ imageTrace Outline Kontur @msg Saved {path} Gemte {path} @msg Select text or click into text with the Type tool to insert glyphs Markér tekst, eller klik i tekst med tekstværktøjet, for at indsætte glyffer @msg Shape Builder: no region under the pointer Figurbygger: intet område under markøren +@msg Shape Builder: select all paths you want to merge Figurbygger: markér alle kurver, du vil flette @msg Shape Builder: select paths or compound paths Figurbygger: markér kurver eller sammensatte kurver @msg Show All Hidden Attributes: nothing is hidden Vis alle skjulte attributter: intet er skjult @msg Split Into Grid: select paths large enough for the grid Opdel i gitter: markér kurver, der er store nok til gitteret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..9e5a5a12a9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4570,6 +4570,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg Saved {path} {path} gespeichert @msg Select text or click into text with the Type tool to insert glyphs Wählen Sie Text aus oder klicken Sie mit dem Text-Werkzeug in einen Text, um Glyphen einzufügen @msg Shape Builder: no region under the pointer Formerstellung: kein Bereich unter dem Zeiger +@msg Shape Builder: select all paths you want to merge Formerstellung: Wählen Sie alle Pfade aus, die Sie zusammenfügen möchten @msg Shape Builder: select paths or compound paths Formerstellung: Wählen Sie Pfade oder zusammengesetzte Pfade aus @msg Show All Hidden Attributes: nothing is hidden Alle ausgeblendeten Attribute einblenden: Es ist nichts ausgeblendet @msg Split Into Grid: select paths large enough for the grid In Raster teilen: Wählen Sie Pfade aus, die groß genug für das Raster sind diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..7f0d2c21ca 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2667,6 +2667,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg Saved {path} Αποθηκεύτηκε το {path} @msg Select text or click into text with the Type tool to insert glyphs Επιλέξτε κείμενο ή κάντε κλικ μέσα σε κείμενο με το εργαλείο κειμένου για εισαγωγή γλύφων @msg Shape Builder: no region under the pointer Δημιουργία σχημάτων: δεν υπάρχει περιοχή κάτω από τον δείκτη +@msg Shape Builder: select all paths you want to merge Δημιουργία σχημάτων: επιλέξτε όλες τις διαδρομές που θέλετε να συγχωνεύσετε @msg Shape Builder: select paths or compound paths Δημιουργία σχημάτων: επιλέξτε διαδρομές ή σύνθετες διαδρομές @msg Show All Hidden Attributes: nothing is hidden Εμφάνιση όλων των κρυφών χαρακτηριστικών: δεν υπάρχουν κρυφά χαρακτηριστικά @msg Split Into Grid: select paths large enough for the grid Διαίρεση σε πλέγμα: επιλέξτε αρκετά μεγάλες διαδρομές για το πλέγμα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..d03ab51f1f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4676,6 +4676,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg Saved {path} Se guardó {path} @msg Select text or click into text with the Type tool to insert glyphs Selecciona texto o haz clic dentro del texto con la herramienta Texto para insertar glifos @msg Shape Builder: no region under the pointer Generador de formas: no hay ninguna región bajo el puntero +@msg Shape Builder: select all paths you want to merge Generador de formas: selecciona todos los trazados que quieras combinar @msg Shape Builder: select paths or compound paths Generador de formas: selecciona trazados o trazados compuestos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos los atributos ocultos: no hay nada oculto @msg Split Into Grid: select paths large enough for the grid Dividir en cuadrícula: selecciona trazados lo bastante grandes para la cuadrícula diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..1b04d476f6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4909,6 +4909,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Saved {path} Tallennettiin {path} @msg Select text or click into text with the Type tool to insert glyphs Valitse tekstiä tai napsauta tekstiin tekstityökalulla, niin voit lisätä merkkejä @msg Shape Builder: no region under the pointer Muodonmuodostin: osoittimen alla ei ole aluetta +@msg Shape Builder: select all paths you want to merge Muodonmuodostin: valitse kaikki polut, jotka haluat yhdistää @msg Shape Builder: select paths or compound paths Muodonmuodostin: valitse polkuja tai yhdistelmäpolkuja @msg Show All Hidden Attributes: nothing is hidden Näytä kaikki piilotetut attribuutit: mitään ei ole piilotettu @msg Split Into Grid: select paths large enough for the grid Jaa ruudukoksi: valitse ruudukolle riittävän suuret polut diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..a76032a6d2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4638,6 +4638,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg Saved {path} {path} enregistré @msg Select text or click into text with the Type tool to insert glyphs Sélectionnez du texte ou cliquez dans un texte avec l’outil Texte pour insérer des glyphes @msg Shape Builder: no region under the pointer Concepteur de forme : aucune zone sous le pointeur +@msg Shape Builder: select all paths you want to merge Concepteur de forme : sélectionnez tous les tracés à fusionner @msg Shape Builder: select paths or compound paths Concepteur de forme : sélectionnez des tracés ou des tracés transparents @msg Show All Hidden Attributes: nothing is hidden Afficher tous les attributs masqués : rien n’est masqué @msg Split Into Grid: select paths large enough for the grid Découper en grille : sélectionnez des tracés assez grands pour la grille diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..b5dd19aed6 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8221,6 +8221,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg shadings of more than 4096 patches or triangles were left out 4096 से अधिक पैच या त्रिकोणों के छायांकन को छोड़ दिया गया था @msg shadings whose functions are of an unknown type are filled with their middle colour छायांकन जिसका कार्य अज्ञात प्रकार के होते हैं, उनके मध्य रंग से भरे होते हैं @msg Shape Builder: no region under the pointer आकृति बिल्डर: सूचक के तहत कोई क्षेत्र नहीं +@msg Shape Builder: select all paths you want to merge आकृति बिल्डर: वे सभी पाथ सिलेक्ट करें जिन्हें आप मर्ज करना चाहते हैं @msg Shape Builder: select paths or compound paths आकृति बिल्डर: पाथ या मिश्रित पाथ सिलेक्ट करें @msg Shaper needs 1–64 source paths शेपर के लिए 1–64 स्रोत पाथ चाहिए @msg shortcut for `{k}` must be a string `{k}` के लिए शॉर्टकट एक स्ट्रिंग होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..a1eedeb72e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5904,6 +5904,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg shadings of more than 4096 patches or triangles were left out kimaradtak a 4096-nál több foltból vagy háromszögből álló árnyalások @msg shadings whose functions are of an unknown type are filled with their middle colour az ismeretlen típusú függvényt használó árnyalások a középső színükkel kitöltve jelennek meg @msg Shape Builder: no region under the pointer Alakzatépítő: a mutató alatt nincs terület +@msg Shape Builder: select all paths you want to merge Alakzatépítő: jelöld ki az összes egyesítendő útvonalat @msg Shape Builder: select paths or compound paths Alakzatépítő: jelölj ki útvonalakat vagy összetett útvonalakat @msg shortcut for `{k}` must be a string `{k}` billentyűparancsa csak szöveg lehet @msg Show All Hidden Attributes: nothing is hidden Összes rejtett attribútum megjelenítése: nincs rejtett elem diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..e5cb65be6f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4704,6 +4704,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Saved {path} Salvato {path} @msg Select text or click into text with the Type tool to insert glyphs Seleziona del testo o fai clic nel testo con lo strumento Testo per inserire glifi @msg Shape Builder: no region under the pointer Generatore forme: nessuna regione sotto il puntatore +@msg Shape Builder: select all paths you want to merge Generatore forme: seleziona tutti i tracciati da unire @msg Shape Builder: select paths or compound paths Generatore forme: seleziona tracciati o tracciati composti @msg Show All Hidden Attributes: nothing is hidden Mostra tutti gli attributi nascosti: non c'è nulla di nascosto @msg Split Into Grid: select paths large enough for the grid Dividi in griglia: seleziona tracciati abbastanza grandi per la griglia diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..2efb701c91 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4570,6 +4570,7 @@ swatch Bright Violet ビビッドバイオレット @msg Live Paint: select paths or compound paths ライブペイント: パスまたは複合パスを選択してください @msg Live Paint: these paths are too degenerate to paint ライブペイント: これらのパスは形状がつぶれすぎていてペイントできません @msg Shape Builder: no region under the pointer シェイプ形成ツール: ポインターの下に領域がありません +@msg Shape Builder: select all paths you want to merge シェイプ形成ツール: 結合するパスをすべて選択してください @msg Shape Builder: select paths or compound paths シェイプ形成ツール: パスまたは複合パスを選択してください @msg image data `{_1}` is missing 画像データ `{_1}` が見つかりません @msg no Live Paint edge near that point その位置の近くにライブペイントのエッジがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..840c2d9d55 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6392,6 +6392,7 @@ font-technology Variable ცვლადი @msg Saved {path} შენახულია: {path} @msg Select text or click into text with the Type tool to insert glyphs გლიფების ჩასასმელად მონიშნეთ ტექსტი ან ტექსტის ხელსაწყოთი დაწკაპეთ ტექსტში @msg Shape Builder: no region under the pointer ფიგურების კონსტრუქტორი: მაჩვენებლის ქვეშ არე არ არის +@msg Shape Builder: select all paths you want to merge ფიგურების კონსტრუქტორი: მონიშნეთ ყველა ტრაექტორია, რომლის გაერთიანებაც გსურთ @msg Shape Builder: select paths or compound paths ფიგურების კონსტრუქტორი: მონიშნეთ ტრაექტორიები ან შედგენილი ტრაექტორიები @msg Show All Hidden Attributes: nothing is hidden ყველა დამალული ატრიბუტის ჩვენება: დამალული არაფერია @msg Split Into Grid: select paths large enough for the grid ბადედ გაყოფა: მონიშნეთ ბადისთვის საკმარისად დიდი ტრაექტორიები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..1ff2189c69 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4497,6 +4497,7 @@ theme Appearance 외관 @msg Live Paint: select paths or compound paths 라이브 페인트: 패스 또는 컴파운드 패스를 선택하세요 @msg Live Paint: these paths are too degenerate to paint 라이브 페인트: 이 패스는 퇴화되어 칠할 수 없습니다 @msg Shape Builder: no region under the pointer 모양 빌더: 포인터 아래에 영역이 없습니다 +@msg Shape Builder: select all paths you want to merge 모양 빌더: 병합할 패스를 모두 선택하세요 @msg Shape Builder: select paths or compound paths 모양 빌더: 패스 또는 컴파운드 패스를 선택하세요 @msg image data `{_1}` is missing 이미지 데이터 `{_1}`이(가) 없습니다 @msg no Live Paint edge near that point 그 지점 근처에 라이브 페인트 가장자리가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..8d7a07ef4b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5076,6 +5076,7 @@ imageTrace Outline Contour @msg Saved {path} {path} opgeslagen @msg Select text or click into text with the Type tool to insert glyphs Selecteer tekst of klik met het tekstgereedschap in tekst om glyphs in te voegen @msg Shape Builder: no region under the pointer Vormbouwer: geen gebied onder de aanwijzer +@msg Shape Builder: select all paths you want to merge Vormbouwer: selecteer alle paden die je wilt samenvoegen @msg Shape Builder: select paths or compound paths Vormbouwer: selecteer paden of samengestelde paden @msg Show All Hidden Attributes: nothing is hidden Alle verborgen kenmerken tonen: er is niets verborgen @msg Split Into Grid: select paths large enough for the grid In raster verdelen: selecteer paden die groot genoeg zijn voor het raster diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..27a3e7a0e4 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4795,6 +4795,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Saved {path} Zapisano {path} @msg Select text or click into text with the Type tool to insert glyphs Zaznacz tekst lub kliknij w tekst narzędziem Tekst, aby wstawić glify @msg Shape Builder: no region under the pointer Kreator kształtów: brak obszaru pod wskaźnikiem +@msg Shape Builder: select all paths you want to merge Kreator kształtów: zaznacz wszystkie ścieżki, które chcesz scalić @msg Shape Builder: select paths or compound paths Kreator kształtów: zaznacz ścieżki lub ścieżki złożone @msg Show All Hidden Attributes: nothing is hidden Pokaż wszystkie ukryte atrybuty: nic nie jest ukryte @msg Split Into Grid: select paths large enough for the grid Podziel na siatkę: zaznacz ścieżki wystarczająco duże dla siatki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..b21daa38e2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3991,6 +3991,7 @@ axis Both Ambos @msg Saved {path} {path} salvo @msg Select text or click into text with the Type tool to insert glyphs Selecione texto ou clique em um texto com a ferramenta Texto para inserir glifos @msg Shape Builder: no region under the pointer Criador de formas: nenhuma região sob o ponteiro +@msg Shape Builder: select all paths you want to merge Criador de formas: selecione todos os traçados que deseja mesclar @msg Shape Builder: select paths or compound paths Criador de formas: selecione traçados ou traçados compostos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos os atributos ocultos: nada está oculto @msg Split Into Grid: select paths large enough for the grid Dividir em grade: selecione traçados grandes o bastante para a grade diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..7b03b0cb13 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4700,6 +4700,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg Saved {path} Сохранено: {path} @msg Select text or click into text with the Type tool to insert glyphs Выделите текст или щёлкните внутри текста инструментом «Текст», чтобы вставить глифы @msg Shape Builder: no region under the pointer Создание фигур: под указателем нет области +@msg Shape Builder: select all paths you want to merge Создание фигур: выделите все контуры, которые нужно объединить @msg Shape Builder: select paths or compound paths Создание фигур: выделите контуры или составные контуры @msg Show All Hidden Attributes: nothing is hidden Показать все скрытые атрибуты: ничего не скрыто @msg Split Into Grid: select paths large enough for the grid Разделение на сетку: выделите контуры, достаточно большие для сетки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..a30113b183 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4582,6 +4582,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg Saved {path} Sparade {path} @msg Select text or click into text with the Type tool to insert glyphs Markera text eller klicka i text med textverktyget för att infoga glyfer @msg Shape Builder: no region under the pointer Formbyggare: inget område under pekaren +@msg Shape Builder: select all paths you want to merge Formbyggare: markera alla banor du vill sammanfoga @msg Shape Builder: select paths or compound paths Formbyggare: markera banor eller sammansatta banor @msg Show All Hidden Attributes: nothing is hidden Visa alla dolda attribut: ingenting är dolt @msg Split Into Grid: select paths large enough for the grid Dela upp i rutnät: markera banor som är tillräckligt stora för rutnätet diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0daefad24a..99bac818f5 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -451,6 +451,21 @@ fn objects_on_path_detach_strings_are_in_complete_catalogs() { } } +/// The status messages the Shape Builder tool gives when a gesture builds nothing come from the +/// tools crate, which [`message_literals`] does not scan, so every complete catalog is checked for +/// them here. +#[test] +fn shape_builder_status_messages_are_in_complete_catalogs() { + use vectorcraft_tools::builder::SHAPE_BUILDER_STATUS; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for s in SHAPE_BUILDER_STATUS { + assert_ne!(message(lang, s), s, "{code}: {s}"); + } + } + assert_eq!(message(de(), SHAPE_BUILDER_STATUS[1]), "Formerstellung: Wählen Sie alle Pfade aus, die Sie zusammenfügen möchten"); +} + /// The Window › Brush Libraries menu, built from the built-in library table, names each library. #[test] fn built_in_brush_library_names_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..70e6670c99 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4413,6 +4413,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Saved {path} {path} kaydedildi @msg Select text or click into text with the Type tool to insert glyphs Glif eklemek için metni seçin veya Yazım aracıyla metne tıklayın @msg Shape Builder: no region under the pointer Şekil Oluşturucu: işaretçinin altında bölge yok +@msg Shape Builder: select all paths you want to merge Şekil Oluşturucu: birleştirmek istediğiniz tüm yolları seçin @msg Shape Builder: select paths or compound paths Şekil Oluşturucu: yolları veya bileşik yolları seçin @msg Show All Hidden Attributes: nothing is hidden Tüm Gizli Özellikleri Göster: hiçbir şey gizli değildir @msg Split Into Grid: select paths large enough for the grid Izgaraya Böl: ızgara için yeterince büyük yollar seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..0045f02543 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4688,6 +4688,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg Saved {path} Збережено: {path} @msg Select text or click into text with the Type tool to insert glyphs Виділіть текст або клацніть всередині тексту інструментом «Текст», щоб вставити гліфи @msg Shape Builder: no region under the pointer Створення фігур: під вказівником немає області +@msg Shape Builder: select all paths you want to merge Створення фігур: виділіть усі контури, які потрібно об’єднати @msg Shape Builder: select paths or compound paths Створення фігур: виділіть контури або складені контури @msg Show All Hidden Attributes: nothing is hidden Показати всі приховані атрибути: нічого не приховано @msg Split Into Grid: select paths large enough for the grid Поділ на сітку: виділіть контури, досить великі для сітки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..35c8793bbc 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5592,6 +5592,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg shadings of more than 4096 patches or triangles were left out các vùng tô có hơn 4096 mảnh hoặc tam giác đã bị bỏ qua @msg shadings whose functions are of an unknown type are filled with their middle colour các vùng tô có hàm loại không xác định được tô bằng màu giữa @msg Shape Builder: no region under the pointer Xây dựng hình dạng: không có vùng nào dưới con trỏ +@msg Shape Builder: select all paths you want to merge Xây dựng hình dạng: chọn tất cả đường dẫn bạn muốn hợp nhất @msg Shape Builder: select paths or compound paths Xây dựng hình dạng: chọn đường dẫn hoặc đường dẫn phức @msg shortcut for `{k}` must be a string phím tắt cho `{k}` phải là chuỗi @msg Show All Hidden Attributes: nothing is hidden Hiện tất cả thuộc tính ẩn: không có gì bị ẩn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..932d8a96a1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4284,6 +4284,7 @@ imageTrace Outline 轮廓 @msg Live Paint: select paths or compound paths 实时上色:请选择路径或复合路径 @msg Live Paint: these paths are too degenerate to paint 实时上色:这些路径过于退化,无法上色 @msg Shape Builder: no region under the pointer 形状生成器:指针下方没有区域 +@msg Shape Builder: select all paths you want to merge 形状生成器:请选择要合并的所有路径 @msg Shape Builder: select paths or compound paths 形状生成器:请选择路径或复合路径 @msg image data `{_1}` is missing 缺少图像数据 `{_1}` @msg no Live Paint edge near that point 该点附近没有实时上色边缘 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..24e3f3e4b2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1915,6 +1915,7 @@ file-filter Templates 範本 @msg Live Paint: select paths or compound paths 即時上色:請選取路徑或複合路徑 @msg Live Paint: these paths are too degenerate to paint 即時上色:這些路徑過度退化,無法上色 @msg Shape Builder: no region under the pointer 形狀建立:指標下方沒有區域 +@msg Shape Builder: select all paths you want to merge 形狀建立:請選取要合併的所有路徑 @msg Shape Builder: select paths or compound paths 形狀建立:請選取路徑或複合路徑 @msg image data `{_1}` is missing 找不到影像資料 `{_1}` @msg no Live Paint edge near that point 該點附近沒有即時上色邊緣 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..58b230f0cb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1295,6 +1295,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, OK in Shape Builder Tool Options gives an error for a highlight Color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. Regression test: `dialogs::shape_builder_options::tests::a_highlight_color_with_an_alpha_part_is_refused`. With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). + The Shape Builder works on the selected paths, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. As VectorCraft's own rule, a click or drag that builds nothing says why in the status bar when it is released: "Shape Builder: select paths or compound paths" when nothing is selected or the selection holds no unlocked, visible path; "Shape Builder: select all paths you want to merge" when the release is over a path or compound path that is not selected; and "Shape Builder: no region under the pointer" otherwise. The document, the selection and the undo history stay as they were, and the next gesture that builds something clears the message. Regression tests: `shape_builder_with_nothing_selected_says_what_to_select`, `shape_builder_names_the_unselected_path_under_a_release_that_built_nothing` and `shape_builder_replayed_gesture_over_nothing_gives_its_status_once` in `builder/tests.rs`, and `tests::build::shape_builder_click_that_builds_nothing_shows_why`. Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). From 24e528abcf9296cc147df6cf4116930423f7ff00 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 07:40:47 -0800 Subject: [PATCH 36/48] Type: Area Type Options First Baseline offers Em Box Height First Baseline gains Em Box Height (`text.areaOptions {firstBaseline: "emBoxHeight"}`, and the Area Type Options dropdown). The top of the first line's ideographic em box, the largest on a line of several sizes, touches the top of the type area inside the inset, in each row/column cell and in vertical type. It is the em box that Top-to-Top leading uses. Min is the least distance, as with the other kinds. Native files save it as `emBoxHeight`. The .ai reader reads editing-data kind 5 as Em Box Height and the writer writes it back; Legacy (6) and unknown kinds keep today's fallback. The dropdown's Ascent and x Height labels, and Fixed in Gujarati, get the catalog rows nine languages were missing, beside the new label in every catalog. Help page: https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-margins-to-text-and-adjust-the-first-baseline.html --- crates/doc/src/text/para_style.rs | 2 + crates/doc/src/text/tests.rs | 14 +++++++ crates/engine/src/cmd/typecmd.rs | 2 +- crates/engine/src/cmd/typecmd/area_tests.rs | 38 ++++++++++++++++++ crates/eps/src/ai_editing/tests.rs | 31 +++++++++++++++ crates/eps/src/ai_editing/writer/texts.rs | 1 + crates/eps/src/import/ate.rs | 12 +++--- crates/text/src/layout/breaking.rs | 1 + crates/text/src/tests/typo.rs | 44 ++++++++++++++++++++- crates/text/src/tests/vertical.rs | 26 ++++++++++++ crates/text/src/tests/warichu.rs | 2 +- crates/ui-egui/src/dialogs/command.rs | 39 +++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 3 ++ crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 4 ++ crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 3 ++ crates/ui-egui/src/i18n/ja.tsv | 3 ++ crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 3 ++ crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 15 +++++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 3 ++ crates/ui-egui/src/i18n/vi.tsv | 3 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 3 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 3 ++ docs/mcp.md | 17 ++++++++ docs/target-app-parity.md | 1 + 43 files changed, 281 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index 62c6b8dd33..17325d071c 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -631,6 +631,8 @@ pub enum FirstBaseline { XHeight, /// The first line's leading. Leading, + /// The top of the first line's ideographic em box touches the frame top. + EmBoxHeight, /// Exactly `first_baseline_min` below the top. Fixed, } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index a5230d5d86..2a7237eda5 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -554,6 +554,20 @@ fn text_flow_is_saved_only_when_by_rows() { assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"flow": "diagonal"})).is_err()); } +/// First Baseline Em Box Height saves as `emBoxHeight` with its minimum and reads back; files from +/// before it read their own first baseline as they did, Ascent when they have none. +#[test] +fn em_box_height_first_baseline_is_saved_and_read_back() { + let set = AreaOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: 9.0, ..AreaOptions::default() }; + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!((saved["firstBaseline"].as_str(), saved["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(9.0))); + assert_eq!(serde_json::from_value::<AreaOptions>(saved).unwrap(), set); + let old = serde_json::json!({"firstBaseline": "leading", "firstBaselineMin": 3.0}); + assert_eq!(serde_json::from_value::<AreaOptions>(old).unwrap().first_baseline, FirstBaseline::Leading); + assert_eq!(serde_json::from_value::<AreaOptions>(serde_json::json!({})).unwrap().first_baseline, FirstBaseline::Ascent); + assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"firstBaseline": "emBox"})).is_err()); +} + /// 120 × 40 area type at (40, 40), its text drawn at twice its size. fn area_type() -> TextObject { let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default()); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index c239cf040e..f50a2c7364 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index aa6b75032d..a8aecac1d1 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -2613,6 +2613,44 @@ fn area_options_columns_change_layout() { assert!(s.execute("text.areaOptions", &json!({"firstBaseline": "nope"})).is_err()); } +/// First Baseline Em Box Height: set, reported and undone like the other kinds, with Min as the +/// least distance; setting it again adds no undo step, and the refusal of an unknown kind lists it. +#[test] +fn area_options_set_the_em_box_height_first_baseline() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "word ".repeat(20), "area": {"width": 300, "height": 120}})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let first = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines[0].first_baseline, + _ => panic!("area type"), + }; + let ascent = first(&s); + let r = s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap(); + assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(0.0))); + let em_box = first(&s); + assert!(em_box > 0.0 && (em_box - ascent).abs() > 0.1, "{em_box} {ascent}"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no change, no undo step"); + // A Min nearer the top keeps the em box; one further down is the distance. + s.execute("text.areaOptions", &json!({"firstBaselineMin": em_box / 2.0})).unwrap(); + assert!((first(&s) - em_box).abs() < 1e-9); + let r = s.execute("text.areaOptions", &json!({"firstBaselineMin": 30})).unwrap(); + assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(30.0))); + assert!((first(&s) - 30.0).abs() < 1e-9); + for _ in 0..3 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent"); + assert!((first(&s) - ascent).abs() < 1e-9); + let e = s.execute("text.areaOptions", &json!({"firstBaseline": "emBox"})).unwrap_err().to_string(); + assert!(e.contains("emBoxHeight"), "{e}"); + assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent"); +} + /// `rowGutter` sets a gutter between rows of its own, the reply passes it back, and a gutter /// given alone is the rows' and the columns' again. #[test] diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index f8e39a4048..476a6b0356 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -5397,6 +5397,37 @@ fn an_empty_last_frame_keeps_the_style_of_the_last_paragraph() { assert_eq!(justify, [Justify::Left, Justify::Right]); } +/// Each First Baseline kind the text document holds, Em Box Height included, comes back with its +/// minimum, without a warning. +#[test] +fn every_first_baseline_kind_comes_back_with_its_minimum() { + use vectorcraft_doc::{FirstBaseline, TextKind, TextObject}; + for (kind, min) in [ + (FirstBaseline::Ascent, 0.0), + (FirstBaseline::CapHeight, 6.0), + (FirstBaseline::XHeight, 0.0), + (FirstBaseline::Leading, 4.0), + (FirstBaseline::EmBoxHeight, 0.0), + (FirstBaseline::EmBoxHeight, 18.5), + (FirstBaseline::Fixed, 40.0), + ] { + let mut d = Document::new(300.0, 200.0); + let layer = d.layers[0].id; + let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "Area", style(12.0, Color::BLACK)); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 20.0, 140.0, 160.0)) }; + area.xf = Affine::IDENTITY; + area.area.first_baseline = kind; + area.area.first_baseline_min = min; + let n = text_node(&mut d, area); + d.insert(Some(layer), usize::MAX, n).unwrap(); + let warnings = export_ai_editing(&d, &opts()).unwrap().warnings; + assert!(warnings.is_empty(), "{kind:?}: {warnings:?}"); + let back = read_back(&d); + let NodeKind::Text(t) = &back.layers[0].children().unwrap()[0].kind else { panic!("type") }; + assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (kind, min), "{kind:?}"); + } +} + /// A minimum first baseline with the Ascent first baseline is reported, and kept with the others. /// An end bracket of an open path that the reader would read as none is reported, and one further /// from the path's end comes back. diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 506d13d9fc..d3c2c2e493 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -1002,6 +1002,7 @@ impl TextDoc { FirstBaseline::CapHeight => Some(2), FirstBaseline::Leading => Some(3), FirstBaseline::XHeight => Some(4), + FirstBaseline::EmBoxHeight => Some(5), }; if let Some(k) = kind { data.push((10, dict(vec![(0, V::Int(k)), (1, real(o.first_baseline_min / scale))]))); diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 0c73b65092..160310dd4e 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -345,8 +345,9 @@ impl AreaFrame { 2 => F::CapHeight, 3 => F::Leading, 4 => F::XHeight, - // Em Box Height (5) and Legacy (6) have no first baseline of their own here: the - // first baseline stays as it was. + 5 => F::EmBoxHeight, + // Legacy (6) has no first baseline of its own here: the first baseline stays as it + // was. _ => return None, }; Some((kind, length(b.get("1")).unwrap_or(0.0))) @@ -2936,12 +2937,12 @@ mod tests { #[test] fn area_frame_first_baseline_kinds_and_minimum_are_read() { use vectorcraft_doc::FirstBaseline as F; - for (code, kind) in [(0, F::Fixed), (2, F::CapHeight), (3, F::Leading), (4, F::XHeight)] { + for (code, kind) in [(0, F::Fixed), (2, F::CapHeight), (3, F::Leading), (4, F::XHeight), (5, F::EmBoxHeight)] { let a = area_of(vec![area_frame(&format!("/10 << /0 {code} /1 30 >>"))], 0, 2.0); assert_eq!((a.first_baseline, a.first_baseline_min), (kind, 60.0), "code {code}"); } // A kind without its own first baseline here, or none known, leaves Ascent. - for code in ["1", "5", "6", "7", "-1", "2.5", "(x)"] { + for code in ["1", "6", "7", "-1", "2.5", "(x)"] { let a = area_of(vec![area_frame(&format!("/10 << /0 {code} /1 30 >>"))], 0, 1.0); assert_eq!((a.first_baseline, a.first_baseline_min), (F::Ascent, 0.0), "code {code}"); } @@ -2972,9 +2973,10 @@ mod tests { }; let placed = |options: &str| placed_in(&[options]); assert_eq!(placed("/10 << /0 2 /1 0 >>"), (false, vectorcraft_doc::FirstBaseline::CapHeight)); + assert_eq!(placed("/10 << /0 5 /1 0 >>"), (false, vectorcraft_doc::FirstBaseline::EmBoxHeight)); // Without one (Ascent), or with one that isn't read, the line goes where the file has it. assert_eq!(placed(""), (true, vectorcraft_doc::FirstBaseline::Fixed)); - assert_eq!(placed("/10 << /0 5 /1 0 >>"), (true, vectorcraft_doc::FirstBaseline::Fixed)); + assert_eq!(placed("/10 << /0 6 /1 0 >>"), (true, vectorcraft_doc::FirstBaseline::Fixed)); // Another frame of the thread keeping one doesn't count for the first. assert_eq!(placed_in(&["", "/10 << /0 2 /1 0 >>"]), (true, vectorcraft_doc::FirstBaseline::Fixed)); } diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index ef62fa2bcc..375bc343a2 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -47,6 +47,7 @@ impl Metrics { FirstBaseline::CapHeight => self.cap, FirstBaseline::XHeight => self.xh, FirstBaseline::Leading => self.lead, + FirstBaseline::EmBoxHeight => self.top, FirstBaseline::Fixed => 0.0, }; v.max(min) diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 351c698451..be0b36124f 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1329,6 +1329,40 @@ fn inset_and_first_baseline_options() { assert!(cap.lines[0].baseline < base.lines[0].baseline && cap.lines[0].baseline > 5.0); } +/// First Baseline Em Box Height: the top of the first line's ideographic em box (the one leading +/// measured from em box top to top uses) touches the top of the type area inside the inset. On a +/// line of several sizes the largest em box decides, and a Min further down sets the baseline. +#[test] +fn em_box_height_puts_the_first_lines_em_box_top_at_the_type_area_top() { + let frame = Rect::new(0.0, 0.0, 300.0, 300.0); + let em_box = |t: &TextObject, inset: f64, min: f64| { + let opts = LayoutOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: min, inset, ..Default::default() }; + layout_with(db(), t, &opts).lines[0].baseline + }; + // The em box top the EmBoxTop leading model sets a frame's first line at. + let em_top = |t: &TextObject| { + let mut t = t.clone(); + t.para.leading_model = vectorcraft_doc::LeadingModel::EmBoxTop; + layout(db(), &t).lines[0].baseline + }; + let t = area(COPY, style(12.0), frame, Justify::Left); + let top = em_top(&t); + assert!(top > 5.0 && top < 12.0, "{top}"); + let ascent = layout(db(), &t).lines[0].baseline; + assert!((top - ascent).abs() > 0.1, "not the ascent: {top} {ascent}"); + assert!((em_box(&t, 0.0, 0.0) - top).abs() < 1e-9); + assert!((em_box(&t, 10.0, 0.0) - (10.0 + top)).abs() < 1e-9, "measured from the inset"); + // A Min nearer the top than the em box changes nothing; one further down is the baseline. + assert!((em_box(&t, 10.0, top / 2.0) - (10.0 + top)).abs() < 1e-9); + assert!((em_box(&t, 10.0, 30.0) - 40.0).abs() < 1e-9); + // 10 pt and 20 pt on the first line: the 20 pt em box top is at the top. + let mut mixed = area("small Large", style(10.0), frame, Justify::Left); + mixed.runs = vec![run("small ", 10.0), run("Large", 20.0)]; + let large = area("Large", style(20.0), frame, Justify::Left); + assert!((em_box(&mixed, 0.0, 0.0) - em_box(&large, 0.0, 0.0)).abs() < 1e-9); + assert!((em_box(&large, 0.0, 0.0) - 2.0 * top * 10.0 / 12.0).abs() < 1e-6); +} + /// `LineInfo::first_baseline`: each line that starts a column has its baseline that far below the /// column's top inside the inset, for every first baseline option, with and without a minimum and /// an inset, in both leading models, and for lines of several sizes (each line in one size). @@ -1343,8 +1377,14 @@ fn lines_starting_a_column_sit_at_their_first_baseline() { let text: String = runs.iter().map(|r| r.text.as_str()).collect(); let mut other_sizes = 0; for model in [vectorcraft_doc::LeadingModel::RomanBaseline, vectorcraft_doc::LeadingModel::EmBoxTop] { - for first_baseline in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::Fixed] - { + for first_baseline in [ + FirstBaseline::Ascent, + FirstBaseline::CapHeight, + FirstBaseline::XHeight, + FirstBaseline::Leading, + FirstBaseline::EmBoxHeight, + FirstBaseline::Fixed, + ] { for (first_baseline_min, inset) in [(0.0, 0.0), (18.0, 6.0)] { for height in [100.0, 120.0, 140.0] { let mut t = area(&text, style(12.0), Rect::new(0.0, 0.0, 420.0, height), Justify::Left); diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index dd12804e91..40c8076b2d 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -142,6 +142,32 @@ fn fit_first_line_widens_a_vertical_frame_from_its_right_edge() { assert_eq!(layout(FontDb::global(), &t).lines.len(), 1); } +/// First Baseline Em Box Height in vertical area type: the first column's em box edge touches the +/// frame's right edge inside the inset, as far in as leading measured from em box top to top sets +/// it. +#[test] +fn em_box_height_sets_a_vertical_frames_first_column_at_its_em_box() { + use vectorcraft_doc::{FirstBaseline, LeadingModel}; + let first = |fb: FirstBaseline, model: LeadingModel| { + let mut t = vertical("§§"); + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, 100.0, 105.0).to_path(0.1)) }; + t.area.first_baseline = fb; + t.area.inset = 5.0; + t.para.leading_model = model; + let l = layout(FontDb::global(), &t); + (l.lines[0].baseline, l.lines[0].first_baseline) + }; + let (baseline, distance) = first(FirstBaseline::EmBoxHeight, LeadingModel::RomanBaseline); + let (em_top, _) = first(FirstBaseline::Ascent, LeadingModel::EmBoxTop); + let (ascent, ascent_distance) = first(FirstBaseline::Ascent, LeadingModel::RomanBaseline); + assert!((baseline - em_top).abs() < 1e-9, "{baseline} {em_top}"); + // Measured from the edge inside the inset, where a Fixed first baseline of 0 sits. + let (edge, _) = first(FirstBaseline::Fixed, LeadingModel::RomanBaseline); + assert!((baseline - distance - edge).abs() < 1e-9, "{baseline} {distance} {edge}"); + assert!((ascent - ascent_distance - edge).abs() < 1e-9, "{ascent} {ascent_distance} {edge}"); + assert!((baseline - ascent).abs() > 0.1, "not the ascent: {baseline} {ascent}"); +} + /// `baselines`: one per line that holds characters, along it for horizontal type and down the /// column's centre line for vertical type (where point type's anchor is); none on a path. #[test] diff --git a/crates/text/src/tests/warichu.rs b/crates/text/src/tests/warichu.rs index cbefb86bb5..7434e43db2 100644 --- a/crates/text/src/tests/warichu.rs +++ b/crates/text/src/tests/warichu.rs @@ -231,7 +231,7 @@ fn a_warichu_line_keeps_the_auto_leading_of_its_own_size() { #[test] fn the_first_baseline_measures_a_block_at_its_own_size() { use vectorcraft_doc::FirstBaseline; - for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading] { + for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::EmBoxHeight] { let baseline = |inside: CharStyle| { let mut t = area("", style(20.0), Rect::new(0.0, 0.0, 300.0, 300.0), Justify::Left); t.area.first_baseline = first; diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index f5215092e8..bd0484c4d1 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -208,8 +208,14 @@ const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "des const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText"), ("Block", "block")]; /// Area Type Options › First Baseline. -const FIRST_BASELINE: form::Choices = - &[("Ascent", "ascent"), ("Cap Height", "capHeight"), ("x Height", "xHeight"), ("Leading", "leading"), ("Fixed", "fixed")]; +const FIRST_BASELINE: form::Choices = &[ + ("Ascent", "ascent"), + ("Cap Height", "capHeight"), + ("x Height", "xHeight"), + ("Leading", "leading"), + ("Em Box Height", "emBoxHeight"), + ("Fixed", "fixed"), +]; /// Area Type Options › Align (vertical alignment of the lines in each row/column). const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("Bottom", "bottom"), ("Justify", "justify")]; @@ -271,6 +277,35 @@ mod tests { assert_eq!(t.area.vertical_align, VerticalAlign::Center); } + /// Area Type Options › First Baseline offers Em Box Height: OK sets it with its Min, and the + /// dialog opens again with it chosen. + #[test] + fn area_type_options_dialog_sets_the_em_box_height_first_baseline() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 20, "text": "Hello", "area": {"width": 200, "height": 200}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + // The labels `i18n::tests::first_baseline_choices_are_in_complete_catalogs` checks. + let labels: Vec<&str> = choices("text.areaOptions", "firstBaseline").unwrap().iter().map(|(l, _)| *l).collect(); + assert_eq!(labels, ["Ascent", "Cap Height", "x Height", "Leading", "Em Box Height", "Fixed"]); + crate::menus::invoke(&mut app, "text.areaOptions", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "ascent"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("firstBaseline".into(), json!("emBoxHeight")); + fields.insert("firstBaselineMin".into(), json!(4.0)); + crate::dialogs::confirm(&mut app).unwrap(); + let NodeKind::Text(t) = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (vectorcraft_doc::FirstBaseline::EmBoxHeight, 4.0)); + crate::menus::invoke(&mut app, "text.areaOptions", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "emBoxHeight"); + } + /// Area Type Options shows the gutter between rows beside the gutter, and OK sets a gutter /// between rows of its own. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..d739d4989a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5756,6 +5756,7 @@ lighting Light Светлина of от sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height Височина на x + Em Box Height Височина на квадратната касетка ▾ Default Actions ▾ Действия по подразбиране ⚠ {chord} was already used by {names} — it has been removed there. Внимание: Комбинацията {chord} вече се използва от {names} — премахната е там. @id file.close file.close diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..d65970cbfe 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5703,6 +5703,7 @@ imageTrace Outline Obris Ascent Uspon Cap Height Visina velikih slova x Height Visina malog slova x + Em Box Height Visina em okvira Justify Poravnaj obostrano First Baseline Prva osnovna linija Vertical Align Okomito poravnanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..ea2d9c4868 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5322,6 +5322,7 @@ digits Malayalam Malaiàlam Write Layers Escriu les capes Writes, moves or deletes files Escriu, mou o suprimeix fitxers x Height Alçada de la x + Em Box Height Alçada de la caixa em X11 (XWayland) X11 (XWayland) X11 (XWayland) When a Pen Is Attached X11 (XWayland) quan hi ha un llapis connectat X: X: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..d302279e32 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6026,6 +6026,7 @@ liquify-list-end {0}, {1} {0} a {1} Ascent Výška nad účařím Cap Height Výška verzálek x Height Výška x + Em Box Height Výška čtverčíku Justify Do bloku First Baseline První účaří Vertical Align Svislé zarovnání diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..7448ae0314 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -8097,6 +8097,7 @@ imageTrace Outline Kontur Ascent Overhøjde Cap Height Versalhøjde x Height x-højde + Em Box Height Em-felthøjde Justify Justér First Baseline Første basislinje Vertical Align Lodret justering diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..f551b9a339 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5366,6 +5366,9 @@ liquify-list-end {0}, {1} {0} und {1} Cap Height Versalhöhe x-Height x-Höhe ICF Box ICF-Rahmen + Ascent Oberlänge + x Height x-Höhe + Em Box Height Gevierthöhe Show Sample Muster einblenden Hide Sample Muster ausblenden Max Ascent/Descent Max. Höhe/Tiefe diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..e6a38c3f8b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5941,6 +5941,7 @@ digits Malayalam Μαλαγιάλαμ [VectorCraft Default] [Προεπιλογή VectorCraft] of από x Height Ύψος x + Em Box Height Ύψος τετραγώνου em ▾ Default Actions ▾ Προεπιλεγμένες ενέργειες ⚠ {chord} was already used by {names} — it has been removed there. Προσοχή: το {chord} χρησιμοποιούνταν ήδη από {names} — αφαιρέθηκε από εκεί. @msg give corners of the path: anchors between two straight sides ορίστε τις γωνίες της διαδρομής: σημεία αγκύρωσης μεταξύ δύο ευθύγραμμων πλευρών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..574c1c50d8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5964,6 +5964,7 @@ effect Regular Regular Ascent Ascendente Cap Height Altura de mayúsculas x Height Altura de la x + Em Box Height Altura del cuadro eme Justify Justificar First Baseline Primera línea de base Vertical Align Alineación vertical diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..4c674feafc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5942,6 +5942,7 @@ liquify-list-end {0}, {1} {0} ja {1} Ascent Nousu Cap Height Versaalikorkeus x Height x-korkeus + Em Box Height Em-laatikon korkeus Justify Tasaa molemmat reunat First Baseline Ensimmäinen perusviiva Vertical Align Pystytasaus diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..7b55bccb02 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6237,6 +6237,7 @@ lighting Light Lumière of sur sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height Hauteur d’x + Em Box Height Hauteur du cadratin ▾ Default Actions ▾ Scripts par défaut ⚠ {chord} was already used by {names} — it has been removed there. Attention : {chord} était déjà utilisé par {names} ; il en a été retiré. @id file.close Fermer diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..e6e32ac6ac 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4352,6 +4352,10 @@ tile {number} ટાઇલ {number} to થી x-Height x-ઊંચાઈ + Ascent એસેન્ટ + x Height x ઊંચાઈ + Fixed નિશ્ચિત + Em Box Height Em બૉક્સ ઊંચાઈ {count} of {total} artboards {total} માંથી {count} આર્ટબોર્ડ {effect} is already applied {effect} પહેલેથી લાગુ છે {file}, line {line} {file}, લાઇન {line} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..25f4a34397 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5738,6 +5738,7 @@ antiAlias Sharp शार्प Write Layers लेयर लिखें Writes, moves or deletes files फ़ाइलों को राइट्स, मूव या डिलीट करता है x Height x ऊँचाई + Em Box Height एम बॉक्स ऊँचाई X Position X स्थिति x-height x-ऊँचाई x-Height x-ऊँचाई diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..d13751bd22 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4943,6 +4943,7 @@ mark-style Japanese Japán Wrinkle Tool Gyűrés Write Layers Rétegek írása x Height x-magasság + Em Box Height Kvirtmező magassága X11 (XWayland) When a Pen Is Attached X11 (XWayland), ha toll csatlakozik If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Ha a grafikus tábla tolla nem rajzol, válassz egy X11 (XWayland) beállítást. X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..ac89a615bc 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5369,6 +5369,7 @@ imageTrace Outline Kontur Ascent Ascent Cap Height Tinggi kapital x Height Tinggi x + Em Box Height Tinggi Em Box Justify Ratakan First Baseline Baseline pertama Vertical Align Perataan vertikal diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..04f9889508 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1045,6 +1045,9 @@ font-technology Variable Variabili Cap Height Altezza maiuscole x-Height Altezza x ICF Box Riquadro ICF + Ascent Ascendente + x Height Altezza x + Em Box Height Altezza riquadro em Show Sample Mostra campione Hide Sample Nascondi campione Max Ascent/Descent Altezza/profondità max diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..c6757d1b02 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -49,6 +49,9 @@ font-technology Variable バリアブル Cap Height キャップハイト x-Height x ハイト ICF Box 平均字面 + Ascent アセント + x Height x ハイト + Em Box Height 仮想ボディの高さ Show Sample サンプルを表示 Hide Sample サンプルを隠す Max Ascent/Descent 最大アセント/ディセント diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..d6a613507c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7359,6 +7359,7 @@ font-technology Variable ცვლადი Ascent ზედა გამონაშვერი Cap Height მთავრული ასოს სიმაღლე x Height x-სიმაღლე + Em Box Height Em-ბლოკის სიმაღლე Justify ორმხრივი სწორება First Baseline პირველი საბაზისო ხაზი Vertical Align ვერტიკალური სწორება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..1635c51fbb 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -43,6 +43,9 @@ font-technology Variable 가변 Cap Height 대문자 높이 x-Height x 높이 ICF Box ICF 박스 + Ascent 어센트 + x Height x 높이 + Em Box Height 엠 박스 높이 Show Sample 샘플 표시 Hide Sample 샘플 숨기기 Max Ascent/Descent 최대 어센트/디센트 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..05a9d1b6ef 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7817,6 +7817,7 @@ imageTrace Outline Contour Ascent Stijghoogte Cap Height Kaphoogte x Height x-hoogte + Em Box Height Em-vakhoogte Justify Uitvullen First Baseline Eerste basislijn Vertical Align Verticaal uitlijnen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..873104f5fc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5874,6 +5874,7 @@ liquify-list-end {0}, {1} {0} i {1} Ascent Wydłużenie górne Cap Height Wysokość wersalików x Height Wysokość x + Em Box Height Wysokość ramki firetowej Justify Justuj First Baseline Pierwsza linia bazowa Vertical Align Wyrównanie pionowe diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..9be13009ce 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5953,6 +5953,7 @@ effect Regular Regular Ascent Ascensão Cap Height Altura das Maiúsculas x Height Altura do x + Em Box Height Altura da Caixa Eme Justify Justificar First Baseline Primeira Linha de Base Vertical Align Alinhamento Vertical diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..e32f6022e2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6995,6 +6995,7 @@ axis Y Axis Ось Y [Press Quality] [Типографское качество] of из x Height Высота строчных + Em Box Height Высота кегельной площадки ▾ Default Actions ▾ Стандартные действия ⚠ {chord} was already used by {names} — it has been removed there. ⚠ {chord} уже было назначено: {names}; там оно удалено. @plural {n} shortcut is assigned more than once|{n} shortcuts are assigned more than once {n} сочетание клавиш назначено несколько раз|{n} сочетания клавиш назначены несколько раз|{n} сочетаний клавиш назначены несколько раз diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..542e9222ec 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6158,6 +6158,7 @@ lighting Light Ljus of av sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height x-höjd + Em Box Height Em-rutans höjd ▾ Default Actions ▾ Standardåtgärder ⚠ {chord} was already used by {names} — it has been removed there. Obs! {chord} användes redan av {names} – det har tagits bort där. @id file.close Stäng diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0daefad24a..c465bb5328 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -434,6 +434,21 @@ fn font_height_reference_labels_are_in_complete_catalogs() { } } +/// Area Type Options › First Baseline's choices (the dropdown reads them in the "effect" context, +/// falling back to the plain row). +#[test] +fn first_baseline_choices_are_in_complete_catalogs() { + let mut missing = vec![]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Ascent", "Cap Height", "x Height", "Leading", "Em Box Height", "Fixed"] { + if lang.catalog().plain(label).is_none() && lang.catalog().contextual("effect", label).is_none() { + missing.push(format!("{} {label}", lang.code)); + } + } + } + assert!(missing.is_empty(), "{missing:?}"); +} + /// The Objects on Path Options section's Detach button, its undo step and the message for a /// Detach with no object chosen. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..b4beca188a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6014,6 +6014,7 @@ lighting Light Işık of arasında sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height x Yükseklik + Em Box Height Em Kutusu Yüksekliği ▾ Default Actions ▾ Varsayılan Eylemler ⚠ {chord} was already used by {names} — it has been removed there. ⚠ {chord} zaten {names} tarafından kullanılmıştı — oradan kaldırıldı. @id file.close Kapat diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..9692df3189 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1039,6 +1039,9 @@ font-technology Variable Варіативні Cap Height Висота великих літер x-Height Висота малих літер ICF Box Рамка ICF + Ascent Підйом + x Height Висота малих літер + Em Box Height Висота кегельного майданчика Show Sample Показати зразок Hide Sample Приховати зразок Max Ascent/Descent Макс. висота/глибина diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..08315ad0aa 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2014,6 +2014,9 @@ digits Hindi Hindi Cap Height Chiều cao chữ hoa x-Height Chiều cao chữ x ICF Box Ô ICF + Ascent Độ cao nét trên + x Height Chiều cao chữ x + Em Box Height Chiều cao ô em Show Sample Hiện mẫu Hide Sample Ẩn mẫu Max Ascent/Descent Độ cao/sâu tối đa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..a24077a4ac 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -976,6 +976,9 @@ antiAlias Sharp 锐利 Cap Height 大写字母高度 x-Height x 字高 ICF Box ICF 框 + Ascent 上缘 + x Height x 字高 + Em Box Height 全角字框高度 Show Sample 显示样本 Hide Sample 隐藏样本 Max Ascent/Descent 最大上升/下降 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..cbfa7bbb62 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1007,6 +1007,9 @@ font-technology Variable 可變 Cap Height 大寫字母高度 x-Height x 字高 ICF Box ICF 框 + Ascent 上緣 + x Height x 字高 + Em Box Height 全形字框高度 Show Sample 顯示樣本 Hide Sample 隱藏樣本 Max Ascent/Descent 最大上升/下降 diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..5fbc7b9d5c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9365,6 +9365,23 @@ Native files save it only when it is `rows`, so files from before it open by col {"name":"run_command","arguments":{"command":"text.areaOptions","params":{"rows":2,"columns":3,"flow":"rows"}}} ``` +### First baseline + +`text.areaOptions {firstBaseline: ascent|capHeight|xHeight|leading|emBoxHeight|fixed, firstBaselineMin?: pt}` (Area +Type Options › First Baseline and Min) sets how far below the top of the type area, inside the inset, the first line +of each row/column cell sits. `emBoxHeight` (Em Box Height) puts the top of the line's ideographic em box at that +top; on a line of several sizes the largest em box is used, and vertical type measures it from the frame's right +edge. The em box is the one leading measured from em box top to top uses: an ideograph's cell in the font's +vertical metrics, or 0.88 em above the baseline when the font has none (VectorCraft's own rule). With every kind but +`fixed`, `firstBaselineMin` is the least distance from the top to the first baseline; with `fixed` it is the +distance. Each threaded frame keeps its own setting. Native files and `.ai` files save `emBoxHeight` and open it again; other values are refused. The help +page describes the option: +https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-margins-to-text-and-adjust-the-first-baseline.html + +```json +{"name":"run_command","arguments":{"command":"text.areaOptions","params":{"firstBaseline":"emBoxHeight","firstBaselineMin":6}}} +``` + ## Fitting area type: Auto Size, Shrink Text to Fit, overflow `text.areaOptions` (and `text.create`'s `area`, `text.createInPath` in area mode) take a `fit`: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..1be6cfce83 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1468,6 +1468,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). Exports to PDF, EPS, SVG, EMF, WMF and the raster formats warn about the area type and type on a path that they draw without the text that doesn't fit, and give their ids, as Print and Print Preview do. On a shaped area type frame, Inset Spacing keeps text that far from the frame's edge, holes included, measured from the edge itself rather than along the line; the archived help treats the inset as the space an area type object leaves between its text and the path that bounds it (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=317>, <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=325>). A rectangular frame keeps its inset from each side as before, and a column's inner edges keep it once. An edge that two contours of the frame share lies inside the frame, so text runs across it with no inset on either side, and a negative text wrap offset does not shrink a wrap object beside such an edge. Tests: `layout::region::inset_on_a_shaped_frame_is_measured_from_its_sloped_edge`, `inset_keeps_text_clear_of_a_hole_s_sloped_edges`, `inset_applies_once_at_a_column_s_edge_and_at_the_frame_s_edge`, `inset_is_not_kept_beside_an_edge_two_contours_share`, `negative_wrap_offset_does_not_shrink_beside_an_edge_two_contours_share`. + Area Type Options › First Baseline offers Em Box Height (`text.areaOptions {firstBaseline: "emBoxHeight"}`), which the help page describes as using the font's em box height (<https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-margins-to-text-and-adjust-the-first-baseline.html>): the top of the first line's ideographic em box, the largest on a line of several sizes, touches the top of the type area inside the inset, in each row/column cell and in vertical type from the frame's right edge. The em box is the one Top-to-Top leading uses (VectorCraft's own measure: an ideograph's cell in the font's vertical metrics, else 0.88 em above the baseline), and Min is the least distance, as with the other kinds. Native files and `.ai` files save and open it; a `.ai` First Baseline kind VectorCraft does not read keeps today's fallback. Tests: `em_box_height_puts_the_first_lines_em_box_top_at_the_type_area_top`, `em_box_height_sets_a_vertical_frames_first_column_at_its_em_box`, `area_options_set_the_em_box_height_first_baseline`, `every_first_baseline_kind_comes_back_with_its_minimum`. An edit copies a thread's story only when it changes one of the thread's frames: with a story of 50,000 characters threaded through 8 frames with a style change at every word, moving another object took 7.8 ms and now takes 0.013 ms, and a frame of a drag took 7.2 ms and now takes 0.012 ms (release build, `threaded_story_edit_timing`). When a story flows through threaded area type, each frame is measured with the whole paragraphs of the story that it needs and a few more, not with the whole rest of the story, and it keeps the same text as before. A story of 1,500 one-line paragraphs (55,892 bytes) through 40 frames was laid out over 2,126,762 bytes of text while the frames were measured, and is now laid out over 21,035 (`thread::tests::many_frames_measure_about_the_text_they_take`). Area type with its lines aligned to the center, the bottom or justified vertically, and type on a path whose first paragraph is aligned Left, Justify Left, Justify All or Auto, are measured the same way: the same story through 40 area frames aligned to the center was laid out over 2,126,762 bytes and is now laid out over 21,035, through 40 paths aligned Left over 2,135,202 bytes and now over 20,583, and through 40 paths aligned Justify All over 2,135,202 bytes and now over 20,583 (same test). Shrink Text to Fit, Dynamic Text, Optical Margin Alignment and Roman Hanging Punctuation on a path, a path aligned to the center or the right, horizontal type on a path whose first paragraph is set right to left or with right-to-left text in the rest of the story, and a frame whose share ends in the story's last paragraph are still measured with the whole rest. A paragraph that continues from one threaded frame into the next has its first-line indent and bullet or number in the frame where it starts; in the next frame its first line starts where its wrapped lines start. In frames that are no longer threaded, copies of a frame and point type converted from one, the first paragraph has its indent and bullet or number again. From 4911e102b1870d038360ded256a701970731b547 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 07:54:26 -0800 Subject: [PATCH 37/48] Packaging Tools: Fold Preview folds the blank in 3D with the printed art on its panels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fold Preview (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's button) shows the document's blank folded about its largest panel, or the panel double-clicked. Creases and perforations fold 90° away from the printed side and partial cuts 90° toward it. Each panel samples a raster of the print, with the fold lines and non-printing layers left out, through its projective map, with a depth buffer; the back shows the board's inside color. The window has a Fold slider, seven view presets, orbit, zoom, pan and perspective, and its status line reports a joint that does not close and panels that pass through each other. - addon.packaging.fold returns each panel's frame, the hinges with their angle and gap, and the collisions. A closing hinge's gap is measured with every hinge folded all the way. - ui.foldPreview sets the window and rejects values of the wrong kind or out of range; saved settings out of range are brought into range. - The print renders off the UI thread where a worker exists and once per document revision. The fold and the view image are worked out again only when the document, the settings or the window's size change. --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/addons.rs | 1 + crates/engine/src/cmd/addons/packaging.rs | 3 + .../engine/src/cmd/addons/packaging/check.rs | 85 ++- .../engine/src/cmd/addons/packaging/fold.rs | 110 +++ .../src/cmd/addons/packaging/fold/tests.rs | 143 ++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/three-d/src/fold.rs | 35 +- crates/three-d/src/fold/pose.rs | 407 ++++++++++ crates/three-d/src/fold/raster.rs | 474 ++++++++++++ crates/three-d/src/fold/raster/tests.rs | 179 +++++ crates/three-d/src/fold/tests.rs | 319 ++++++++ crates/ui-egui/src/addons/packaging.rs | 14 +- .../ui-egui/src/addons/packaging/preview.rs | 702 ++++++++++++++++++ .../src/addons/packaging/preview/tests.rs | 489 ++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 10 + crates/ui-egui/src/i18n/bs.tsv | 10 + crates/ui-egui/src/i18n/ca.tsv | 10 + crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fi.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/gu.tsv | 10 + crates/ui-egui/src/i18n/hi.tsv | 10 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ka.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sv.tsv | 10 + crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panel_docking.rs | 1 + crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/state.rs | 6 + docs/mcp.md | 56 +- 50 files changed, 3285 insertions(+), 31 deletions(-) create mode 100644 crates/engine/src/cmd/addons/packaging/fold.rs create mode 100644 crates/engine/src/cmd/addons/packaging/fold/tests.rs create mode 100644 crates/three-d/src/fold/pose.rs create mode 100644 crates/three-d/src/fold/raster.rs create mode 100644 crates/three-d/src/fold/raster/tests.rs create mode 100644 crates/ui-egui/src/addons/packaging/preview.rs create mode 100644 crates/ui-egui/src/addons/packaging/preview/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index f658cccb58..3b0ae56576 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -136,6 +136,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..cd112ac48a 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -821,6 +821,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. +pub use addons::{fold_source, print_hidden}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 8c310878fd..1ab2d5d9fa 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -16,6 +16,7 @@ mod shapes; mod typetools; pub(crate) use image::{DecodedImages, refresh_color_masks}; +pub use packaging::{fold_source, print_hidden}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 6099386b98..9de16ca200 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -6,8 +6,10 @@ //! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. mod check; +mod fold; mod roles; +pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; use super::super::CommandSpec; @@ -15,6 +17,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec<CommandSpec> { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index da8f7f25dd..9507a17daa 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::PathData; -use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; +use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks}; use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; @@ -14,7 +14,7 @@ use crate::{Result, Session}; const CHECK: &str = "addon.packaging.check"; /// How far apart the ends of two lines may be and still be joined, in points. -const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); +pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); pub fn specs() -> Vec<CommandSpec> { vec![cmd!( @@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind { } } -fn check(s: &mut Session, p: &Value) -> Result<Value> { - let select = switch_or(p, "select", false, CHECK)?; - let tolerance = match length_given(p, "tolerance", CHECK)? { - None => TOLERANCE.1, - Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, - Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), - }; +/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or +/// `document`), the lines, and the ids of those on a non-printing layer. +pub(super) struct Lines { + pub scope: &'static str, + pub lines: Vec<FoldLine>, + pub non_printing: Vec<u64>, +} + +/// The tolerance `p` gives for `cmd`, or the default. +pub(super) fn tolerance(p: &Value, cmd: &str) -> Result<f64> { + match length_given(p, "tolerance", cmd)? { + None => Ok(TOLERANCE.1), + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t), + Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + } +} + +/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while +/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines +/// are left out in every scope, members of a selected group included. +pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result<Lines> { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, CHECK)?; + let roots = checked_ids_or_selection(s, p, cmd)?; let d = &s.doc()?.doc; - // Hidden lines are left out in every scope, members of a selected group included. let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>(); - let (scope, targets) = match (given, roots.is_empty()) { - (true, _) => ("ids", shown(role_targets(d, &roots, false).0)), - (false, false) => ("selection", shown(role_targets(d, &roots, false).0)), - (false, true) => ("document", shown_targets(d)), - }; + Ok(match (given, roots.is_empty()) { + (true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)), + (false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)), + (false, true) => document_lines(d), + }) +} + +/// Every shown fold line of `d`. +pub(super) fn document_lines(d: &Document) -> Lines { + lines_of(d, "document", shown_targets(d)) +} + +fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines { let table = RoleTable::of(d); let mut lines = vec![]; let mut non_printing = vec![]; @@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> { segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); lines.push(FoldLine { path, kind: kind(role), key: id.0 }); } - let (found, mut issues) = blanks(&lines, tolerance); - if !non_printing.is_empty() { - issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + Lines { scope, lines, non_printing } +} + +/// The blanks `lines` make and their issues, the non-printing one last. +pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec<Blank>, Vec<Issue>) { + let (found, mut issues) = blanks(&lines.lines, tolerance); + if !lines.non_printing.is_empty() { + issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None }); } - let ok = !issues.iter().any(|i| i.code.is_error()); - let rows: Vec<Value> = issues + (found, issues) +} + +/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with. +pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec<Value> { + issues .iter() .map(|i| { let mut row = json!({ @@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> { } row }) - .collect(); + .collect() +} + +fn check(s: &mut Session, p: &Value) -> Result<Value> { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = tolerance(p, CHECK)?; + let lines = lines(s, p, CHECK)?; + let scope = lines.scope; + let (found, issues) = found(&lines, tolerance); + let d = &s.doc()?.doc; + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows = issue_rows(&issues, scope); if select { let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); ids.sort_unstable_by_key(|id| id.0); diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs new file mode 100644 index 0000000000..068b2375c9 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -0,0 +1,110 @@ +//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by +//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the +//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::{Blank, Issue, fold, pick}; + +use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or}; +use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance}; +use super::roles::{RoleTable, can_carry}; +use crate::{Result, Session}; + +const FOLD: &str = "addon.packaging.fold"; + +pub fn specs() -> Vec<CommandSpec> { + vec![cmd!( + query "addon.packaging.fold", + "Fold", + [], + None, + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + has_doc, + fold_command + )] +} + +/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the +/// whole document): what the Fold Preview window folds. +pub fn fold_source(d: &Document) -> (Vec<Blank>, Vec<Issue>) { + found(&document_lines(d), TOLERANCE.1) +} + +/// The objects the print on a folded blank leaves out: the layers that do not print and, unless +/// `fold_lines`, every object with a line role. +pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec<NodeId> { + fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec<NodeId>) { + match &n.kind { + NodeKind::Layer { printable: false, .. } => out.push(n.id), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)), + _ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id), + _ => {} + } + } + let table = RoleTable::of(d); + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out)); + out +} + +fn fold_command(s: &mut Session, p: &Value) -> Result<Value> { + let tolerance = tolerance(p, FOLD)?; + let amount = number_or(p, "amount", 1.0, FOLD)?; + if !(0.0..=1.0).contains(&amount) { + return Err(bad(FOLD, "`amount` must be from 0 to 1")); + } + let base = match p.get("base") { + None | Some(Value::Null) => None, + Some(v) => { + let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?; + Some(vectorcraft_geom::Point::new(x, y)) + } + }; + let lines = lines(s, p, FOLD)?; + let (blanks, issues) = found(&lines, tolerance); + let ok = !issues.iter().any(|i| i.code.is_error()); + let picked = pick(&blanks, base); + if base.is_some() && picked.is_none() { + return Err(bad(FOLD, "`base` is in no panel")); + } + let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?))); + let Some((index, blank, f)) = folded else { + return Ok(json!({ + "ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [], + "issues": issue_rows(&issues, lines.scope), + })); + }; + let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]); + let panels: Vec<Value> = blank + .panels + .iter() + .zip(&f.panels) + .map(|(panel, placed)| { + json!({ + "outline": panel.outline.to_bezpath().to_svg(), + "frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t}, + "parent": placed.parent, + "depth": placed.depth, + }) + }) + .collect(); + let hinges: Vec<Value> = f + .hinges + .iter() + .map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap})) + .collect(); + Ok(json!({ + "ok": ok, + "blank": index, + "blanks": blanks.len(), + "base": f.base, + "panels": panels, + "hinges": hinges, + "collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::<Vec<_>>(), + "issues": issue_rows(&issues, lines.scope), + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/fold/tests.rs b/crates/engine/src/cmd/addons/packaging/fold/tests.rs new file mode 100644 index 0000000000..da7cd6a84e --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold/tests.rs @@ -0,0 +1,143 @@ +//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn fold(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.fold", &p).unwrap() +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec<u64>) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +fn near(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +#[test] +fn a_tray_folds_its_walls_up_round_the_base() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}"); + let panels = r["panels"].as_array().unwrap(); + assert_eq!(panels.len(), 5); + let base = r["base"].as_u64().unwrap() as usize; + let frame = &panels[base]["frame"]; + assert!( + near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]), + "{frame}" + ); + assert!(panels[base]["parent"].is_null()); + assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data"); + for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) { + assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}"); + // Each wall stands square to the base, its print facing out. + let z = vector(&p["frame"]["z"]); + assert!(z[2].abs() < 1e-9 && (z[0].hypot(z[1]) - 1.0).abs() < 1e-9, "wall {i}: {z:?}"); + } + let hinges = r["hinges"].as_array().unwrap(); + assert_eq!(hinges.len(), 4); + assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}"); + assert_eq!(r["collisions"], json!([])); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step"); + + // Flat, every frame is the flat blank's own. + let r = fold(&mut s, json!({ "amount": 0 })); + for p in r["panels"].as_array().unwrap() { + assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}"); + } +} + +#[test] +fn the_base_is_the_panel_under_a_point() { + let mut s = session(); + tray(&mut s); + // The left wall: x 100 to 140, y 140 to 240. + let r = fold(&mut s, json!({ "base": [120, 190] })); + let base = r["base"].as_u64().unwrap() as usize; + let panels = r["panels"].as_array().unwrap(); + assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0])); + // The tray's base is now a child of the wall, and the other walls its children. + let depths: Vec<u64> = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect(); + let mut sorted = depths.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}"); + let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string(); + assert!(e.contains("`base` is in no panel"), "{e}"); +} + +#[test] +fn bad_values_are_refused() { + let mut s = session(); + tray(&mut s); + for (p, want) in [ + (json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"), + (json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"), + (json!({ "amount": "1" }), "`amount` must be a number"), + (json!({ "base": [1] }), "`base` must be a point"), + (json!({ "base": "middle" }), "`base` must be a point"), + (json!({ "tolerance": 50 }), "`tolerance` must be from"), + ] { + let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } +} + +#[test] +fn without_a_blank_nothing_is_folded_and_the_issues_say_why() { + let mut s = session(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}"); + assert_eq!(r["panels"], json!([])); + assert_eq!(r["issues"][0]["code"], "noCut"); +} + +#[test] +fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let art = path(&mut s, "M150 150 L200 150 L200 200 Z"); + let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap(); + let d = &s.doc().unwrap().doc; + let hidden: Vec<u64> = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect(); + for id in creases.iter().chain([&outline, ¬es]) { + assert!(hidden.contains(id), "{id} in {hidden:?}"); + } + assert!(!hidden.contains(&art)); + let shown: Vec<u64> = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect(); + assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out"); + let (blanks, issues) = cmd::fold_source(d); + assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5)); + assert!(issues.is_empty(), "{issues:?}"); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 1338bb5776..d11fc6ea00 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -41,6 +41,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.image.removeBackground", "addon.image.removeColorMask", "addon.packaging.check", + "addon.packaging.fold", "addon.packaging.roles", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 2dbff773f9..1bfb46f93b 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -34,6 +34,18 @@ pub enum LineKind { Perforation, } +impl LineKind { + /// The angle (degrees) a line of this kind folds at: 90 for a Crease or a Perforation, -90 for + /// a Partial Cut. A positive angle folds away from the printed side; none for a Cut. + pub fn fold_angle(self) -> Option<f64> { + match self { + LineKind::Cut => None, + LineKind::Crease | LineKind::Perforation => Some(90.0), + LineKind::PartialCut => Some(-90.0), + } + } +} + /// A fold line: the path (document coordinates), its kind, and a key the issues name it by. #[derive(Clone, Debug)] pub struct FoldLine { @@ -57,10 +69,18 @@ pub struct Panel { pub area: f64, } +impl Panel { + /// A point inside the panel, or the middle of its bounds for one too thin to find one in. + pub fn point_inside(&self) -> Option<Point> { + point_in(&self.outline) + } +} + /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. +/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is +/// ([`LineKind::fold_angle`]). #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, @@ -69,6 +89,7 @@ pub struct Hinge { pub to: Point, pub keys: Vec<u64>, pub straight: bool, + pub angle: f64, } /// What can be wrong with fold lines, in the order [`blanks`] lists them. @@ -1276,7 +1297,9 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let (p0, p1) = group.iter().filter_map(|p| chord(p)).max_by(|x, y| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let ((p0, p1), longest) = + group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1308,7 +1331,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1426,7 +1449,7 @@ impl Context<'_> { /// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of /// the larger tie, and the tie goes to the one whose inside point is highest on the page, then /// leftmost. -fn base_panel(panels: &[Panel]) -> Option<usize> { +pub fn base_panel(panels: &[Panel]) -> Option<usize> { let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); if !top.is_finite() { return None; @@ -1440,5 +1463,9 @@ fn base_panel(panels: &[Panel]) -> Option<usize> { .map(|(i, _)| i) } +mod pose; +pub mod raster; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs new file mode 100644 index 0000000000..650ab54291 --- /dev/null +++ b/crates/three-d/src/fold/pose.rs @@ -0,0 +1,407 @@ +//! A blank folded into its 3D shape ([`fold`]). +//! +//! The flat blank lies at z = 0 with document x to the right and document y flipped so y points up; +//! the printed side faces +z. The base panel stays in place. The other panels are reached from it +//! through a breadth-first tree of hinges, each panel's hinges taken in the order of their ends (y, +//! then x, the first end first), so the tree does not depend on the order the lines were drawn in. A child +//! panel turns about its hinge by the hinge's angle times the fold amount; a positive angle moves it +//! toward -z, away from the printed side, whichever way the hinge was drawn. Hinges outside the tree +//! close a loop of panels: [`FoldedHinge::gap`] says how far apart their two placements end up when +//! the blank is folded all the way. + +use std::collections::{HashSet, VecDeque}; + +use vectorcraft_geom::{PathData, PathEl, Point, Shape as _}; + +use super::{Blank, base_panel, point_in}; + +/// Most points a panel's outline is flattened to; a panel with more is left out of the collision +/// test and the preview. +pub const MAX_POLYGON_POINTS: usize = 1 << 16; + +type V3 = [f64; 3]; + +fn sub(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn add(a: V3, b: V3) -> V3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} + +fn scale(a: V3, s: f64) -> V3 { + [a[0] * s, a[1] * s, a[2] * s] +} + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn length(a: V3) -> f64 { + dot(a, a).sqrt() +} + +/// A document point on the flat blank (y flipped so it points up, z = 0). +pub(super) fn flat(p: Point) -> V3 { + [p.x, -p.y, 0.0] +} + +/// Where a panel is: a rotation `m` (rows) and a translation `t`, taking a point of the flat +/// blank (see [`flat`]) to its place in 3D. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pose { + pub m: [[f64; 3]; 3], + pub t: [f64; 3], +} + +impl Pose { + /// The flat blank's own place. + pub const IDENTITY: Pose = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] }; + + /// Where the flat point `v` goes. + pub fn apply(&self, v: [f64; 3]) -> [f64; 3] { + add(self.turn(v), self.t) + } + + /// The direction `v` turned by the rotation alone. + pub fn turn(&self, v: [f64; 3]) -> [f64; 3] { + let [a, b, c] = self.m; + [dot(a, v), dot(b, v), dot(c, v)] + } + + /// Where the document point `p` goes. + pub fn place(&self, p: Point) -> [f64; 3] { + self.apply(flat(p)) + } + + /// The direction the printed side faces. + pub fn normal(&self) -> [f64; 3] { + self.turn([0.0, 0.0, 1.0]) + } + + /// This pose followed, in the flat blank's terms, by a right-handed turn of `theta` radians + /// about the line through `at` along the unit direction `axis`: the pose of a panel hinged to + /// this one there. + fn turned_about(&self, at: V3, axis: V3, theta: f64) -> Pose { + let (s, c) = theta.sin_cos(); + let [x, y, z] = axis; + // Rodrigues' rotation matrix. + let r = [ + [c + x * x * (1.0 - c), x * y * (1.0 - c) - z * s, x * z * (1.0 - c) + y * s], + [y * x * (1.0 - c) + z * s, c + y * y * (1.0 - c), y * z * (1.0 - c) - x * s], + [z * x * (1.0 - c) - y * s, z * y * (1.0 - c) + x * s, c + z * z * (1.0 - c)], + ]; + let mut m = [[0.0; 3]; 3]; + for (i, row) in m.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + *cell = (0..3).map(|k| self.m[i][k] * r[k][j]).sum(); + } + } + // p ↦ self(r (p - at) + at) = (self.m r) p + self.m (at - r at) + self.t + let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; + Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } + } +} + +/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no +/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it +/// and the base. +#[derive(Clone, Debug)] +pub struct FoldedPanel { + pub pose: Pose, + pub parent: Option<usize>, + pub depth: usize, +} + +/// A folded hinge: its panels, its angle (degrees, before the fold amount), whether it is in the +/// fold tree and, for one that is not, how far apart its two placements end up with every hinge at +/// its full angle, whatever the fold amount (`gap`, points), and whether that is close enough to call +/// it closed. +#[derive(Clone, Debug)] +pub struct FoldedHinge { + pub a: usize, + pub b: usize, + pub angle: f64, + pub tree: bool, + pub closes: bool, + pub gap: f64, +} + +/// A blank folded at one amount. +#[derive(Clone, Debug)] +pub struct Folded { + pub base: usize, + pub panels: Vec<FoldedPanel>, + /// The panels in breadth-first order from the base, the panels not joined to it last. + pub order: Vec<usize>, + pub hinges: Vec<FoldedHinge>, + /// Pairs of panels (`a` < `b`) that pass through each other. + pub collisions: Vec<(usize, usize)>, +} + +/// The panel of `blank` that `p` (document coordinates) lies in. +pub fn panel_at(blank: &Blank, p: Point) -> Option<usize> { + blank.panels.iter().position(|panel| panel.outline.to_bezpath().winding(p) != 0) +} + +/// Which of `blanks` to fold, and about which of its panels: the blank and panel `at` (document +/// coordinates) lies in, or, without a point, the blank with the largest panel (the first of equals) +/// and its base panel. `None` when `at` lies in no panel, or no blank has a panel. +pub fn pick(blanks: &[Blank], at: Option<Point>) -> Option<(usize, usize)> { + match at { + Some(p) => blanks.iter().enumerate().find_map(|(i, b)| Some((i, panel_at(b, p)?))), + None => { + let largest = |b: &Blank| b.panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); + let (i, b) = + blanks.iter().enumerate().filter(|(_, b)| !b.panels.is_empty()).fold(None, |best: Option<(usize, &Blank)>, (i, b)| match best { + Some((_, kept)) if largest(kept) >= largest(b) => best, + _ => Some((i, b)), + })?; + Some((i, base_panel(&b.panels)?)) + } + } +} + +/// `blank` folded about its panel `base` (the largest when `None`) by `amount` (0, flat, to 1, every +/// hinge at its angle). `tolerance` (points) is how far apart a closing hinge's placements may end +/// up and still close (or 0.5% of its length, when that is more), and how far apart two panels in +/// one plane may lie and still be stacked rather than crossing. `None` when the blank has no +/// panels, `base` is not one of them, or `amount` is not from 0 to 1. +pub fn fold(blank: &Blank, base: Option<usize>, amount: f64, tolerance: f64) -> Option<Folded> { + let base = match base { + Some(b) => b, + None => base_panel(&blank.panels)?, + }; + if base >= blank.panels.len() || !(0.0..=1.0).contains(&amount) { + return None; + } + let tolerance = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { 0.01 }; + let n = blank.panels.len(); + // Each panel's hinges, by the place they start (y, then x), then by the other panel. + let mut by_panel: Vec<Vec<usize>> = vec![vec![]; n]; + for (i, h) in blank.hinges.iter().enumerate() { + for p in [h.a, h.b] { + if let Some(list) = by_panel.get_mut(p) { + list.push(i); + } + } + } + // A hinge's ends, the one first by (y, x) first. + let ends = |i: &usize| { + blank.hinges.get(*i).map_or([f64::INFINITY; 4], |h| { + let (s, e) = if (h.from.y, h.from.x) <= (h.to.y, h.to.x) { (h.from, h.to) } else { (h.to, h.from) }; + [s.y, s.x, e.y, e.x] + }) + }; + for list in &mut by_panel { + list.sort_by(|a, b| { + let (ka, kb) = (ends(a), ends(b)); + ka.iter().zip(&kb).fold(std::cmp::Ordering::Equal, |o, (x, y)| o.then(x.total_cmp(y))).then(a.cmp(b)) + }); + } + let centers: Vec<Option<V3>> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); + let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // Closing hinges are measured with every hinge at its full angle, so a blank that closes when + // folded is not reported open part of the way there. + let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let measured = full.as_deref().unwrap_or(&panels); + let hinges = blank + .hinges + .iter() + .zip(&tree) + .map(|(h, &tree)| { + let (pa, pb) = (measured.get(h.a).map(|p| p.pose), measured.get(h.b).map(|p| p.pose)); + let gap = match (pa, pb) { + (Some(pa), Some(pb)) if !tree => [h.from, h.to].iter().map(|&e| length(sub(pa.place(e), pb.place(e)))).fold(0.0, f64::max), + _ => 0.0, + }; + let closes = tree || gap <= tolerance.max(0.005 * h.from.distance(h.to)); + FoldedHinge { a: h.a, b: h.b, angle: h.angle, tree, closes, gap } + }) + .collect(); + let collisions = collisions(blank, &panels, tolerance); + Some(Folded { base, panels, order, hinges, collisions }) +} + +/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not +/// joined to the base last). +fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: usize, amount: f64) -> (Vec<FoldedPanel>, Vec<bool>, Vec<usize>) { + let n = blank.panels.len(); + let mut panels: Vec<FoldedPanel> = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut reached = vec![false; n]; + let mut tree = vec![false; blank.hinges.len()]; + let mut order = Vec::with_capacity(n); + let mut queue = VecDeque::from([base]); + if let Some(r) = reached.get_mut(base) { + *r = true; + } + while let Some(p) = queue.pop_front() { + order.push(p); + let Some(parent) = panels.get(p).cloned() else { continue }; + for &hi in by_panel.get(p).map(Vec::as_slice).unwrap_or_default() { + let Some(h) = blank.hinges.get(hi) else { continue }; + let child = if h.a == p { h.b } else { h.a }; + if reached.get(child) != Some(&false) { + continue; + } + let (mut from, mut to) = (flat(h.from), flat(h.to)); + let len = length(sub(to, from)); + if !(len.is_finite() && len > 0.0) { + continue; + } + // The parent on the left of the hinge's direction, the child on its right. The side is + // read next to the hinge, so a parent with a notch or an arm past the hinge's line still + // turns the child the right way; the panel's inside point is the fallback. + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + Some(left) => left, + None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), + }; + if !left { + std::mem::swap(&mut from, &mut to); + } + let axis = scale(sub(to, from), 1.0 / len); + let theta = (h.angle * amount).to_radians(); + if !theta.is_finite() { + continue; + } + if let Some(slot) = panels.get_mut(child) { + *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + } + if let Some(r) = reached.get_mut(child) { + *r = true; + } + if let Some(t) = tree.get_mut(hi) { + *t = true; + } + queue.push_back(child); + } + } + order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); + (panels, tree, order) +} + +/// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) +/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and +/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset +/// tells them apart. The nearest offset is tried first. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option<bool> { + let bp = outline.to_bezpath(); + let mid = scale(add(from, to), 0.5); + let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; + let doc = |v: V3| Point::new(v[0], -v[1]); + let mut offsets = [1e-3, 0.25, len * 0.01]; + offsets.sort_by(f64::total_cmp); + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); + (l != r).then_some(l) + }) +} + +/// The rings of `path` flattened to `tolerance`, in document coordinates; `None` past +/// [`MAX_POLYGON_POINTS`] points. +pub fn polygon(path: &PathData, tolerance: f64) -> Option<Vec<Vec<Point>>> { + let mut rings: Vec<Vec<Point>> = vec![]; + let mut count = 0usize; + let mut fits = true; + vectorcraft_geom::flatten(path.to_bezpath(), tolerance, |el| { + if !fits { + return; + } + match el { + PathEl::MoveTo(p) => rings.push(vec![p]), + PathEl::LineTo(p) => match rings.last_mut() { + Some(r) => r.push(p), + None => rings.push(vec![p]), + }, + _ => return, + } + count += 1; + fits = count <= MAX_POLYGON_POINTS; + }); + rings.retain(|r| r.len() >= 3); + (fits && rings.iter().flatten().all(|p| p.is_finite())).then_some(rings) +} + +/// A panel placed in 3D: its rings, the plane it lies in (unit normal and offset) and its bounds. +struct Placed { + rings: Vec<Vec<V3>>, + normal: V3, + offset: f64, + lo: V3, + hi: V3, +} + +/// The pairs of `panels` that pass through each other. Two panels hinged to each other are not +/// tested, nor two in parallel planes (stacked in one plane, or apart). +fn collisions(blank: &Blank, panels: &[FoldedPanel], tolerance: f64) -> Vec<(usize, usize)> { + let placed: Vec<Option<Placed>> = blank + .panels + .iter() + .zip(panels) + .map(|(panel, f)| { + let rings: Vec<Vec<V3>> = + polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| f.pose.place(p)).collect()).collect(); + let all = rings.iter().flatten(); + let lo = all.clone().fold([f64::INFINITY; 3], |a, p| [a[0].min(p[0]), a[1].min(p[1]), a[2].min(p[2])]); + let hi = all.fold([f64::NEG_INFINITY; 3], |a, p| [a[0].max(p[0]), a[1].max(p[1]), a[2].max(p[2])]); + let normal = f.pose.normal(); + let offset = dot(normal, f.pose.t); + Some(Placed { rings, normal, offset, lo, hi }) + }) + .collect(); + let hinged: HashSet<(usize, usize)> = blank.hinges.iter().map(|h| (h.a.min(h.b), h.a.max(h.b))).collect(); + let mut out = vec![]; + for (i, a) in placed.iter().enumerate() { + let Some(a) = a else { continue }; + for (j, b) in placed.iter().enumerate().skip(i + 1) { + let Some(b) = b else { continue }; + if hinged.contains(&(i, j)) || (0..3).any(|k| a.hi[k] + tolerance < b.lo[k] || b.hi[k] + tolerance < a.lo[k]) { + continue; + } + let line = cross(a.normal, b.normal); + let along = length(line); + if along.is_nan() || along <= 1e-9 { + continue; + } + let u = scale(line, 1.0 / along); + let on_a = crossings(&a.rings, b.normal, b.offset, u, tolerance); + let on_b = crossings(&b.rings, a.normal, a.offset, u, tolerance); + if on_a.iter().any(|x| on_b.iter().any(|y| x.1.min(y.1) - x.0.max(y.0) > tolerance)) { + out.push((i, j)); + } + } + } + out +} + +/// Where `rings` cross the plane `normal · p = offset`: the spans of the line along `u` that lie +/// inside them, by their place along `u`. A panel with no point more than `tolerance` to one side +/// of the plane only touches it, and crosses it nowhere; otherwise points within `tolerance` of it +/// count as on its positive side. +fn crossings(rings: &[Vec<V3>], normal: V3, offset: f64, u: V3, tolerance: f64) -> Vec<(f64, f64)> { + let side = |p: V3| dot(normal, p) - offset; + let sides = rings.iter().flatten().map(|&p| side(p)); + let (above, below) = sides.fold((false, false), |(a, b), s| (a || s > tolerance, b || s < -tolerance)); + if !(above && below) { + return vec![]; + } + let mut at = vec![]; + for ring in rings { + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (sp, sq) = (side(p), side(q)); + if (sp >= -tolerance) != (sq >= -tolerance) { + let t = (sp / (sp - sq)).clamp(0.0, 1.0); + at.push(dot(u, add(p, scale(sub(q, p), t)))); + } + } + } + at.retain(|x| x.is_finite()); + at.sort_by(f64::total_cmp); + at.as_chunks::<2>().0.iter().map(|&[a, b]| (a, b)).collect() +} diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs new file mode 100644 index 0000000000..012a9621de --- /dev/null +++ b/crates/three-d/src/fold/raster.rs @@ -0,0 +1,474 @@ +//! Draws a [`Folded`] blank as pixels: each panel's outline is projected through the view and filled +//! by scanline, with a depth buffer, and each pixel takes its color from a raster of the flat print +//! (the printed side) or from the inside color (the back), shaded by the panel's slope to a fixed +//! light. The inverse of the panel's projective map gives the flat point under every pixel, so the +//! print is drawn without seams under perspective. With perspective, each panel is cut at a near +//! plane in front of the eye before it is projected. + +use vectorcraft_geom::{Point, Rect}; + +use super::pose::{Folded, polygon}; +use super::{Blank, Panel}; + +/// Most pixels a side of the view or of the print raster may have. +pub const MAX_SIDE: u32 = 4096; +/// Most pixels the view may have in all (2,048 × 1,024; 32 MiB of buffers). +pub const MAX_PIXELS: u32 = 1 << 21; +/// The share of the eye's distance a panel is cut at in front of the eye. +const NEAREST: f64 = 1e-3; +/// How far apart (points of view depth) two panels may be and still tie. +const TIE: f64 = 1e-4; +/// The light's direction: above, to the left of and toward the viewer. +const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; + +type V3 = [f64; 3]; + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// The view: its size in pixels, its turn (degrees: `rotate_x` tips the top toward the viewer, +/// `rotate_y` turns the right side toward the viewer), its scale (pixels per point at the center's +/// depth), how far it is moved (pixels), its perspective (the field of view in degrees; 0 for none) +/// and the 3D point at its middle. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Camera { + pub width: u32, + pub height: u32, + pub rotate_x: f64, + pub rotate_y: f64, + pub scale: f64, + pub pan: [f64; 2], + pub perspective: f64, + pub center: [f64; 3], +} + +impl Camera { + /// The turn from 3D to the view's own axes (x right, y up, z toward the viewer), as rows. + fn rotation(&self) -> [[f64; 3]; 3] { + let (sx, cx) = self.rotate_x.to_radians().sin_cos(); + let (sy, cy) = (-self.rotate_y).to_radians().sin_cos(); + // Rx · Ry + [[cy, 0.0, sy], [sx * sy, cx, -sx * cy], [-cx * sy, sx, cx * cy]] + } + + /// The point `p` in the view's own axes, its middle at the origin. + pub fn to_view(&self, p: V3) -> V3 { + let r = self.rotation(); + let d = [p[0] - self.center[0], p[1] - self.center[1], p[2] - self.center[2]]; + [dot(r[0], d), dot(r[1], d), dot(r[2], d)] + } + + /// The distance (points) from the eye to the view's middle and the focal length (pixels) under + /// perspective; `None` without it. + fn eye(&self) -> Option<(f64, f64)> { + if self.perspective <= 0.0 || self.perspective >= 180.0 { + return None; + } + let half = f64::from(self.width.min(self.height)) / 2.0; + let focal = half / (self.perspective.to_radians() / 2.0).tan(); + let eye = focal / self.scale; + (focal.is_finite() && eye.is_finite() && eye > 0.0).then_some((eye, focal)) + } + + fn usable(&self) -> bool { + let finite = + [self.rotate_x, self.rotate_y, self.scale, self.pan[0], self.pan[1], self.perspective].iter().chain(&self.center).all(|v| v.is_finite()); + let pixels = u64::from(self.width) * u64::from(self.height); + finite && self.scale > 0.0 && (1..=MAX_SIDE).contains(&self.width) && (1..=MAX_SIDE).contains(&self.height) && pixels <= u64::from(MAX_PIXELS) + } +} + +/// One level of the print raster: premultiplied RGBA, 4 bytes a pixel. +#[derive(Clone, Debug)] +pub struct Level { + pub width: u32, + pub height: u32, + pub pixels: Vec<u8>, +} + +impl Level { + /// The color at pixel `(x, y)`, clamped to the edges. + fn at(&self, x: i64, y: i64) -> [f32; 4] { + let x = x.clamp(0, i64::from(self.width) - 1); + let y = y.clamp(0, i64::from(self.height) - 1); + let i = usize::try_from((y * i64::from(self.width) + x) * 4).unwrap_or(usize::MAX); + match self.pixels.get(i..i.saturating_add(4)) { + Some(&[r, g, b, a]) => [f32::from(r), f32::from(g), f32::from(b), f32::from(a)], + _ => [0.0; 4], + } + } + + /// The color at `(x, y)` (pixels), between the four nearest pixels. + fn sample(&self, x: f64, y: f64) -> [f32; 4] { + let (fx, fy) = (x - 0.5, y - 0.5); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32); + let (x0, y0) = (x0 as i64, y0 as i64); + let (a, b, c, d) = (self.at(x0, y0), self.at(x0 + 1, y0), self.at(x0, y0 + 1), self.at(x0 + 1, y0 + 1)); + let mut out = [0.0; 4]; + for (k, o) in out.iter_mut().enumerate() { + let top = a[k] + (b[k] - a[k]) * tx; + let bottom = c[k] + (d[k] - c[k]) * tx; + *o = top + (bottom - top) * ty; + } + out + } + + /// This level at half its size, rounded up, each pixel the mean of the four it covers (an odd + /// last row or column with itself). + fn half(&self) -> Option<Level> { + let (w, h) = (self.width.div_ceil(2), self.height.div_ceil(2)); + if (w, h) == (self.width, self.height) { + return None; + } + let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..i64::from(h) { + for x in 0..i64::from(w) { + let px = [self.at(2 * x, 2 * y), self.at(2 * x + 1, 2 * y), self.at(2 * x, 2 * y + 1), self.at(2 * x + 1, 2 * y + 1)]; + for k in 0..4 { + pixels.push((px.iter().map(|p| p[k]).sum::<f32>() / 4.0).round() as u8); + } + } + } + Some(Level { width: w, height: h, pixels }) + } +} + +/// The flat print: the document rect it covers and its raster at full size and at two halvings. +#[derive(Clone, Debug)] +pub struct Print { + pub region: Rect, + pub levels: Vec<Level>, +} + +impl Print { + /// The print of `region` from `pixels` (premultiplied RGBA, `width` × `height`); `None` when + /// the sizes do not agree, a side is 0 or more than [`MAX_SIDE`], or the region is empty. + pub fn new(region: Rect, width: u32, height: u32, pixels: Vec<u8>) -> Option<Print> { + let fits = (1..=MAX_SIDE).contains(&width) && (1..=MAX_SIDE).contains(&height); + let empty = !(region.width() > 0.0 && region.height() > 0.0 && region.is_finite()); + if !fits || empty || pixels.len() != width as usize * height as usize * 4 { + return None; + } + let mut levels = vec![Level { width, height, pixels }]; + while levels.len() < 3 { + let Some(next) = levels.last().and_then(Level::half) else { break }; + levels.push(next); + } + Some(Print { region, levels }) + } + + /// The print's color (premultiplied, 0 to 255) at document point `p`, from the level whose + /// pixels are closest to `footprint` points across; transparent outside the region. + fn sample(&self, p: Point, footprint: f64) -> [f32; 4] { + let Some(base) = self.levels.first() else { return [0.0; 4] }; + if !self.region.contains(p) { + return [0.0; 4]; + } + let per_point = f64::from(base.width) / self.region.width(); + let level = if footprint.is_finite() && footprint > 0.0 { (footprint * per_point).log2().floor().max(0.0) as usize } else { 0 }; + let level = level.min(self.levels.len() - 1); + let Some(l) = self.levels.get(level) else { return [0.0; 4] }; + // Each level halves the one before it, so a pixel of level n covers 2ⁿ of the first's. + let shrink = f64::from(1u32 << level); + let sx = f64::from(base.width) / self.region.width() / shrink; + let sy = f64::from(base.height) / self.region.height() / shrink; + l.sample((p.x - self.region.x0) * sx, (p.y - self.region.y0) * sy) + } +} + +/// What [`render`] draws: a folded blank, its print (if any), the color of the board's back and of +/// its printed side where the print has no art (straight RGBA), and the view. +pub struct Scene<'a> { + pub blank: &'a Blank, + pub folded: &'a Folded, + pub print: Option<&'a Print>, + pub inside: [u8; 4], + pub outside: [u8; 4], + pub camera: Camera, +} + +/// A drawn view: premultiplied RGBA, 4 bytes a pixel, transparent where no panel is; and for each +/// pixel the panel drawn there plus 1 (0 for none). +#[derive(Clone, Debug)] +pub struct Image { + pub width: u32, + pub height: u32, + pub pixels: Vec<u8>, + pub panels: Vec<u16>, +} + +impl Image { + /// The panel drawn at pixel `(x, y)`. + pub fn panel_at(&self, x: u32, y: u32) -> Option<usize> { + if x >= self.width || y >= self.height { + return None; + } + let i = y as usize * self.width as usize + x as usize; + self.panels.get(i).and_then(|&p| usize::from(p).checked_sub(1)) + } +} + +/// The 3D bounds of `blank`'s panels folded as `folded` places them (low and high corners). +pub fn bounds(blank: &Blank, folded: &Folded) -> Option<(V3, V3)> { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for (panel, f) in blank.panels.iter().zip(&folded.panels) { + let Some(b) = panel.outline.bounds() else { continue }; + for c in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)] { + let p = f.pose.place(c); + for k in 0..3 { + lo[k] = lo[k].min(p[k]); + hi[k] = hi[k].max(p[k]); + } + } + } + lo.iter().chain(&hi).all(|v| v.is_finite()).then_some((lo, hi)) +} + +/// A panel ready to fill: its projective map from the flat blank to the view and back, its depth +/// plane in view terms, and its color factors. +struct Mapped { + /// Flat (u, v, 1) → (x w, y w, w) in pixels, as rows. + forward: [[f64; 3]; 3], + /// The inverse of `forward`. + inverse: [[f64; 3]; 3], + /// View depth at flat (u, v): u a + v b + c. + depth: [f64; 3], + printed: bool, + shade: f32, +} + +fn mul(m: &[[f64; 3]; 3], v: V3) -> V3 { + [dot(m[0], v), dot(m[1], v), dot(m[2], v)] +} + +fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { + let [[a, b, c], [d, e, f], [g, h, i]] = *m; + let co = [e * i - f * h, f * g - d * i, d * h - e * g]; + let det = a * co[0] + b * co[1] + c * co[2]; + if !(det.is_finite() && det.abs() > 1e-300) { + return None; + } + let inv = [ + [co[0] / det, (c * h - b * i) / det, (b * f - c * e) / det], + [co[1] / det, (a * i - c * g) / det, (c * d - a * f) / det], + [co[2] / det, (b * g - a * h) / det, (a * e - b * d) / det], + ]; + inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) +} + +fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option<Mapped> { + let r = camera.rotation(); + let turn = |v: V3| mul(&r, f.pose.turn(v)); + let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); + let o = camera.to_view(f.pose.t); + let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); + let normal = turn([0.0, 0.0, 1.0]); + let (w, k, printed) = match camera.eye() { + Some((eye, focal)) => ([-a[2], -b[2], eye - o[2]], focal, dot(normal, [-o[0], -o[1], eye - o[2]]) > 0.0), + None => ([0.0, 0.0, 1.0], camera.scale, normal[2] > 0.0), + }; + let x = [cx * w[0] + k * a[0], cx * w[1] + k * b[0], cx * w[2] + k * o[0]]; + let y = [cy * w[0] - k * a[1], cy * w[1] - k * b[1], cy * w[2] - k * o[1]]; + let forward = [x, y, w]; + let inverse = invert(&forward)?; + let facing = if printed { normal } else { [-normal[0], -normal[1], -normal[2]] }; + let shade = (0.6 + 0.4 * dot(facing, LIGHT).max(0.0)) as f32; + Some(Mapped { forward, inverse, depth: [a[2], b[2], o[2]], printed, shade }) +} + +/// `ring` (flat points) cut to the side of the plane `w · (u, v, 1) ≥ near`. +fn clip(ring: &[[f64; 2]], w: V3, near: f64) -> Vec<[f64; 2]> { + let at = |p: [f64; 2]| dot(w, [p[0], p[1], 1.0]) - near; + let mut out = Vec::with_capacity(ring.len() + 4); + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (dp, dq) = (at(p), at(q)); + if dp >= 0.0 { + out.push(p); + } + if (dp >= 0.0) != (dq >= 0.0) { + let t = dp / (dp - dq); + out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]); + } + } + out +} + +/// The buffers [`render`] fills. +struct Target { + width: usize, + height: usize, + color: Vec<u8>, + depth: Vec<f64>, + rank: Vec<u16>, + panel: Vec<u16>, +} + +/// One panel's fill: its map, rank (for ties), panel number and colors. +struct Fill<'a> { + mapped: &'a Mapped, + rank: u16, + panel: u16, + print: Option<&'a Print>, + inside: [f32; 4], + outside: [f32; 4], +} + +impl Fill<'_> { + /// The document point under pixel center `(x, y)`, or `None` behind the eye. + fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { + let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); + (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) + } + + /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. + fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { + let base = if self.mapped.printed { + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let under = 1.0 - p[3] / 255.0; + [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] + } else { + self.inside + }; + let s = self.mapped.shade; + [base[0] * s, base[1] * s, base[2] * s, base[3]] + } + + /// Fill the span of row `row` from `x0` to `x1` (pixel coordinates) into `target`. + fn span(&self, target: &mut Target, row: usize, x0: f64, x1: f64) { + let first = (x0 - 0.5).ceil().max(0.0); + let last = ((x1 - 0.5).ceil() - 1.0).min(target.width as f64 - 1.0); + if first > last { + return; + } + let y = row as f64 + 0.5; + for col in first as usize..=last as usize { + let x = col as f64 + 0.5; + let Some((u, v)) = self.flat_at(x, y) else { continue }; + let [a, b, c] = self.mapped.depth; + let z = u * a + v * b + c; + let i = row * target.width + col; + let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; + let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + if !wins { + continue; + } + let footprint = self.flat_at(x + 1.0, y).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v)); + let color = self.color(u, v, footprint); + if let Some(px) = target.color.get_mut(i * 4..i * 4 + 4) { + for (o, c) in px.iter_mut().zip(color) { + *o = c.round().clamp(0.0, 255.0) as u8; + } + } + if let Some(d) = target.depth.get_mut(i) { + *d = z; + } + if let Some(r) = target.rank.get_mut(i) { + *r = self.rank; + } + if let Some(p) = target.panel.get_mut(i) { + *p = self.panel; + } + } + } + + /// Fill the projected `rings` (pixel coordinates), even-odd, into `target`. + fn rings(&self, target: &mut Target, rings: &[Vec<[f64; 2]>]) { + let ys = rings.iter().flatten().map(|p| p[1]); + let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))); + if !(lo.is_finite() && hi.is_finite()) { + return; + } + let first = (lo - 0.5).ceil().max(0.0); + let last = (hi - 0.5).floor().min(target.height as f64 - 1.0); + if first > last { + return; + } + let mut xs = vec![]; + for row in first as usize..=last as usize { + let y = row as f64 + 0.5; + xs.clear(); + for ring in rings { + for (k, p) in ring.iter().enumerate() { + let Some(q) = ring.get((k + 1) % ring.len()) else { continue }; + if (p[1] <= y) != (q[1] <= y) { + xs.push(p[0] + (y - p[1]) * (q[0] - p[0]) / (q[1] - p[1])); + } + } + } + xs.retain(|x| x.is_finite()); + xs.sort_by(f64::total_cmp); + for &[a, b] in xs.as_chunks::<2>().0 { + self.span(target, row, a, b); + } + } + } +} + +fn rgba(c: [u8; 4]) -> [f32; 4] { + let a = f32::from(c[3]) / 255.0; + [f32::from(c[0]) * a, f32::from(c[1]) * a, f32::from(c[2]) * a, f32::from(c[3])] +} + +/// The outline rings of `panel` in flat terms (u, v), flattened finely enough for `scale` pixels a +/// point. +fn flat_rings(panel: &Panel, scale: f64) -> Option<Vec<Vec<[f64; 2]>>> { + let b = panel.outline.bounds()?; + let tolerance = (0.25 / scale).max((b.width() + b.height()) * 1e-5).max(1e-6); + Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) +} + +/// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more +/// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than +/// [`super::MAX_POLYGON_POINTS`] points, are left out. +pub fn render(scene: &Scene) -> Option<Image> { + let camera = scene.camera; + if !camera.usable() { + return None; + } + let (width, height) = (camera.width as usize, camera.height as usize); + let pixels = width * height; + let mut target = + Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; + let (inside, outside) = (rgba(scene.inside), rgba(scene.outside)); + let near = camera.eye().map(|(eye, _)| eye * NEAREST); + for (rank, &pi) in scene.folded.order.iter().enumerate() { + let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; + let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let projected: Vec<Vec<[f64; 2]>> = rings + .iter() + .map(|r| match near { + Some(near) => clip(r, mapped.forward[2], near), + None => r.clone(), + }) + .filter(|r| r.len() >= 3) + .map(|r| { + r.into_iter() + .filter_map(|[u, v]| { + let [x, y, w] = mul(&mapped.forward, [u, v, 1.0]); + let p = [x / w, y / w]; + (w > 0.0 && p[0].is_finite() && p[1].is_finite()).then_some(p) + }) + .collect::<Vec<_>>() + }) + .filter(|r| r.len() >= 3) + .collect(); + let fill = Fill { + mapped: &mapped, + rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), + print: scene.print, + inside, + outside, + }; + fill.rings(&mut target, &projected); + } + Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs new file mode 100644 index 0000000000..477040b571 --- /dev/null +++ b/crates/three-d/src/fold/raster/tests.rs @@ -0,0 +1,179 @@ +use vectorcraft_geom::{PathData, Point, Rect, SubPath}; + +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::*; + +fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { + SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true) +} + +fn panel(subpaths: Vec<SubPath>) -> Panel { + Panel { outline: PathData::new(subpaths), area: 0.0 } +} + +/// A blank of `panels` and a fold that places each at `poses`, in the order given. +fn scene_of(panels: Vec<Panel>, poses: Vec<Pose>) -> (Blank, Folded) { + let n = panels.len(); + let folded = Folded { + base: 0, + panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + order: (0..n).collect(), + hinges: vec![], + collisions: vec![], + }; + (Blank { panels, hinges: vec![], holes: vec![] }, folded) +} + +/// Facing the printed side, 100 × 100 pixels, one pixel a point, the flat square 0..100 filling it. +fn front() -> Camera { + Camera { width: 100, height: 100, rotate_x: 0.0, rotate_y: 0.0, scale: 1.0, pan: [0.0; 2], perspective: 0.0, center: [50.0, -50.0, 0.0] } +} + +fn moved(z: f64) -> Pose { + Pose { t: [0.0, 0.0, z], ..Pose::IDENTITY } +} + +fn pixel(img: &Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// A 2 × 2 print of the square 0..100: red, green on top; blue, white below. +fn quads() -> Print { + let px = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]]; + Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 2, 2, px.concat()).expect("a print") +} + +const WHITE: [u8; 4] = [255, 255, 255, 255]; + +#[test] +fn a_flat_panel_takes_the_print_s_color_under_each_pixel() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + assert_eq!(pixel(&img, 5, 5), [lit(255.0), 0, 0, 255], "top left is red"); + assert_eq!(pixel(&img, 94, 5), [0, lit(255.0), 0, 255], "top right is green"); + assert_eq!(pixel(&img, 5, 94), [0, 0, lit(255.0), 255], "bottom left is blue"); + assert_eq!(img.panel_at(50, 50), Some(0)); + // Where the print has no art, the board's printed side shows. + let empty = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 1, 1, vec![0; 4]).expect("a print"); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&empty), inside: [0, 0, 0, 255], outside: [200, 100, 50, 255], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255]); +} + +#[test] +fn the_back_of_a_panel_shows_the_inside_color() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 200, 0, 255], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let draw = |z: f64| { + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(z)]); + render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn") + }; + assert_eq!(draw(5.0).panel_at(50, 50), Some(1), "panel 1 is in front"); + assert_eq!(draw(-5.0).panel_at(50, 50), Some(0), "panel 1 is behind"); + assert_eq!(draw(0.0).panel_at(50, 50), Some(1), "a tie goes to the panel later in the order"); + // Panels that cross: each shows where it is nearer. + let tilted = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 1.0]], t: [0.0, 0.0, -25.0] }; + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, tilted]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(20, 50), Some(0), "the tilted panel is behind on the left"); + assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); +} + +#[test] +fn a_hole_in_a_panel_is_left_empty() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), None); + assert_eq!(pixel(&img, 50, 50), [0; 4]); + assert_eq!(img.panel_at(10, 50), Some(0)); +} + +#[test] +fn a_panel_past_the_eye_at_a_wide_perspective_is_cut_at_the_near_plane() { + // A long panel standing out of the page toward the viewer, through the eye. + let toward = Pose { m: [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], t: [0.0, -50.0, 0.0] }; + let (b, f) = scene_of(vec![panel(vec![square(0.0, -1000.0, 100.0, 1000.0)])], vec![toward]); + for perspective in [1.0, 60.0, 160.0, 179.0] { + let camera = Camera { perspective, scale: 8.0, rotate_x: 30.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let drawn = img.panels.iter().filter(|&&p| p != 0).count(); + assert!(drawn > 0, "{perspective}°: some of it shows"); + assert_eq!(img.pixels.len(), 100 * 100 * 4); + } +} + +#[test] +fn unusable_views_and_prints_are_refused() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for camera in [ + Camera { width: 0, ..front() }, + Camera { height: MAX_SIDE + 1, ..front() }, + Camera { width: MAX_SIDE, height: MAX_PIXELS / MAX_SIDE + 1, ..front() }, + Camera { scale: 0.0, ..front() }, + Camera { rotate_x: f64::NAN, ..front() }, + Camera { center: [f64::INFINITY, 0.0, 0.0], ..front() }, + ] { + assert!(render(&Scene { blank: &b, folded: &f, print: None, inside: [0; 4], outside: WHITE, camera }).is_none(), "{camera:?}"); + } + let region = Rect::new(0.0, 0.0, 10.0, 10.0); + assert!(Print::new(region, 2, 2, vec![0; 15]).is_none(), "too few bytes"); + assert!(Print::new(region, 0, 2, vec![]).is_none()); + assert!(Print::new(region, MAX_SIDE + 1, 1, vec![0; (MAX_SIDE as usize + 1) * 4]).is_none()); + assert!(Print::new(Rect::new(0.0, 0.0, 0.0, 10.0), 1, 1, vec![0; 4]).is_none(), "an empty region"); + let p = Print::new(region, 8, 4, vec![255; 8 * 4 * 4]).expect("a print"); + assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(8, 4), (4, 2), (2, 1)]); +} + +#[test] +fn halving_an_odd_sized_print_keeps_its_last_row_and_column() { + // 3 × 3, transparent but for an opaque white last column and last row. + let mut px = vec![0u8; 3 * 3 * 4]; + for i in [2, 5, 6, 7, 8] { + px[i * 4..i * 4 + 4].copy_from_slice(&[255; 4]); + } + let p = Print::new(Rect::new(0.0, 0.0, 30.0, 30.0), 3, 3, px).expect("a print"); + let half = &p.levels[1]; + assert_eq!((half.width, half.height), (2, 2)); + // The bottom right pixel of the half level covers only the corner pixel. + assert_eq!(&half.pixels[12..16], &[255; 4]); + assert_eq!(&half.pixels[0..4], &[0; 4], "the top left covers four transparent pixels"); +} + +#[test] +fn a_print_far_smaller_on_screen_samples_a_halved_level() { + // Columns alternate black and white: halved, they average to gray. + let mut px = vec![]; + for _ in 0..4 { + for x in 0..4 { + px.extend(if x % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 4, 4, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 2 pixels: 2 print pixels a view pixel. + let camera = Camera { width: 2, height: 2, scale: 0.02, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 0); + assert!((80..=150).contains(&r), "gray, not a black or white column: {r}"); +} + +#[test] +fn the_bounds_take_in_every_folded_panel() { + let (b, f) = + scene_of(vec![panel(vec![square(0.0, 0.0, 10.0, 10.0)]), panel(vec![square(0.0, 0.0, 10.0, 10.0)])], vec![Pose::IDENTITY, moved(-7.0)]); + let (lo, hi) = bounds(&b, &f).expect("bounds"); + assert_eq!((lo, hi), ([0.0, -10.0, -7.0], [10.0, 0.0, 0.0])); +} diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index ef014300c0..8031a0b2a1 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -913,4 +913,323 @@ proptest! { sorted.sort_by_key(|i| i.code); prop_assert_eq!(sorted, issues); } + + /// Random fold lines fold at any amount without a panic, every pose finite and every panel + /// keeping its shape. + #[test] + fn random_blanks_fold_to_finite_poses( + segs in proptest::collection::vec((1u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..8), + amount in 0.0f64..=1.0, + ) { + let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation]; + let mut lines: Vec<FoldLine> = segs + .iter() + .enumerate() + .map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64)) + .collect(); + lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99)); + let (blanks, _) = blanks(&lines, TOL); + for b in &blanks { + let Some(f) = fold(b, None, amount, TOL) else { continue }; + prop_assert_eq!(f.panels.len(), b.panels.len()); + prop_assert_eq!(f.order.len(), b.panels.len()); + for p in &f.panels { + prop_assert!(p.pose.m.iter().flatten().chain(&p.pose.t).all(|v| v.is_finite())); + let n = p.pose.normal(); + prop_assert!((n[0] * n[0] + n[1] * n[1] + n[2] * n[2] - 1.0).abs() < 1e-9); + } + } + } +} + +/// The 3D corners of panel `i` of `b` folded as `f` places them. +fn corners(b: &Blank, f: &Folded, i: usize) -> Vec<[f64; 3]> { + let rings = polygon(&b.panels[i].outline, 0.01).expect("a polygon"); + rings.into_iter().flatten().map(|p| f.panels[i].pose.place(p)).collect() +} + +fn flat_center(b: &Blank, i: usize) -> [f64; 3] { + let c = point_in(&b.panels[i].outline).expect("a point inside"); + [c.x, -c.y, 0.0] +} + +#[test] +fn a_slotted_box_folds_every_panel_onto_a_face_of_the_box_with_the_print_outside() { + let (b, issues) = check(¬ched_box()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + // The base panel is the leftmost of the two largest body panels: x 20 to 120, y 30 to 110. + let base = &b.panels[f.base]; + assert_eq!(base.outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((20.0, 30.0))); + // The box: the base panel's face (z = 0), 60 deep (the narrow body panels' width). + let (lo, hi) = ([20.0, -110.0, -60.0], [120.0, -30.0, 0.0]); + let middle = [70.0, -70.0, -30.0]; + for i in 0..b.panels.len() { + let points = corners(b, &f, i); + let face = (0..3).find_map(|k| [lo[k], hi[k]].into_iter().find(|&at| points.iter().all(|p| (p[k] - at).abs() < 1e-6)).map(|at| (k, at))); + let (k, at) = face.unwrap_or_else(|| panic!("panel {i} lies on no face of the box: {points:?}")); + for p in &points { + for j in 0..3 { + assert!(p[j] > lo[j] - 1e-6 && p[j] < hi[j] + 1e-6, "panel {i} reaches out of the box: {p:?}"); + } + } + // The printed side faces out of the box. + let n = f.panels[i].pose.normal(); + assert!((n[k].abs() - 1.0).abs() < 1e-9, "panel {i} is square to its face: {n:?}"); + assert!(n[k] * (at - middle[k]) > 0.0, "panel {i}'s print faces out: {n:?}"); + } + assert!(f.hinges.iter().all(|h| h.tree && h.closes && (h.angle - 90.0).abs() < 1e-12), "{:?}", f.hinges); + assert!(f.collisions.is_empty(), "the stacked flaps and the glue flap do not cross: {:?}", f.collisions); + assert_eq!(f.order.first(), Some(&f.base)); + assert_eq!(f.order.len(), 13); +} + +#[test] +fn at_amount_0_the_blank_is_flat() { + let (b, _) = check(¬ched_box()); + let f = fold(&b[0], None, 0.0, TOL).expect("folds"); + for p in &f.panels { + for (row, want) in p.pose.m.iter().zip(Pose::IDENTITY.m) { + assert!(row.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-12), "{:?}", p.pose); + } + assert!(p.pose.t.iter().all(|v| v.abs() < 1e-9), "{:?}", p.pose); + } +} + +/// A 100 × 60 rectangle split by a line of `kind` at x = 60 (drawn upward when `up`), turned by +/// `quarter` quarter turns about the origin and mirrored in x when `mirror`. +fn two_panels(kind: LineKind, quarter: u8, mirror: bool, up: bool) -> Vec<FoldLine> { + let at = |(x, y): (f64, f64)| { + let x = if mirror { -x } else { x }; + (0..quarter).fold((x, y), |(x, y), _| (-y, x)) + }; + let outline: Vec<(f64, f64)> = [(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)].into_iter().map(at).collect(); + let (a, b) = if up { ((60.0, 60.0), (60.0, 0.0)) } else { ((60.0, 0.0), (60.0, 60.0)) }; + vec![cut(&outline, 1), line(kind, &[at(a), at(b)], false, 2)] +} + +#[test] +fn a_crease_folds_away_from_the_print_and_a_partial_cut_toward_it_however_it_is_drawn() { + for quarter in 0..4 { + for mirror in [false, true] { + for up in [false, true] { + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::Perforation, -1.0), (LineKind::PartialCut, 1.0)] { + let case = format!("{kind:?}, {quarter} quarter turns, mirrored {mirror}, drawn up {up}"); + let (b, issues) = check(&two_panels(kind, quarter, mirror, up)); + assert!(issues.is_empty(), "{case}: {issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let h = &b.hinges[0]; + let hinge = [(h.from.x + h.to.x) / 2.0, -(h.from.y + h.to.y) / 2.0, 0.0]; + let c = flat_center(b, child); + let away = [c[0] - hinge[0], c[1] - hinge[1], 0.0]; + let along = [h.to.x - h.from.x, h.from.y - h.to.y]; + let off_line = (along[0] * away[1] - along[1] * away[0]).abs() / along[0].hypot(along[1]); + let placed = f.panels[child].pose.apply(c); + // The child stands up out of the plane: behind it for a crease, in front of it + // for a partial cut, at its distance from the hinge. + assert!(placed[2] * sign > 0.0, "{case}: {placed:?}"); + assert!((placed[2].abs() - off_line).abs() < 1e-6, "{case}: {placed:?} {off_line}"); + // Its printed side faces away from the base panel after a crease, back toward + // it after a partial cut. + let n = f.panels[child].pose.normal(); + assert!((n[0] * away[0] + n[1] * away[1]) * -sign > 0.0, "{case}: {n:?}"); + // Half way, the child is half way round. + let half = fold(b, None, 0.5, TOL).expect("folds"); + let z = half.panels[child].pose.normal()[2]; + assert!((z - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{case}: {z}"); + } + } + } + } +} + +/// A 100 × 100 square divided into four panels by a crease across it each way. +fn crossed() -> Vec<FoldLine> { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + crease((50.0, 0.0), (50.0, 100.0), 2), + crease((0.0, 50.0), (100.0, 50.0), 3), + ] +} + +#[test] +fn a_loop_of_hinges_closes_when_flat_and_reports_its_gap_when_folded() { + let (b, issues) = check(&crossed()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (4, 4)); + let folded = fold(b, None, 1.0, TOL).expect("folds"); + let closing: Vec<&FoldedHinge> = folded.hinges.iter().filter(|h| !h.tree).collect(); + assert_eq!(closing.len(), 1, "three hinges make the tree, one closes the loop"); + assert!(!closing[0].closes && closing[0].gap > 10.0, "{closing:?}"); + // The gap is measured folded all the way, whatever the amount: flat or half way, the loop is + // still reported open by the same gap. + for amount in [0.0, 0.5] { + let part = fold(b, None, amount, TOL).expect("folds"); + let h = part.hinges.iter().find(|h| !h.tree).expect("a closing hinge"); + assert!(!h.closes && (h.gap - closing[0].gap).abs() < 1e-9, "{amount}: {h:?}"); + } + // The base is the top-left panel: four equal panels tie, and the highest, then leftmost, wins. + assert_eq!(b.panels[folded.base].outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((0.0, 0.0))); +} + +#[test] +fn hinges_that_start_at_one_point_fold_the_same_in_any_line_order() { + // About the bottom-right panel, its two hinges both start at the middle of the square. + let lines = crossed(); + let orders = [[0, 1, 2], [0, 2, 1], [2, 1, 0], [1, 2, 0], [1, 0, 2], [2, 0, 1]]; + let mut seen = None; + for order in orders { + let lines: Vec<FoldLine> = order.iter().map(|&i| lines[i].clone()).collect(); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{order:?}: {issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(75.0, 75.0)).expect("the bottom-right panel"); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + let closing = f.hinges.iter().zip(&b.hinges).find(|(h, _)| !h.tree).map(|(_, h)| ((h.from.x + h.to.x) / 2.0, (h.from.y + h.to.y) / 2.0)); + let top_left = panel_at(b, p(25.0, 25.0)).expect("the top-left panel"); + let placed = f.panels[top_left].pose.place(p(25.0, 25.0)).map(|v| (v * 1e6).round()); + let got = (closing, placed); + assert_eq!(seen.get_or_insert(got), &got, "{order:?}"); + } +} + +/// A 100 × 60 rectangle: the left 60 pt is one panel, the right is split across at y = 30, and the +/// line between them bends by `lean` pt over its lower half. +fn leaning(lean: f64) -> Vec<FoldLine> { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + crease((60.0, 0.0), (60.0, 30.0), 2), + crease((60.0, 30.0), (60.0 + lean, 60.0), 3), + crease((60.0, 30.0), (100.0, 30.0), 4), + ] +} + +#[test] +fn a_loop_closes_within_the_tolerance_or_half_a_percent_of_its_hinge() { + // Both right panels turn about one line, so the hinge between them closes exactly. + let gap = |lean: f64, amount: f64| { + let (b, issues) = check(&leaning(lean)); + assert!(issues.is_empty(), "{lean}: {issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (3, 3)); + let base = panel_at(b, p(30.0, 30.0)).expect("the left panel"); + let f = fold(b, Some(base), amount, TOL).expect("folds"); + let h = f.hinges.iter().find(|h| !h.tree).expect("a closing hinge").clone(); + (h.closes, h.gap) + }; + let (closes, at) = gap(0.0, 1.0); + assert!(closes && at < 1e-9, "{at}"); + // A small lean opens it by more than the 0.1 pt tolerance but less than 0.5% of its 40 pt + // length (0.2 pt): still closed. + let (closes, at) = gap(0.1, 1.0); + assert!(closes && at > TOL && at <= 0.2, "{at}"); + // A larger lean opens it past both, flat or folded. + for amount in [0.0, 1.0] { + let (closes, at) = gap(1.0, amount); + assert!(!closes && at > 0.2, "{amount}: {at}"); + } +} + +#[test] +fn a_panel_no_hinge_joins_stays_flat_where_it_is() { + let lines = vec![ + cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1), + crease((50.0, 49.95), (50.0, 50.0), 2), + ]; + let (b, _) = check(&lines); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (2, 0)); + let f = fold(b, None, 1.0, TOL).expect("folds"); + let loose = 1 - f.base; + assert_eq!(f.panels[loose].parent, None); + assert_eq!(f.panels[loose].pose, Pose::IDENTITY); + assert_eq!(f.order, vec![f.base, loose], "the loose panel comes last"); +} + +#[test] +fn a_child_of_a_notched_panel_folds_away_from_the_print() { + // The base is an L: a 30 × 140 strip with an 80 pt arm along its top running right to x = 300. + // The child, below the arm past a 2 pt slot, is hinged to the strip along x = 30. + let lines = vec![ + cut(&[(0.0, 0.0), (300.0, 0.0), (300.0, 80.0), (30.0, 80.0), (30.0, 82.0), (300.0, 82.0), (300.0, 140.0), (0.0, 140.0)], 1), + crease((30.0, 82.0), (30.0, 140.0), 2), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(15.0, 110.0)).expect("the L"); + let child = panel_at(b, p(150.0, 110.0)).expect("the child"); + // The L's inside point lies in its arm, on the child's side of the hinge's line. + let inside = b.panels[base].point_inside().expect("a point inside"); + assert!(inside.x > 30.0, "{inside:?}"); + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::PartialCut, 1.0)] { + let mut lines = lines.clone(); + lines[1].kind = kind; + let (b, _) = check(&lines); + let f = fold(&b[0], Some(base), 1.0, TOL).expect("folds"); + let placed = f.panels[child].pose.place(p(150.0, 110.0)); + assert!(placed[2] * sign > 99.0, "{kind:?}: {placed:?}"); + } +} + +#[test] +fn a_lid_folded_over_the_base_crosses_the_taller_wall_opposite() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. + let lines = vec![ + cut(&[(0.0, 0.0), (310.0, 0.0), (310.0, 50.0), (0.0, 50.0)], 1), + crease((120.0, 0.0), (120.0, 50.0), 2), + crease((150.0, 0.0), (150.0, 50.0), 3), + crease((250.0, 0.0), (250.0, 50.0), 4), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(200.0, 25.0)).expect("the base panel"); + let (lid, wall) = (panel_at(b, p(60.0, 25.0)).unwrap(), panel_at(b, p(280.0, 25.0)).unwrap()); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + assert_eq!(f.collisions, vec![(lid.min(wall), lid.max(wall))]); + // Half folded, nothing crosses yet. + assert!(fold(b, Some(base), 0.4, TOL).expect("folds").collisions.is_empty()); +} + +#[test] +fn the_base_is_the_panel_under_a_point_and_the_same_in_any_input_order() { + let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), crease((50.0, 0.0), (50.0, 60.0), 2)]; + let (b, _) = check(&lines); + assert_eq!(panel_at(&b[0], p(500.0, 500.0)), None, "a point outside every panel"); + let right = panel_at(&b[0], p(75.0, 30.0)).expect("the right panel"); + assert_eq!(fold(&b[0], Some(right), 1.0, TOL).expect("folds").base, right); + let mut reversed = lines.clone(); + reversed.reverse(); + let (r, _) = check(&reversed); + for blank in [&b[0], &r[0]] { + let f = fold(blank, None, 1.0, TOL).expect("folds"); + // Equal panels: the leftmost wins. + assert_eq!(blank.panels[f.base].outline.bounds().map(|r| r.x0.round()), Some(0.0)); + } + assert!(fold(&b[0], Some(9), 1.0, TOL).is_none(), "no panel 9"); + assert!(fold(&b[0], None, 1.5, TOL).is_none(), "past 1"); + assert!(fold(&b[0], None, f64::NAN, TOL).is_none()); + assert!(fold(&Blank::default(), None, 1.0, TOL).is_none(), "no panels"); +} + +#[test] +fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { + let (b, _) = check(&two_panels(LineKind::PartialCut, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, -90.0); + let (b, _) = check(&two_panels(LineKind::Perforation, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, 90.0); + // A crease and a short partial cut on one line: the crease is the longer piece. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + line(LineKind::PartialCut, &[(60.0, 0.0), (60.0, 10.0)], false, 2), + crease((60.0, 10.0), (60.0, 60.0), 3), + ]; + let (b, _) = check(&lines); + assert_eq!(b[0].hinges.len(), 1); + assert_eq!(b[0].hinges[0].angle, 90.0); } diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 54f233d945..4a9303efdd 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -4,7 +4,8 @@ //! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that //! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu //! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each -//! with a Select button; the list is kept until the document changes. +//! with a Select button; the list is kept until the document changes. Its Fold Preview button, like +//! the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`). use std::sync::{Arc, Weak}; @@ -25,6 +26,8 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that shows the Fold Preview window. +pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. pub const ROLES: &[(&str, &str)] = &[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")]; @@ -46,6 +49,8 @@ pub fn menu() -> Vec<Item> { make("Make Perforation Line", "perforation"), Item::Sep, Item::Cmd("Check Fold Lines", CHECK, Value::Null), + Item::Sep, + Item::Cmd("Fold Preview", PREVIEW, json!({})), ] } @@ -147,6 +152,11 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::flat_button(ui, tl!("Check"), width).clicked() { run_check(app, ui.ctx(), json!({})); } + if widgets::flat_button(ui, tl!("Fold Preview"), width).clicked() + && let Err(e) = app.run(PREVIEW, json!({})) + { + app.status(e); + } let Some(checked) = last_check(app, ui.ctx()) else { return }; ui.add_space(4.0); dim_label(ui, &crate::i18n::msg(&checked.summary())); @@ -272,5 +282,7 @@ pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } +pub mod preview; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs new file mode 100644 index 0000000000..a85b8650d9 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -0,0 +1,702 @@ +//! The Fold Preview window: the document's blank folded into its 3D shape +//! ([`vectorcraft_three_d::fold::fold`]), with the printed art on the outside of each panel and the +//! board's inside color on the back, drawn by [`vectorcraft_three_d::fold::raster::render`]. +//! +//! The window folds the blank that the document's shown fold lines make, about its largest panel +//! or the panel the user double-clicked. Its print is a raster of the document with the fold lines +//! and the layers that do not print left out ([`vectorcraft_engine::cmd::print_hidden`]), rendered +//! once per document revision, off the UI thread on native builds ([`crate::thumb_worker`]), and +//! sampled through each panel's projective map when the fold, the view or the print changes. Dragging turns the view, a Shift-drag +//! keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a +//! panel makes it the base, and the arrow keys turn the view by 5° when it has the keyboard focus. +//! The settings live in `UiState::fold_preview` (`ui.inspect`); `ui.foldPreview` sets them. + +use std::sync::Arc; + +use egui::{Color32, Rect, Sense, Ui, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect as DRect}; +use vectorcraft_three_d::fold::raster::{self, Camera, Image, MAX_PIXELS, MAX_SIDE, Print}; +use vectorcraft_three_d::fold::{Blank, Folded, fold, pick}; + +use crate::VectorcraftApp; +use crate::thumb_worker::{Settle, ThumbWorker}; +use crate::widgets::{self, dim_label}; + +/// The window's id (`window.panel {panel: "foldPreview"}`). +pub const ID: &str = "foldPreview"; + +/// The view presets: label, id, the turn about x (the top toward the viewer) and about y (the +/// right side toward the viewer), in degrees. +pub const VIEWS: [(&str, &str, f64, f64); 7] = [ + ("Front", "front", 0.0, 0.0), + ("Back", "back", 0.0, 180.0), + ("Left", "left", 0.0, -90.0), + ("Right", "right", 0.0, 90.0), + ("Top", "top", 90.0, 0.0), + ("Bottom", "bottom", -90.0, 0.0), + ("Three-Quarter", "threeQuarter", 25.0, 35.0), +]; + +/// The tolerance the window folds with (points), as Check Fold Lines' default. +const TOLERANCE: f64 = 0.1; +/// The share of the view's shorter side the folded blank fills at a zoom of 1. +const FIT: f64 = 0.45; +/// The print raster's longest side, in pixels, and the fewest pixels it gives a point. +const PRINT_SIDE: f64 = 2048.0; +/// Degrees the view turns for each point dragged, and for each arrow key press. +const DRAG_TURN: f64 = 0.5; +const KEY_TURN: f64 = 5.0; + +/// The window's settings (kept with the UI state). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Settings { + /// How far the blank is folded: 0 flat, 1 every hinge at its angle. + pub amount: f64, + /// The view's turn, in degrees (see [`VIEWS`]). + pub rotate_x: f64, + pub rotate_y: f64, + /// The zoom: 1 fits the folded blank in the view. + pub zoom: f64, + /// How far the view is moved, in points. + pub pan: [f64; 2], + /// The field of view in degrees; 0 for none. + pub perspective: f64, + /// The board's inside color: `#rrggbb` or the name of a swatch. + pub inside: String, + /// Draw the fold lines on the print. + pub show_fold_lines: bool, + /// The base panel: the one under this point (document coordinates); the largest when `None`. + pub base: Option<[f64; 2]>, +} + +impl Default for Settings { + fn default() -> Self { + let (_, _, rotate_x, rotate_y) = VIEWS[6]; + Self { + amount: 1.0, + rotate_x, + rotate_y, + zoom: 1.0, + pan: [0.0; 2], + perspective: 0.0, + inside: "#ffffff".into(), + show_fold_lines: false, + base: None, + } + } +} + +impl Settings { + /// The view preset these settings show, if any. + fn view(&self) -> Option<&'static (&'static str, &'static str, f64, f64)> { + VIEWS.iter().find(|v| (v.2 - self.rotate_x).abs() < 1e-9 && (v.3 - self.rotate_y).abs() < 1e-9) + } + + /// These settings with every value in the range `ui.foldPreview` allows: saved UI state is read + /// as it was stored. A value that is not a number takes its default. + fn clamped(mut self) -> Self { + let within = |v: f64, lo: f64, hi: f64, or: f64| if v.is_finite() { v.clamp(lo, hi) } else { or }; + let turn = |v: f64| if (-180.0..=180.0).contains(&v) { v } else { wrapped(v) }; + let fresh = Settings::default(); + self.amount = within(self.amount, 0.0, 1.0, fresh.amount); + self.zoom = within(self.zoom, 0.1, 8.0, fresh.zoom); + self.perspective = within(self.perspective, 0.0, 160.0, fresh.perspective); + (self.rotate_x, self.rotate_y) = (turn(self.rotate_x), turn(self.rotate_y)); + self.pan = self.pan.map(|v| if v.is_finite() { v } else { 0.0 }); + self.base = self.base.filter(|b| b.iter().all(|v| v.is_finite())); + self + } +} + +/// `angle` (degrees) brought into -180 to 180. +fn wrapped(angle: f64) -> f64 { + let a = (angle + 180.0).rem_euclid(360.0) - 180.0; + if a.is_finite() { a } else { 0.0 } +} + +/// What the print raster shows: the document, its revision, whether the fold lines are drawn, and +/// the region and size. +#[derive(Clone, Copy, Debug, PartialEq)] +struct PrintKey { + uid: u64, + revision: u64, + fold_lines: bool, + region: [u64; 4], + width: u32, + height: u32, +} + +/// The last frame drawn: its size in pixels and how long the fold and the drawing took (ms). +#[derive(Clone, Copy, Debug, Default)] +struct Frame { + width: u32, + height: u32, + fold_ms: f64, + draw_ms: f64, +} + +/// A document's blanks and whether its fold lines have an error, by (uid, revision). +type Blanks = ((u64, u64), Arc<Vec<Blank>>, bool); + +/// What a fold folds: the document (uid, revision), the blank, the base panel and the amount's bits. +type FoldKey = (u64, u64, usize, usize, u64); + +/// What the last image shows: the fold, the camera, the inside color and the print. +#[derive(Clone, Copy, Debug, PartialEq)] +struct DrawKey { + fold: FoldKey, + camera: Camera, + inside: [u8; 4], + print: Option<PrintKey>, +} + +#[derive(Default)] +struct Cache { + blanks: Option<Blanks>, + /// The last fold, what it folds and how long it took (ms). + folded: Option<(FoldKey, Arc<Folded>, f64)>, + /// What the texture shows. + drawn: Option<DrawKey>, + /// Folds worked out and images rendered (tests count them). + folds: u64, + renders: u64, + /// The print shown and what it shows. + print: Option<(PrintKey, Arc<Print>)>, + /// Renders the print off the UI thread (None: on this thread). + worker: Option<ThumbWorker<(), PrintKey>>, + worker_started: bool, + pending: Option<PrintKey>, + settle: Settle, + tex: Option<egui::TextureHandle>, + /// The last frame's image, for double-click picking, and the screen rect it filled. + image: Option<(Image, Rect)>, + frame: Option<Frame>, + /// Prints rendered (tests count them). + prints: u64, +} + +thread_local! { + static CACHE: crate::graphics::TexCache<Cache> = crate::graphics::TexCache::default(); + static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); +} + +/// The board's inside color (straight RGBA) for `inside`: `#rrggbb`, or a swatch of `d` with a +/// plain color; `None` for anything else. +fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> { + if inside.starts_with('#') { + return vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)); + } + match &d.swatch(inside)?.paint { + vectorcraft_color::Paint::Solid { color, .. } => Some(color.to_rgba8(1.0)), + _ => None, + } +} + +/// The document rect a print of `blank` covers: its panels' bounds, with a point to spare. +fn print_region(blank: &Blank) -> Option<DRect> { + let r = blank.panels.iter().filter_map(|p| p.outline.bounds()).reduce(|a, b| a.union(b))?; + let r = r.inflate(1.0, 1.0); + (r.width() > 0.0 && r.height() > 0.0 && r.is_finite()).then_some(r) +} + +/// The pixel size of the print of `region`: its longest side [`PRINT_SIDE`]. +fn print_size(region: DRect) -> (u32, u32, f64) { + let scale = PRINT_SIDE / region.width().max(region.height()); + let side = |len: f64| ((len * scale).ceil() as u32).clamp(1, MAX_SIDE); + (side(region.width()), side(region.height()), scale) +} + +impl Cache { + /// The blanks of document `uid` at `revision`, worked out again only when it changed. + fn blanks(&mut self, uid: u64, revision: u64, d: &vectorcraft_engine::doc::Document) -> (Arc<Vec<Blank>>, bool) { + if let Some((key, blanks, errors)) = &self.blanks + && *key == (uid, revision) + { + return (blanks.clone(), *errors); + } + let (blanks, issues) = vectorcraft_engine::cmd::fold_source(d); + let errors = issues.iter().any(|i| i.code.is_error()); + let blanks = Arc::new(blanks); + self.blanks = Some(((uid, revision), blanks.clone(), errors)); + (blanks, errors) + } + + /// `blank` folded about `panel` by `amount` (what `key` names), worked out again only when the + /// key changed, and how long that took (ms). + fn fold(&mut self, key: FoldKey, blank: &Blank, panel: usize, amount: f64) -> Option<(Arc<Folded>, f64)> { + if let Some((k, f, ms)) = &self.folded + && *k == key + { + return Some((f.clone(), *ms)); + } + let t0 = crate::now_ms(); + let f = Arc::new(fold(blank, Some(panel), amount, TOLERANCE)?); + let ms = crate::now_ms() - t0; + self.folded = Some((key, f.clone(), ms)); + self.folds += 1; + Some((f, ms)) + } + + /// Bring the print up to `key`: on the worker when there is one, else here, and not before the + /// document has settled unless there is no print of it yet. + fn update_print(&mut self, ctx: &egui::Context, doc: &Arc<vectorcraft_engine::doc::Document>, key: PrintKey, region: DRect, scale: f64) { + if !self.worker_started { + self.worker_started = true; + self.worker = ThumbWorker::spawn(ctx, "fold-preview"); + } + let done = match self.worker.as_ref().map(ThumbWorker::poll) { + Some(Some(done)) => done, + Some(None) => { + (self.worker, self.pending) = (None, None); + vec![] + } + None => vec![], + }; + for d in done { + if self.pending == Some(d.key) { + self.pending = None; + } + if let Some(img) = d.img { + self.keep_print(d.key, img); + } + } + let shown = self.print.as_ref().map(|(k, _)| *k); + if shown == Some(key) || self.pending == Some(key) { + return; + } + let have = shown.is_some_and(|k| k.uid == key.uid); + if have && !self.settle.settled(ctx, key.uid, key.revision, ctx.input(|i| i.time)) { + return; + } + let opts = vectorcraft_render::RenderOptions { + skip_templates: true, + image_mips: true, + hidden: vectorcraft_engine::cmd::print_hidden(doc, key.fold_lines), + ..Default::default() + }; + if let Some(w) = &self.worker { + let (doc, opts) = (doc.clone(), opts.clone()); + if w.submit((), key, Box::new(move |r| Some(r.render_region_with(&doc, region, scale, &opts)))) { + self.pending = Some(key); + return; + } + self.worker = None; + } + let img = RENDERER.with(|r| r.borrow_mut().render_region_with(doc, region, scale, &opts)); + self.keep_print(key, img); + } + + /// The print to draw for `want`: the one shown when it is of the same document, blank region and + /// Show Fold Lines setting (an older revision while the new one renders), else none. + fn print_for(&self, want: &PrintKey) -> Option<(PrintKey, Arc<Print>)> { + let same = |k: &PrintKey| (k.uid, k.fold_lines, k.region) == (want.uid, want.fold_lines, want.region); + self.print.as_ref().filter(|(k, _)| same(k)).map(|(k, p)| (*k, p.clone())) + } + + fn keep_print(&mut self, key: PrintKey, img: vectorcraft_render::Rendered) { + let region = + DRect::new(f64::from_bits(key.region[0]), f64::from_bits(key.region[1]), f64::from_bits(key.region[2]), f64::from_bits(key.region[3])); + if let Some(print) = Print::new(region, img.width, img.height, img.pixels) { + self.print = Some((key, Arc::new(print))); + self.prints += 1; + } + } +} + +/// `ui.foldPreview {amount?, view?, rotateX?, rotateY?, zoom?, perspective?, inside?, +/// showFoldLines?, base?}`: set the window's settings, show it, and answer with them and the last +/// frame's size and times. A value of the wrong kind or out of range is an error, and nothing is +/// set. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { + let mut set = app.ui.fold_preview.clone(); + let number = |key: &str, lo: f64, hi: f64| -> Result<Option<f64>, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_f64() { + Some(n) if (lo..=hi).contains(&n) => Ok(Some(n)), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + }, + } + }; + if let Some(a) = number("amount", 0.0, 1.0)? { + set.amount = a; + } + match p.get("view") { + None | Some(Value::Null) => {} + Some(v) => { + let (_, _, x, y) = v + .as_str() + .and_then(|v| VIEWS.iter().find(|view| view.1 == v)) + .ok_or_else(|| format!("`view` must be one of {}", VIEWS.iter().map(|v| v.1).collect::<Vec<_>>().join(", ")))?; + (set.rotate_x, set.rotate_y) = (*x, *y); + } + } + if let Some(x) = number("rotateX", -180.0, 180.0)? { + set.rotate_x = x; + } + if let Some(y) = number("rotateY", -180.0, 180.0)? { + set.rotate_y = y; + } + if let Some(z) = number("zoom", 0.1, 8.0)? { + set.zoom = z; + } + if let Some(v) = number("perspective", 0.0, 160.0)? { + set.perspective = v; + } + match p.get("inside") { + None | Some(Value::Null) => {} + Some(v) => { + let inside = v.as_str().unwrap_or_default(); + let known = app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some() + || (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some()); + if !known { + return Err(format!("`inside` must be #rrggbb or the name of a swatch with a plain color, not {v}")); + } + set.inside = inside.to_string(); + } + } + match p.get("showFoldLines") { + None | Some(Value::Null) => {} + Some(v) => set.show_fold_lines = v.as_bool().ok_or("`showFoldLines` must be true or false")?, + } + match p.get("base") { + None => {} + Some(Value::Null) => set.base = None, + Some(v) => { + let a = v.as_array().filter(|a| a.len() == 2); + let xy: Option<Vec<f64>> = a.map(|a| a.iter().filter_map(Value::as_f64).filter(|n| n.is_finite()).collect()); + let Some(&[x, y]) = xy.as_deref() else { return Err("`base` must be a point: [x, y], or null".into()) }; + let blanks = app.session.active().map(|st| vectorcraft_engine::cmd::fold_source(&st.doc).0).unwrap_or_default(); + if pick(&blanks, Some(Point::new(x, y))).is_none() { + return Err("`base` is in no panel".into()); + } + set.base = Some([x, y]); + } + } + if p.get("view").is_some_and(|v| !v.is_null()) || p.get("zoom").is_some_and(|v| !v.is_null()) { + set.pan = [0.0; 2]; + } + app.ui.fold_preview = set; + crate::panel_docking::reveal_panel(app, ID)?; + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + Ok(state(app)) +} + +/// The window's settings and the last frame's size and times. +fn state(app: &VectorcraftApp) -> Value { + let frame = CACHE.with(|c| c.borrow().frame); + let mut out = serde_json::to_value(&app.ui.fold_preview).unwrap_or_default(); + if let Some(o) = out.as_object_mut() { + o.insert( + "frame".into(), + frame.map_or(Value::Null, |f| json!({"width": f.width, "height": f.height, "foldMs": f.fold_ms, "drawMs": f.draw_ms})), + ); + } + out +} + +/// The toolbar: the view presets, Perspective, Inside, Show Fold Lines and Reset. +fn toolbar(app: &VectorcraftApp, ui: &mut Ui, set: &mut Settings) { + ui.horizontal_wrapped(|ui| { + let labels: Vec<&str> = VIEWS.iter().map(|v| v.0).collect(); + let current = set.view().map_or("", |v| v.0); + if let Some(i) = widgets::dropdown_named(ui, "fold-preview-view", Some(tl!("View")), current, &labels, 120.0) + && let Some(&(_, _, x, y)) = VIEWS.get(i) + { + (set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]); + } + let swatches: Vec<String> = app.session.active().map_or_else(Vec::new, |st| { + st.doc.swatches.iter().filter(|s| matches!(s.paint, vectorcraft_color::Paint::Solid { .. })).map(|s| s.name.clone()).collect() + }); + let mut names: Vec<&str> = vec![tl!("White")]; + names.extend(swatches.iter().map(String::as_str)); + let shown = if set.inside == "#ffffff" { tl!("White") } else { set.inside.as_str() }; + ui.label(tl!("Inside")); + if let Some(i) = widgets::dropdown_names_named(ui, "fold-preview-inside", Some(tl!("Inside")), shown, &names, 110.0) { + set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_else(|| "#ffffff".into()); + } + if widgets::check(ui, tl!("Show Fold Lines"), set.show_fold_lines, true) { + set.show_fold_lines = !set.show_fold_lines; + } + if widgets::flat_button_fit(ui, tl!("Reset"), 48.0).clicked() { + let fresh = Settings::default(); + (set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective) = (fresh.rotate_x, fresh.rotate_y, 1.0, [0.0; 2], 0.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Perspective")); + widgets::slider(ui, egui::Slider::new(&mut set.perspective, 0.0..=160.0).suffix("°").fixed_decimals(0)); + }); +} + +/// The Fold and Zoom sliders. +fn sliders(ui: &mut Ui, set: &mut Settings) { + ui.horizontal(|ui| { + ui.label(tl!("Fold")); + let mut percent = set.amount * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 0.0..=100.0).suffix("%").fixed_decimals(0)).changed() { + set.amount = (percent / 100.0).clamp(0.0, 1.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Zoom")); + let mut percent = set.zoom * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 10.0..=800.0).suffix("%").fixed_decimals(0).logarithmic(true)).changed() { + set.zoom = (percent / 100.0).clamp(0.1, 8.0); + } + }); +} + +/// Turns, moves and zooms the view with the pointer, the wheel and the arrow keys, and picks the +/// base panel of `blank` (the blank `key` folds) on a double-click. +fn interact(ui: &Ui, response: &egui::Response, set: &mut Settings, blank: Option<(&Blank, FoldKey)>) { + if response.clicked() || response.drag_started() { + response.request_focus(); + } + let (shift, space) = ui.input(|i| (i.modifiers.shift, i.key_down(egui::Key::Space))); + let delta = response.drag_delta(); + if delta != egui::Vec2::ZERO { + if response.dragged_by(egui::PointerButton::Middle) || (space && response.dragged_by(egui::PointerButton::Primary)) { + set.pan[0] += f64::from(delta.x); + set.pan[1] += f64::from(delta.y); + } else if response.dragged_by(egui::PointerButton::Primary) { + let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y)); + if shift { + if dx.abs() >= dy.abs() { + dy = 0.0; + } else { + dx = 0.0; + } + } + set.rotate_y = wrapped(set.rotate_y + dx * DRAG_TURN); + set.rotate_x = wrapped(set.rotate_x + dy * DRAG_TURN); + } + } + if response.hovered() { + let scroll = f64::from(ui.input(|i| i.smooth_scroll_delta.y + (i.zoom_delta() - 1.0) * 200.0)); + if scroll != 0.0 { + set.zoom = (set.zoom * (scroll * 0.002).exp()).clamp(0.1, 8.0); + } + } + if response.has_focus() { + // The view keeps the arrow keys, so they turn it rather than move the focus on. + ui.memory_mut(|m| { + m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + let presses = |key| ui.input_mut(|i| i.count_and_consume_key(egui::Modifiers::NONE, key)) as f64 * KEY_TURN; + let (left, right, up, down) = + (presses(egui::Key::ArrowLeft), presses(egui::Key::ArrowRight), presses(egui::Key::ArrowUp), presses(egui::Key::ArrowDown)); + if left + right + up + down > 0.0 { + set.rotate_y = wrapped(set.rotate_y + right - left); + set.rotate_x = wrapped(set.rotate_x + down - up); + } + } + if response.double_clicked() + && let Some(pos) = response.interact_pointer_pos() + && let Some((blank, key)) = blank + { + // The image on screen is the last one drawn; its panel numbers are used only while it shows + // the same blank of the same document revision. + let picked = CACHE.with(|c| { + let c = c.borrow(); + let shown = c.drawn.map(|d| (d.fold.0, d.fold.1, d.fold.2)); + if shown != Some((key.0, key.1, key.2)) { + return None; + } + let (img, rect) = c.image.as_ref()?; + let x = (pos.x - rect.left()) / rect.width() * img.width as f32; + let y = (pos.y - rect.top()) / rect.height() * img.height as f32; + img.panel_at(x.max(0.0) as u32, y.max(0.0) as u32) + }); + if let Some(p) = picked.and_then(|i| blank.panels.get(i)).and_then(|p| p.point_inside()) { + set.base = Some([p.x, p.y]); + } + } +} + +/// The status line under the view, in English (shown translated). +fn status(blanks: usize, folded: Option<(&Blank, &Folded)>, errors: bool) -> Vec<String> { + let Some((blank, f)) = folded else { + return vec!["Check the fold lines first.".into()]; + }; + let mut out = vec![crate::i18n::fmt( + "Panels: {panels}, hinges: {hinges}", + &[("panels", &blank.panels.len().to_string()), ("hinges", &blank.hinges.len().to_string())], + )]; + if errors { + out.push("Check the fold lines first.".into()); + } + if blanks > 1 { + out.push(crate::i18n::fmt("Other blanks not shown: {count}", &[("count", &(blanks - 1).to_string())])); + } + if let Some(gap) = f.hinges.iter().filter(|h| !h.closes).map(|h| h.gap).reduce(f64::max) { + out.push(crate::i18n::fmt("A joint does not close by {gap} pt.", &[("gap", &format!("{gap:.1}"))])); + } + if !f.collisions.is_empty() { + out.push("Two panels pass through each other.".into()); + } + out +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(st) = app.session.active() else { + crate::panels::empty_state(ui, "box", tl!("No document"), tl!("Open a document to preview its folded shape.")); + return; + }; + let (uid, revision, doc) = (st.uid, st.revision, st.doc.clone()); + let mut set = app.ui.fold_preview.clone().clamped(); + toolbar(app, ui, &mut set); + let (blanks, errors) = CACHE.with(|c| c.borrow_mut().blanks(uid, revision, &doc)); + let base_point = set.base.map(|[x, y]| Point::new(x, y)); + let picked = pick(&blanks, base_point).or_else(|| pick(&blanks, None)); + let folded = picked.and_then(|(b, panel)| { + let blank = blanks.get(b)?; + let key = (uid, revision, b, panel, set.amount.to_bits()); + let (f, ms) = CACHE.with(|c| c.borrow_mut().fold(key, blank, panel, set.amount))?; + Some((blank, f, key, ms)) + }); + + let bottom = ui.spacing().interact_size.y * 3.0 + 12.0; + let size = vec2(ui.available_width().max(64.0), (ui.available_height() - bottom).max(64.0)); + let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag()); + let view_name = set.view().map_or("", |v| v.0); + response.widget_info(|| { + let mut info = egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Fold Preview")); + info.current_text_value = Some(crate::i18n::t(view_name).to_string()); + info + }); + interact(ui, &response, &mut set, folded.as_ref().map(|(b, _, key, _)| (*b, *key))); + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().rect_filled(rect, 2.0, t.pasteboard); + if let Some((blank, f, key, fold_ms)) = &folded { + draw(ui, rect, &doc, *key, blank, f, &set, *fold_ms); + } + if response.has_focus() { + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } + for line in status(blanks.len(), folded.as_ref().map(|(b, f, ..)| (*b, &**f)), errors) { + dim_label(ui, &crate::i18n::msg(&line)); + } + sliders(ui, &mut set); + if set != app.ui.fold_preview { + app.ui.fold_preview = set; + } +} + +/// Draws `blank` folded as `f` (the fold `key` names) into `rect`, with the print of `doc`. The image +/// is rendered again only when the fold, the view, the inside color or the print changed. +#[allow(clippy::too_many_arguments)] +fn draw(ui: &Ui, rect: Rect, doc: &Arc<vectorcraft_engine::doc::Document>, key: FoldKey, blank: &Blank, f: &Folded, set: &Settings, fold_ms: f64) { + // Pixels per point of the view, lowered when the window has more pixels than the view may have + // in all or along either side, so the image keeps the window's proportions. + let (w, h) = (f64::from(rect.width()), f64::from(rect.height())); + let mut ppp = f64::from(ui.ctx().pixels_per_point()); + let area = w * h * ppp * ppp; + if area > f64::from(MAX_PIXELS) { + ppp *= (f64::from(MAX_PIXELS) / area).sqrt(); + } + ppp = ppp.min(f64::from(MAX_SIDE) / w.max(h).max(1.0)); + let width = ((w * ppp).floor() as u32).clamp(1, MAX_SIDE); + let height = ((h * ppp).floor() as u32).clamp(1, MAX_SIDE); + let Some((lo, hi)) = raster::bounds(blank, f) else { return }; + let center = [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0, (lo[2] + hi[2]) / 2.0]; + let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() / 2.0; + let mut fit = FIT * f64::from(width.min(height)) / radius.max(1e-6); + if set.perspective > 0.0 { + // The eye at two radii from the middle or farther, so at a zoom of 1 the whole blank is in + // front of it. + let focal = f64::from(width.min(height)) / 2.0 / (set.perspective.to_radians() / 2.0).tan(); + fit = fit.min(focal / (2.0 * radius.max(1e-6))); + } + let camera = Camera { + width, + height, + rotate_x: set.rotate_x, + rotate_y: set.rotate_y, + scale: fit * set.zoom, + pan: [set.pan[0] * ppp, set.pan[1] * ppp], + perspective: set.perspective, + center, + }; + let inside = inside_color(doc, &set.inside).unwrap_or([255; 4]); + // While the print of a new revision renders, the last one of the same blank and setting is + // drawn; a print of another document, blank or Show Fold Lines setting is not. + let print = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let region = print_region(blank)?; + let (pw, ph, scale) = print_size(region); + let pkey = PrintKey { + uid: key.0, + revision: key.1, + fold_lines: set.show_fold_lines, + region: [region.x0.to_bits(), region.y0.to_bits(), region.x1.to_bits(), region.y1.to_bits()], + width: pw, + height: ph, + }; + c.update_print(ui.ctx(), doc, pkey, region, scale); + c.print_for(&pkey) + }); + let draw_key = DrawKey { fold: key, camera, inside, print: print.as_ref().map(|(k, _)| *k) }; + let kept = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let Some(tex) = c.tex.as_ref().filter(|_| c.drawn == Some(draw_key)).map(|t| t.id()) else { return false }; + ui.painter().image(tex, rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + if let Some((_, at)) = &mut c.image { + *at = rect; + } + true + }); + if kept { + return; + } + let t0 = crate::now_ms(); + let scene = raster::Scene { blank, folded: f, print: print.as_ref().map(|(_, p)| &**p), inside, outside: [255; 4], camera }; + let Some(img) = raster::render(&scene) else { return }; + let draw_ms = crate::now_ms() - t0; + let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + c.drawn = Some(draw_key); + c.renders += 1; + match &mut c.tex { + Some(tex) => tex.set(color, egui::TextureOptions::LINEAR), + None => c.tex = Some(ui.ctx().load_texture("fold-preview", color, egui::TextureOptions::LINEAR)), + } + if let Some(tex) = &c.tex { + let uv = Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + ui.painter().image(tex.id(), rect, uv, Color32::WHITE); + } + c.frame = Some(Frame { width: img.width, height: img.height, fold_ms, draw_ms }); + c.image = Some((img, rect)); + }); +} + +#[cfg(test)] +pub(crate) fn prints_rendered() -> u64 { + CACHE.with(|c| c.borrow().prints) +} + +#[cfg(test)] +pub(crate) fn last_image() -> Option<Image> { + CACHE.with(|c| c.borrow().image.as_ref().map(|(i, _)| i.clone())) +} + +/// The folds worked out and the images rendered so far. +#[cfg(test)] +pub(crate) fn work_done() -> (u64, u64) { + CACHE.with(|c| (c.borrow().folds, c.borrow().renders)) +} + +/// The screen rect the last image filled. +#[cfg(test)] +pub(crate) fn last_rect() -> Option<Rect> { + CACHE.with(|c| c.borrow().image.as_ref().map(|(_, r)| *r)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs new file mode 100644 index 0000000000..9fdfb1972e --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -0,0 +1,489 @@ +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use std::sync::Arc; + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; + +use super::{Cache, ID, PrintKey, Settings, last_image, last_rect, prints_rendered, show, status, work_done}; +use crate::{VectorcraftApp, menus}; + +/// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each +/// side) and a red square printed on the base, nothing selected → (app, the red square's id). +fn app() -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = [ + path(&mut app, "M140 140 L240 140"), + path(&mut app, "M240 140 L240 240"), + path(&mut app, "M240 240 L140 240"), + path(&mut app, "M140 240 L140 140"), + ]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + let red = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("paint.setFill", json!({ "color": "#ff0000" })).unwrap(); + app.run("paint.setStroke", json!({ "none": true })).unwrap(); + app.run("object.arrange.sendToBack", json!({})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, red) +} + +/// Draws the window in a 520 × 440 frame, twice (egui lays out on the first). +fn frame(app: &mut VectorcraftApp) { + frame_at(app, 1.0); +} + +/// [`frame`] at `zoom` pixels per point. +fn frame_at(app: &mut VectorcraftApp, zoom: f32) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(zoom); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(520.0, 440.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } +} + +fn color_at(img: &vectorcraft_three_d::fold::raster::Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// The color at the middle of the window's last image. +fn middle(img: &vectorcraft_three_d::fold::raster::Image) -> [u8; 4] { + color_at(img, img.width / 2, img.height / 2) +} + +#[test] +fn the_menu_item_and_the_panel_button_show_the_window_and_a_second_run_keeps_it() { + let (mut app, _) = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Fold Preview").expect("listed"); + assert_eq!((item.command.as_deref(), &item.params), (Some("ui.foldPreview"), &json!({}))); + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "the window opens"); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "a second run leaves it open"); + let text = crate::tests_labels::painted_text(&mut app, super::super::show); + assert!(text.contains("Fold Preview"), "the Fold Lines panel has the button: {text}"); +} + +#[test] +fn ui_fold_preview_sets_the_window_and_refuses_bad_values() { + let (mut app, _) = app(); + let r = app + .run( + "ui.foldPreview", + json!({"amount": 0.5, "view": "top", "zoom": 2, "perspective": 40, "inside": "#00ff00", "showFoldLines": true, "base": [120, 190]}), + ) + .unwrap(); + let want = Settings { + amount: 0.5, + rotate_x: 90.0, + rotate_y: 0.0, + zoom: 2.0, + pan: [0.0; 2], + perspective: 40.0, + inside: "#00ff00".into(), + show_fold_lines: true, + base: Some([120.0, 190.0]), + }; + assert_eq!(app.ui.fold_preview, want); + assert_eq!(r["rotateX"], 90.0, "{r}"); + assert!(r.get("frame").is_some(), "{r}"); + app.run("ui.foldPreview", json!({"rotateX": -30, "rotateY": 170, "base": null})).unwrap(); + assert_eq!((app.ui.fold_preview.rotate_x, app.ui.fold_preview.rotate_y, app.ui.fold_preview.base), (-30.0, 170.0, None)); + let kept = app.ui.fold_preview.clone(); + for (p, want) in [ + (json!({"amount": 2}), "`amount` must be a number from 0 to 1"), + (json!({"amount": "half"}), "`amount` must be a number from 0 to 1"), + (json!({"view": "sideways"}), "`view` must be one of"), + (json!({"rotateX": 200}), "`rotateX` must be a number from -180 to 180"), + (json!({"zoom": 0}), "`zoom` must be a number from 0.1 to 8"), + (json!({"perspective": 170}), "`perspective` must be a number from 0 to 160"), + (json!({"inside": "no such swatch"}), "`inside` must be #rrggbb"), + (json!({"inside": 7}), "`inside` must be #rrggbb"), + (json!({"showFoldLines": "yes"}), "`showFoldLines` must be true or false"), + (json!({"base": [1, "2"]}), "`base` must be a point"), + (json!({"base": [5, 5]}), "`base` is in no panel"), + (json!({"amount": 0.2, "zoom": 99}), "`zoom` must be a number"), + ] { + let e = app.run("ui.foldPreview", p.clone()).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + assert_eq!(app.ui.fold_preview, kept, "{p} sets nothing"); + } + // A swatch with a plain color names the inside. + app.run("ui.foldPreview", json!({"inside": "White"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "White"); +} + +#[test] +fn the_window_draws_the_print_on_the_folded_panels_and_the_inside_on_their_backs() { + let (mut app, _) = app(); + // Flat, from the front: the base's print, red, fills the middle. + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let before = prints_rendered(); + frame(&mut app); + assert!(prints_rendered() > before, "the print is rendered on this thread without a worker"); + let img = last_image().expect("a frame"); + let [r, g, b, a] = middle(&img); + assert!(r > 150 && g < 40 && b < 40 && a == 255, "red print: {:?}", [r, g, b, a]); + let state = app.run("ui.foldPreview", json!({})).unwrap(); + assert_eq!((state["frame"]["width"].as_u64(), state["frame"]["height"].as_u64()), (Some(u64::from(img.width)), Some(u64::from(img.height)))); + // From the back, the base's inside shows in the inside color. + app.run("ui.foldPreview", json!({"view": "back", "inside": "#00ff00"})).unwrap(); + frame(&mut app); + let [r, g, b, _] = middle(&last_image().expect("a frame")); + assert!(r < 40 && g > 150 && b < 40, "green inside: {:?}", [r, g, b]); + // Folded and seen from the front, the walls stand edge on: the base fills the same place. + app.run("ui.foldPreview", json!({"amount": 1, "view": "front"})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let [r, ..] = middle(&img); + assert!(r > 150, "the base still shows its print: {:?}", middle(&img)); + // The same print is not rendered again while the document does not change. + let prints = prints_rendered(); + frame(&mut app); + assert_eq!(prints_rendered(), prints); +} + +#[test] +fn a_wide_perspective_still_fits_the_whole_folded_blank_in_the_view() { + let (mut app, _) = app(); + // Without perspective, the base and the two walls behind it that face the viewer show. + let mut flat = None; + for perspective in [0, 60, 160] { + app.run("ui.foldPreview", json!({"amount": 1, "view": "threeQuarter", "zoom": 1, "perspective": perspective})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let mut shown: Vec<usize> = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter_map(|(x, y)| img.panel_at(x, y)).collect(); + shown.sort_unstable(); + shown.dedup(); + let flat = flat.get_or_insert_with(|| shown.clone()); + assert_eq!(flat.len(), 3); + assert_eq!(&shown, flat, "{perspective}°: the same panels show"); + let edge = (0..img.width).flat_map(|x| [(x, 0), (x, img.height - 1)]).chain((0..img.height).flat_map(|y| [(0, y), (img.width - 1, y)])); + assert!(edge.into_iter().all(|(x, y)| img.panel_at(x, y).is_none()), "{perspective}°: nothing reaches the edge of the view"); + } +} + +#[test] +fn a_window_with_more_pixels_than_the_view_may_have_is_drawn_smaller() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + frame_at(&mut app, 8.0); + let img = last_image().expect("a frame"); + assert!(u64::from(img.width) * u64::from(img.height) <= u64::from(vectorcraft_three_d::fold::raster::MAX_PIXELS), "{}×{}", img.width, img.height); + assert!(img.width > 1000, "still sharper than one pixel a point: {}", img.width); + let [r, ..] = middle(&img); + assert!(r > 150, "the base's print shows: {:?}", middle(&img)); +} + +#[test] +fn the_print_leaves_out_the_fold_lines_unless_they_are_shown() { + let (mut app, red) = app(); + // Without the red square, the base's middle shows the board with no art; with a crease drawn + // across the middle and the fold lines shown, the crease's color shows there. + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let mid = app.run("path.create", json!({ "d": "M140 190 L240 190" })).unwrap()["id"].as_u64().unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": [mid] })).unwrap(); + app.run("select.set", json!({ "ids": [mid] })).unwrap(); + app.run("stroke.set", json!({ "weight": 20 })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front", "zoom": 1})).unwrap(); + frame(&mut app); + let plain = middle(&last_image().expect("a frame")); + app.run("ui.foldPreview", json!({"showFoldLines": true})).unwrap(); + frame(&mut app); + let lined = middle(&last_image().expect("a frame")); + assert_ne!(plain, lined, "the crease shows only with Show Fold Lines on"); + assert!(plain[0] > 200 && plain[1] > 200 && plain[2] > 200, "the board is white where the print has no art: {plain:?}"); +} + +#[test] +fn the_window_says_when_there_is_nothing_to_fold() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Check the fold lines first."), "{text}"); + let mut none = VectorcraftApp::new(Session::new(), Default::default()); + let text = crate::tests_labels::painted_text(&mut none, show); + assert!(text.contains("Open a document to preview its folded shape."), "{text}"); +} + +#[test] +fn the_settings_are_kept_with_the_ui_state() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0.25, "view": "left"})).unwrap(); + let saved: Value = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(saved["fold_preview"]["amount"], 0.25, "{}", saved["fold_preview"]); + let back: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(back.fold_preview, app.ui.fold_preview); +} + +#[test] +fn saved_settings_out_of_range_are_brought_into_range() { + let (mut app, _) = app(); + app.ui.fold_preview = Settings { + amount: 3.0, + rotate_x: 200.0, + rotate_y: 180.0, + zoom: 0.0, + pan: [f64::NAN, 4.0], + perspective: -5.0, + base: Some([f64::INFINITY, 0.0]), + ..Settings::default() + }; + frame(&mut app); + let set = &app.ui.fold_preview; + assert_eq!( + (set.amount, set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective, set.base), + (1.0, -160.0, 180.0, 0.1, [0.0, 4.0], 0.0, None) + ); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Check the fold lines first."), "the blank folds: {text}"); + assert!(last_image().is_some(), "and is drawn"); +} + +/// A window kept open over frames, as the app draws it. +struct View { + ctx: egui::Context, + time: f64, +} + +impl View { + fn new(app: &mut VectorcraftApp) -> Self { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut v = View { ctx, time: 0.0 }; + v.idle(app); + v + } + + fn step(&mut self, app: &mut VectorcraftApp, events: Vec<Event>, modifiers: Modifiers) { + self.time += 0.05; + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(520.0, 440.0)); + let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect(); + let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } + + fn idle(&mut self, app: &mut VectorcraftApp) { + for _ in 0..3 { + self.step(app, vec![], Modifiers::NONE); + } + } + + /// Presses `button` at `at`, drags by `by` in four steps and lets go, holding `modifiers`. + fn drag(&mut self, app: &mut VectorcraftApp, at: Pos2, by: egui::Vec2, button: PointerButton, modifiers: Modifiers) { + let press = |pos, pressed| Event::PointerButton { pos, button, pressed, modifiers }; + self.step(app, vec![Event::PointerMoved(at)], modifiers); + self.step(app, vec![press(at, true)], modifiers); + for k in 1..=4 { + self.step(app, vec![Event::PointerMoved(at + by * (k as f32 / 4.0))], modifiers); + } + self.step(app, vec![press(at + by, false)], modifiers); + self.idle(app); + } + + fn click(&mut self, app: &mut VectorcraftApp, at: Pos2) { + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + self.step(app, vec![Event::PointerMoved(at)], Modifiers::NONE); + self.step(app, vec![press(true)], Modifiers::NONE); + self.step(app, vec![press(false)], Modifiers::NONE); + } + + fn key(&mut self, app: &mut VectorcraftApp, key: egui::Key) { + let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + self.step(app, vec![press], Modifiers::NONE); + self.step(app, vec![], Modifiers::NONE); + } +} + +/// The app showing the tray flat from the front, in a [`View`], and the middle of the view. +fn front_view() -> (VectorcraftApp, View, Pos2) { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let view = View::new(&mut app); + let at = last_rect().expect("the view is drawn").center(); + (app, view, at) +} + +#[test] +fn a_drag_turns_the_view_and_a_shift_drag_keeps_to_one_axis() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_y <= 20.0 + 1e-9, "{set:?}"); + assert!(set.rotate_x > 2.0 && set.rotate_x <= 10.0 + 1e-9, "{set:?}"); + app.run("ui.foldPreview", json!({"view": "front"})).unwrap(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::SHIFT); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_x == 0.0, "only the larger move turns the view: {set:?}"); +} + +#[test] +fn a_middle_drag_moves_the_view_and_the_wheel_zooms_it() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(30.0, -10.0), PointerButton::Middle, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.pan[0] > 0.0 && set.pan[1] < 0.0, "{set:?}"); + assert_eq!((set.rotate_x, set.rotate_y), (0.0, 0.0), "the view does not turn"); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 60.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }; + view.step(&mut app, vec![Event::PointerMoved(at), wheel], Modifiers::NONE); + for _ in 0..20 { + view.step(&mut app, vec![], Modifiers::NONE); + } + assert!(app.ui.fold_preview.zoom > 1.05, "{:?}", app.ui.fold_preview); +} + +#[test] +fn the_arrow_keys_turn_the_focused_view_and_keep_the_focus() { + let (mut app, mut view, at) = front_view(); + view.click(&mut app, at); + view.idle(&mut app); + // Up first: the toolbar is above the view, where the focus would go if the view let it. + view.key(&mut app, egui::Key::ArrowUp); + view.key(&mut app, egui::Key::ArrowRight); + view.key(&mut app, egui::Key::ArrowRight); + let set = &app.ui.fold_preview; + assert_eq!((set.rotate_x, set.rotate_y), (-5.0, 10.0), "every press turns the view by 5°"); + // A focused view seen from the back stays there until a key turns it. + app.run("ui.foldPreview", json!({"view": "back"})).unwrap(); + view.idle(&mut app); + assert_eq!(app.ui.fold_preview.rotate_y, 180.0); +} + +#[test] +fn a_double_click_on_a_panel_makes_it_the_base() { + let (mut app, mut view, at) = front_view(); + // The left wall is the base; the middle of the view shows the tray's base panel. + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + view.click(&mut app, at); + let [x, y] = app.ui.fold_preview.base.expect("a base"); + assert!((140.0..240.0).contains(&x) && (140.0..240.0).contains(&y), "the base panel is picked: {x}, {y}"); +} + +#[test] +fn a_double_click_as_the_document_changes_picks_nothing_from_the_old_image() { + let (mut app, mut view, at) = front_view(); + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + view.step(&mut app, vec![press(true)], Modifiers::NONE); + // The document changes between the image on screen and the release that ends the double-click. + app.run("shape.rectangle", json!({"x": 350, "y": 350, "width": 10, "height": 10})).unwrap(); + view.step(&mut app, vec![press(false)], Modifiers::NONE); + assert_eq!(app.ui.fold_preview.base, Some([120.0, 190.0]), "the base is kept"); +} + +#[test] +fn the_view_is_folded_and_drawn_again_only_when_something_changes() { + let (mut app, mut view, _) = front_view(); + let (folds, renders) = work_done(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders), "nothing changed: no fold and no render"); + app.run("ui.foldPreview", json!({"rotateY": 10})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders + 1), "a turn renders once and does not fold again"); + app.run("ui.foldPreview", json!({"amount": 0.5})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds + 1, renders + 2), "a new amount folds and renders once"); +} + +#[test] +fn a_short_wide_window_keeps_its_proportions() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(2200.0, 260.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(&mut app, ui)); + out.textures_delta.clear(); + } + let (img, rect) = (last_image().expect("a frame"), last_rect().expect("a rect")); + let (image, window) = (f64::from(img.width) / f64::from(img.height), f64::from(rect.width() / rect.height())); + assert!(img.width <= vectorcraft_three_d::fold::raster::MAX_SIDE, "{}", img.width); + assert!((image - window).abs() / window < 0.02, "image {image}, window {window}"); +} + +#[test] +fn a_print_of_another_blank_or_setting_is_not_drawn_while_the_new_one_renders() { + let key = PrintKey { uid: 1, revision: 5, fold_lines: false, region: [0, 0, 10, 10], width: 1, height: 1 }; + let region = vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0); + let print = vectorcraft_three_d::fold::raster::Print::new(region, 1, 1, vec![255; 4]).expect("a print"); + let cache = Cache { print: Some((key, Arc::new(print))), ..Default::default() }; + assert!(cache.print_for(&PrintKey { revision: 6, ..key }).is_some(), "a newer revision of the same blank keeps the last print"); + for other in [PrintKey { uid: 2, ..key }, PrintKey { fold_lines: true, ..key }, PrintKey { region: [0, 0, 20, 10], ..key }] { + assert!(cache.print_for(&other).is_none(), "{other:?}"); + } +} + +#[test] +fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { + use vectorcraft_three_d::fold::{Blank, Folded, FoldedHinge}; + let hinge = |tree, closes, gap| FoldedHinge { a: 0, b: 1, angle: 90.0, tree, closes, gap }; + let f = Folded { + base: 0, + panels: vec![], + order: vec![], + hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], + collisions: vec![(0, 1)], + }; + let lines = status(3, Some((&Blank::default(), &f)), true); + assert_eq!( + lines, + [ + "Panels: 0, hinges: 0", + "Check the fold lines first.", + "Other blanks not shown: 2", + "A joint does not close by 12.3 pt.", + "Two panels pass through each other." + ] + ); + let f = Folded { hinges: vec![hinge(false, true, 0.05)], collisions: vec![], ..f }; + assert_eq!(status(1, Some((&Blank::default(), &f)), false), ["Panels: 0, hinges: 0"]); +} + +#[test] +fn the_window_says_when_folded_panels_pass_through_each_other() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. Folded + // about the base, the lid crosses the taller wall. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M0 0 L310 0 L310 50 L0 50 Z"); + let creases = [path(&mut app, "M120 0 L120 50"), path(&mut app, "M150 0 L150 50"), path(&mut app, "M250 0 L250 50")]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"base": [200, 25], "amount": 1})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Two panels pass through each other."), "{text}"); + assert!(!text.contains("A joint does not close"), "{text}"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index b27a198fc1..2e6ca34ff5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7120,4 +7120,14 @@ breakText Glyphs Глифи @msg A panel is not joined to the rest by a crease. Панел не е свързан с останалите с линия за биговане. @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} + Fold Preview Преглед на сгъването + Fold Сгъване + Show Fold Lines Покажи линиите на сгъване + Three-Quarter Три четвърти + Open a document to preview its folded shape. Отворете документ, за да прегледате сгънатата му форма. +@msg Check the fold lines first. Първо проверете линиите на сгъване. +@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, панти: {hinges} +@msg Other blanks not shown: {count} Други разкрои не са показани: {count} +@msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt. +@msg Two panels pass through each other. Два панела минават един през друг. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index df8c34eeeb..9bdc66c1a0 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7173,4 +7173,14 @@ shape Open Otvoren @msg A panel is not joined to the rest by a crease. Panel nije povezan s ostatkom nijednom linijom bigovanja. @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} + Fold Preview Pregled savijanja + Fold Savijanje + Show Fold Lines Prikaži linije savijanja + Three-Quarter Tri četvrtine + Open a document to preview its folded shape. Otvorite dokument da pregledate njegov savijeni oblik. +@msg Check the fold lines first. Prvo provjerite linije savijanja. +@msg Panels: {panels}, hinges: {hinges} Paneli: {panels}, šarke: {hinges} +@msg Other blanks not shown: {count} Ostali krojevi nisu prikazani: {count} +@msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt. +@msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a3f6252a3f..43bb40fc9f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7981,4 +7981,14 @@ breakText Glyphs Glifs @msg A panel is not joined to the rest by a crease. Un panell no està unit a la resta per cap línia d’hendit. @msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings} + Fold Preview Previsualització del plegat + Fold Plegat + Show Fold Lines Mostra les línies de plegat + Three-Quarter Tres quarts + Open a document to preview its folded shape. Obre un document per previsualitzar-ne la forma plegada. +@msg Check the fold lines first. Primer comprova les línies de plegat. +@msg Panels: {panels}, hinges: {hinges} Panells: {panels}, frontisses: {hinges} +@msg Other blanks not shown: {count} Altres troquelats no mostrats: {count} +@msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt. +@msg Two panels pass through each other. Dos panells es travessen l’un a l’altre. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 83662e4b5b..98440947cb 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9778,3 +9778,13 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Fold Preview Náhled skládání + Fold Složení + Show Fold Lines Zobrazit linie skladu + Three-Quarter Tři čtvrtě + Open a document to preview its folded shape. Otevřete dokument, abyste zobrazili náhled jeho složeného tvaru. +@msg Check the fold lines first. Nejprve zkontrolujte linie skladu. +@msg Panels: {panels}, hinges: {hinges} Panely: {panels}, panty: {hinges} +@msg Other blanks not shown: {count} Další přířezy nejsou zobrazeny: {count} +@msg A joint does not close by {gap} pt. Spoj se nezavírá o {gap} pt. +@msg Two panels pass through each other. Dva panely procházejí jeden druhým. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 6a7c29cbce..cdcff1b2b1 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -9880,4 +9880,14 @@ breakText Glyphs Glyffer @msg A panel is not joined to the rest by a crease. Et panel er ikke forbundet med resten af en rillelinje. @msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings} + Fold Preview Forhåndsvisning af foldning + Fold Foldning + Show Fold Lines Vis foldelinjer + Three-Quarter Trekvart + Open a document to preview its folded shape. Åbn et dokument for at se dets foldede form. +@msg Check the fold lines first. Kontrollér foldelinjerne først. +@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, hængsler: {hinges} +@msg Other blanks not shown: {count} Andre emner vises ikke: {count} +@msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt. +@msg Two panels pass through each other. To paneler går gennem hinanden. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1b1ec46863..02896284d5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9376,3 +9376,13 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Fold Preview Faltvorschau + Fold Falten + Show Fold Lines Faltlinien einblenden + Three-Quarter Dreiviertelansicht + Open a document to preview its folded shape. Öffnen Sie ein Dokument, um seine gefaltete Form in der Vorschau zu sehen. +@msg Check the fold lines first. Prüfen Sie zuerst die Faltlinien. +@msg Panels: {panels}, hinges: {hinges} Felder: {panels}, Scharniere: {hinges} +@msg Other blanks not shown: {count} Weitere Zuschnitte nicht angezeigt: {count} +@msg A joint does not close by {gap} pt. Eine Verbindung schließt um {gap} pt nicht. +@msg Two panels pass through each other. Zwei Felder durchdringen einander. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 618db0a6a8..aea697439c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7955,4 +7955,14 @@ breakText Glyphs Γλύφοι @msg A panel is not joined to the rest by a crease. Ένα πάνελ δεν συνδέεται με τα υπόλοιπα με καμία γραμμή πτύχωσης. @msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} + Fold Preview Προεπισκόπηση δίπλωσης + Fold Δίπλωση + Show Fold Lines Εμφάνιση γραμμών δίπλωσης + Three-Quarter Τρία τέταρτα + Open a document to preview its folded shape. Ανοίξτε ένα έγγραφο για να δείτε σε προεπισκόπηση το διπλωμένο σχήμα του. +@msg Check the fold lines first. Ελέγξτε πρώτα τις γραμμές δίπλωσης. +@msg Panels: {panels}, hinges: {hinges} Πάνελ: {panels}, μεντεσέδες: {hinges} +@msg Other blanks not shown: {count} Άλλα αναπτύγματα δεν εμφανίζονται: {count} +@msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt. +@msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3cf461791e..2f95bcbf1c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7942,4 +7942,14 @@ breakText Glyphs Glifos @msg A panel is not joined to the rest by a crease. Un panel no está unido al resto por ninguna línea de hendido. @msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings} + Fold Preview Vista previa del plegado + Fold Plegado + Show Fold Lines Mostrar líneas de plegado + Three-Quarter Tres cuartos + Open a document to preview its folded shape. Abre un documento para previsualizar su forma plegada. +@msg Check the fold lines first. Comprueba primero las líneas de plegado. +@msg Panels: {panels}, hinges: {hinges} Paneles: {panels}, bisagras: {hinges} +@msg Other blanks not shown: {count} Otros troquelados no mostrados: {count} +@msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt. +@msg Two panels pass through each other. Dos paneles se atraviesan entre sí. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 0b1e3c881b..6b01d0477c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8038,4 +8038,14 @@ breakText Glyphs Merkit @msg A panel is not joined to the rest by a crease. Paneelia ei ole liitetty muihin millään nuuttausviivalla. @msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings} + Fold Preview Taiton esikatselu + Fold Taitto + Show Fold Lines Näytä taittoviivat + Three-Quarter Kolme neljäsosaa + Open a document to preview its folded shape. Avaa asiakirja, niin voit esikatsella sen taitettua muotoa. +@msg Check the fold lines first. Tarkista ensin taittoviivat. +@msg Panels: {panels}, hinges: {hinges} Paneelit: {panels}, saranat: {hinges} +@msg Other blanks not shown: {count} Muita aihioita ei näytetä: {count} +@msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt. +@msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 66d3c23c01..e166d67798 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9763,4 +9763,14 @@ breakText Glyphs Glyphes @msg A panel is not joined to the rest by a crease. Un panneau n’est relié au reste par aucune ligne de rainage. @msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s) + Fold Preview Aperçu du pliage + Fold Pliage + Show Fold Lines Afficher les lignes de pliage + Three-Quarter Trois-quarts + Open a document to preview its folded shape. Ouvrez un document pour prévisualiser sa forme pliée. +@msg Check the fold lines first. Vérifiez d’abord les lignes de pliage. +@msg Panels: {panels}, hinges: {hinges} {panels} panneau(x), {hinges} charnière(s) +@msg Other blanks not shown: {count} {count} autre(s) flan(s) non affiché(s) +@msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt. +@msg Two panels pass through each other. Deux panneaux se traversent. @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 385fccc138..76057376ed 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4877,6 +4877,16 @@ swatch [Registration] [રજિસ્ટ્રેશન] @msg A panel is not joined to the rest by a crease. એક પેનલ કોઈ ક્રીઝ લાઇનથી બાકીના સાથે જોડાયેલી નથી. @msg A fold line is on a non-printing layer. એક ફોલ્ડ લાઇન નોન-પ્રિન્ટિંગ લેયર પર છે. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, હિન્જ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings} + Fold Preview ફોલ્ડ પ્રિવ્યૂ + Fold ફોલ્ડ + Show Fold Lines ફોલ્ડ લાઇન્સ બતાવો + Three-Quarter ત્રણ-ચતુર્થાંશ + Open a document to preview its folded shape. તેનો ફોલ્ડ કરેલો આકાર જોવા દસ્તાવેજ ખોલો. +@msg Check the fold lines first. પહેલાં ફોલ્ડ લાઇન્સ ચેક કરો. +@msg Panels: {panels}, hinges: {hinges} પેનલ: {panels}, હિન્જ: {hinges} +@msg Other blanks not shown: {count} બીજા બ્લેન્ક બતાવ્યા નથી: {count} +@msg A joint does not close by {gap} pt. એક સાંધો {gap} pt થી બંધ થતો નથી. +@msg Two panels pass through each other. બે પેનલ એકબીજામાંથી પસાર થાય છે. Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e332f6be32..a465a78cc8 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9383,3 +9383,13 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Fold Preview फ़ोल्ड प्रीव्यू + Fold फ़ोल्ड + Show Fold Lines फ़ोल्ड लाइनें दिखाएँ + Three-Quarter तीन-चौथाई + Open a document to preview its folded shape. इसका फ़ोल्ड किया हुआ आकार देखने के लिए कोई डॉक्यूमेंट ओपन करें। +@msg Check the fold lines first. पहले फ़ोल्ड लाइनें चेक करें। +@msg Panels: {panels}, hinges: {hinges} पैनल: {panels}, हिंज: {hinges} +@msg Other blanks not shown: {count} दूसरे ब्लैंक नहीं दिखाए गए: {count} +@msg A joint does not close by {gap} pt. एक जोड़ {gap} pt से बंद नहीं होता। +@msg Two panels pass through each other. दो पैनल एक-दूसरे के आर-पार जाते हैं। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e4452cb211..f3570ab058 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9766,3 +9766,13 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Fold Preview Hajtás előnézete + Fold Hajtás + Show Fold Lines Hajtásvonalak megjelenítése + Three-Quarter Háromnegyed + Open a document to preview its folded shape. Nyiss meg egy dokumentumot a hajtogatott alakja előnézetéhez. +@msg Check the fold lines first. Előbb ellenőrizd a hajtásvonalakat. +@msg Panels: {panels}, hinges: {hinges} Panelek: {panels}, zsanérok: {hinges} +@msg Other blanks not shown: {count} További kiterítékek nincsenek megjelenítve: {count} +@msg A joint does not close by {gap} pt. Egy illesztés {gap} pt-tal nem záródik. +@msg Two panels pass through each other. Két panel áthatol egymáson. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 37ea827f3c..6601f2cfe7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7135,4 +7135,14 @@ breakText Glyphs Glif @msg A panel is not joined to the rest by a crease. Sebuah panel tidak tersambung ke bagian lain oleh garis lekuk apa pun. @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} + Fold Preview Pratinjau lipatan + Fold Lipat + Show Fold Lines Tampilkan garis lipat + Three-Quarter Tiga perempat + Open a document to preview its folded shape. Buka dokumen untuk melihat pratinjau bentuk terlipatnya. +@msg Check the fold lines first. Periksa garis lipat terlebih dahulu. +@msg Panels: {panels}, hinges: {hinges} Panel: {panels}, engsel: {hinges} +@msg Other blanks not shown: {count} Bentangan lain tidak ditampilkan: {count} +@msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt. +@msg Two panels pass through each other. Dua panel saling menembus. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7005d218f7..53a9f9ab07 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9410,3 +9410,13 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Fold Preview Anteprima piegatura + Fold Piegatura + Show Fold Lines Mostra linee di piega + Three-Quarter Tre quarti + Open a document to preview its folded shape. Apri un documento per vederne in anteprima la forma piegata. +@msg Check the fold lines first. Verifica prima le linee di piega. +@msg Panels: {panels}, hinges: {hinges} Pannelli: {panels}, cerniere: {hinges} +@msg Other blanks not shown: {count} Altri fustellati non mostrati: {count} +@msg A joint does not close by {gap} pt. Una giunzione non si chiude di {gap} pt. +@msg Two panels pass through each other. Due pannelli si attraversano. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9b403f103c..1d72426468 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9477,3 +9477,13 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Fold Preview 折りプレビュー + Fold 折り + Show Fold Lines 折り線を表示 + Three-Quarter 斜め + Open a document to preview its folded shape. ドキュメントを開くと折った形をプレビューできます。 +@msg Check the fold lines first. 先に折り線をチェックしてください。 +@msg Panels: {panels}, hinges: {hinges} パネル: {panels}、ヒンジ: {hinges} +@msg Other blanks not shown: {count} 表示されていない他の展開図: {count} +@msg A joint does not close by {gap} pt. 継ぎ目が {gap} pt 閉じていません。 +@msg Two panels pass through each other. 2 つのパネルが互いを貫通しています。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a069c9bac6..7baa711ee9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10044,4 +10044,14 @@ font-script Japanese იაპონური @msg A panel is not joined to the rest by a crease. პანელი დანარჩენს არცერთი ბიგის ხაზით არ უერთდება. @msg A fold line is on a non-printing layer. მოკეცვის ხაზი არასაბეჭდ შრეზეა. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} + Fold Preview მოკეცვის გადახედვა + Fold მოკეცვა + Show Fold Lines მოკეცვის ხაზების ჩვენება + Three-Quarter სამი მეოთხედი + Open a document to preview its folded shape. გახსენით დოკუმენტი მისი მოკეცილი ფორმის სანახავად. +@msg Check the fold lines first. ჯერ შეამოწმეთ მოკეცვის ხაზები. +@msg Panels: {panels}, hinges: {hinges} პანელები: {panels}, ანჯამები: {hinges} +@msg Other blanks not shown: {count} სხვა ნამზადები არ ჩანს: {count} +@msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით. +@msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e2de2a8d46..e2eb144f28 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9373,3 +9373,13 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Fold Preview 접기 미리 보기 + Fold 접기 + Show Fold Lines 접는 선 표시 + Three-Quarter 3/4 보기 + Open a document to preview its folded shape. 접은 모양을 미리 보려면 문서를 여세요. +@msg Check the fold lines first. 먼저 접는 선을 검사하세요. +@msg Panels: {panels}, hinges: {hinges} 패널: {panels}, 힌지: {hinges} +@msg Other blanks not shown: {count} 표시되지 않은 다른 전개도: {count} +@msg A joint does not close by {gap} pt. 이음매가 {gap} pt만큼 닫히지 않습니다. +@msg Two panels pass through each other. 두 패널이 서로 관통합니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index aaa159876e..fa05510f1a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9811,3 +9811,13 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Fold Preview Vouwvoorbeeld + Fold Vouwen + Show Fold Lines Vouwlijnen tonen + Three-Quarter Driekwart + Open a document to preview its folded shape. Open een document om de gevouwen vorm te bekijken. +@msg Check the fold lines first. Controleer eerst de vouwlijnen. +@msg Panels: {panels}, hinges: {hinges} Panelen: {panels}, scharnieren: {hinges} +@msg Other blanks not shown: {count} Andere uitslagen niet getoond: {count} +@msg A joint does not close by {gap} pt. Een naad sluit {gap} pt niet. +@msg Two panels pass through each other. Twee panelen gaan door elkaar heen. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6f7c6eb49a..a0540715ae 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9631,3 +9631,13 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Fold Preview Podgląd złożenia + Fold Złożenie + Show Fold Lines Pokaż linie zgięcia + Three-Quarter Trzy czwarte + Open a document to preview its folded shape. Otwórz dokument, aby zobaczyć podgląd jego złożonego kształtu. +@msg Check the fold lines first. Najpierw sprawdź linie zgięcia. +@msg Panels: {panels}, hinges: {hinges} Panele: {panels}, zawiasy: {hinges} +@msg Other blanks not shown: {count} Inne wykroje nie są pokazane: {count} +@msg A joint does not close by {gap} pt. Połączenie nie domyka się o {gap} pt. +@msg Two panels pass through each other. Dwa panele przechodzą przez siebie. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4138d050c8..eb9d9c52ae 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9849,3 +9849,13 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Fold Preview Visualização da Dobra + Fold Dobra + Show Fold Lines Mostrar Linhas de Dobra + Three-Quarter Três Quartos + Open a document to preview its folded shape. Abra um documento para visualizar sua forma dobrada. +@msg Check the fold lines first. Verifique primeiro as linhas de dobra. +@msg Panels: {panels}, hinges: {hinges} Painéis: {panels}, dobradiças: {hinges} +@msg Other blanks not shown: {count} Outras planificações não exibidas: {count} +@msg A joint does not close by {gap} pt. Uma junção não fecha por {gap} pt. +@msg Two panels pass through each other. Dois painéis se atravessam. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 5f73b0dd78..1c1dda90c2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9870,5 +9870,15 @@ shape Open Открытый @msg A panel is not joined to the rest by a crease. Панель не соединена с остальными ни одной линией биговки. @msg A fold line is on a non-printing layer. Линия сгиба находится на непечатаемом слое. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings} + Fold Preview Предпросмотр сгиба + Fold Сгиб + Show Fold Lines Показать линии сгиба + Three-Quarter Три четверти + Open a document to preview its folded shape. Откройте документ, чтобы просмотреть его в сложенном виде. +@msg Check the fold lines first. Сначала проверьте линии сгиба. +@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, шарниры: {hinges} +@msg Other blanks not shown: {count} Другие развёртки не показаны: {count} +@msg A joint does not close by {gap} pt. Стык не смыкается на {gap} pt. +@msg Two panels pass through each other. Две панели проходят друг сквозь друга. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 769e5c7873..0ca8801ade 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9459,4 +9459,14 @@ digits Hindi Hindi @msg A panel is not joined to the rest by a crease. En panel är inte förbunden med resten av någon biglinje. @msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings} + Fold Preview Förhandsgranskning av falsning + Fold Falsning + Show Fold Lines Visa falslinjer + Three-Quarter Trekvarts + Open a document to preview its folded shape. Öppna ett dokument för att förhandsgranska dess falsade form. +@msg Check the fold lines first. Kontrollera falslinjerna först. +@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, gångjärn: {hinges} +@msg Other blanks not shown: {count} Andra ämnen visas inte: {count} +@msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt. +@msg Two panels pass through each other. Två paneler går igenom varandra. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 8937e9fe77..25975ba9ee 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9732,3 +9732,13 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Fold Preview Katlama Önizlemesi + Fold Katlama + Show Fold Lines Katlama Çizgilerini Göster + Three-Quarter Dörtte Üç + Open a document to preview its folded shape. Katlanmış şeklini önizlemek için bir belgeyi açın. +@msg Check the fold lines first. Önce katlama çizgilerini denetleyin. +@msg Panels: {panels}, hinges: {hinges} Paneller: {panels}, menteşeler: {hinges} +@msg Other blanks not shown: {count} Gösterilmeyen diğer açınımlar: {count} +@msg A joint does not close by {gap} pt. Bir birleşim {gap} pt kadar kapanmıyor. +@msg Two panels pass through each other. İki panel birbirinin içinden geçiyor. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 99f8038a30..1aca1f7cfa 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9385,3 +9385,13 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Fold Preview Перегляд згину + Fold Згин + Show Fold Lines Показати лінії згину + Three-Quarter Три чверті + Open a document to preview its folded shape. Відкрийте документ, щоб переглянути його у складеному вигляді. +@msg Check the fold lines first. Спершу перевірте лінії згину. +@msg Panels: {panels}, hinges: {hinges} Панелі: {panels}, шарніри: {hinges} +@msg Other blanks not shown: {count} Інші розгортки не показано: {count} +@msg A joint does not close by {gap} pt. Стик не змикається на {gap} pt. +@msg Two panels pass through each other. Дві панелі проходять одна крізь одну. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index cece3dcf1b..21713b4b2b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7495,6 +7495,16 @@ breakText Glyphs Glyph @msg A panel is not joined to the rest by a crease. Một mặt không được nối với phần còn lại bằng đường cấn nào. @msg A fold line is on a non-printing layer. Một đường gấp nằm trên lớp không in. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Mặt: {panels}, bản lề: {hinges}, lỗi: {errors}, cảnh báo: {warnings} + Fold Preview Xem trước nếp gấp + Fold Gấp + Show Fold Lines Hiện đường gấp + Three-Quarter Ba phần tư + Open a document to preview its folded shape. Mở tài liệu để xem trước hình dạng đã gấp của nó. +@msg Check the fold lines first. Hãy kiểm tra đường gấp trước. +@msg Panels: {panels}, hinges: {hinges} Mặt: {panels}, bản lề: {hinges} +@msg Other blanks not shown: {count} Các khuôn trải khác không được hiển thị: {count} +@msg A joint does not close by {gap} pt. Một mối nối hở {gap} pt. +@msg Two panels pass through each other. Hai mặt xuyên qua nhau. # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 677f7268b4..bb53379905 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9616,4 +9616,14 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. 一个面板没有通过任何压痕线与其余部分相连。 @msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings} + Fold Preview 折叠预览 + Fold 折叠 + Show Fold Lines 显示折线 + Three-Quarter 四分之三视图 + Open a document to preview its folded shape. 打开文档以预览其折叠后的形状。 +@msg Check the fold lines first. 请先检查折线。 +@msg Panels: {panels}, hinges: {hinges} 面板:{panels},铰链:{hinges} +@msg Other blanks not shown: {count} 未显示的其他展开图:{count} +@msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。 +@msg Two panels pass through each other. 两个面板相互穿插。 @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b50f0671b0..b165b4fa03 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9426,4 +9426,14 @@ breakText Glyphs 字符 @msg A panel is not joined to the rest by a crease. 一個面板沒有透過任何壓痕線與其餘部分相連。 @msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings} + Fold Preview 摺疊預覽 + Fold 摺疊 + Show Fold Lines 顯示摺線 + Three-Quarter 四分之三視圖 + Open a document to preview its folded shape. 開啟文件以預覽其摺疊後的形狀。 +@msg Check the fold lines first. 請先檢查摺線。 +@msg Panels: {panels}, hinges: {hinges} 面板:{panels},鉸鏈:{hinges} +@msg Other blanks not shown: {count} 未顯示的其他展開圖:{count} +@msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。 +@msg Two panels pass through each other. 兩個面板相互穿插。 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b4e1c668ac..4966b9b31b 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -860,6 +860,7 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< } "ui.imageTracePresetDialog" => crate::dialogs::trace_presets::open(app, p), "ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p), + "ui.foldPreview" => crate::addons::packaging::preview::command(app, p), "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), "window.graphicStyleLibrary" => crate::panels::graphic_styles::open_library(app, p), "ui.libraryPanel" => crate::panels::library_panel::command(app, p), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 2b285c704b..af7f870f83 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1148,6 +1148,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.foldPreview", + "Fold Preview", + "", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb or the name of a swatch with a plain color (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + ), ( "ui.copyScriptConsole", "Copy Script Console", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0a4f01879d..7bf9249234 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1377,6 +1377,7 @@ pub(crate) fn floating_size(panel: &str) -> egui::Vec2 { // Tall enough to show its Corners and Shared Edges sections, last in it, which the Corner // Tool's and Shared Edge Merge Tool's menu items open. crate::addons::pathtools::ID => egui::vec2(260.0, 660.0), + crate::addons::packaging::preview::ID => egui::vec2(520.0, 440.0), _ => egui::vec2(260.0, 360.0), } } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 487d501054..67a90c90e2 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -191,6 +191,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), crate::addons::color::ID => crate::addons::color::show(app, ui), crate::addons::packaging::ID => crate::addons::packaging::show(app, ui), + crate::addons::packaging::preview::ID => crate::addons::packaging::preview::show(app, ui), crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), crate::addons::pathtools::shape::ID => crate::addons::pathtools::shape::show(app, ui), crate::addons::pen::ID => crate::addons::pen::show(app, ui), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d3698aaeef..480bb37ed8 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -228,6 +228,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), (crate::addons::packaging::ID, "Fold Lines", "scissors"), + (crate::addons::packaging::preview::ID, "Fold Preview", "box"), (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), (crate::addons::pathtools::shape::ID, "Parametric Shape", "hexagon"), (crate::addons::pen::ID, "Smart Pen", "spline-pointer"), @@ -712,6 +713,10 @@ pub struct UiState { /// Flattener Preview panel: highlight, overprints, preset and options (`ui.flattenerPreview`). #[serde(default)] pub flattener_preview: crate::panels::flattener_preview::Settings, + /// Fold Preview window: fold amount, view, zoom, perspective, inside color, fold lines and + /// base panel (`ui.foldPreview`). + #[serde(default)] + pub fold_preview: crate::addons::packaging::preview::Settings, /// Color Guide panel: Limit to Library, a swatch library id, "document" (the document's /// swatches) or "" (none) (`ui.colorGuideLimit`). #[serde(default)] @@ -1237,6 +1242,7 @@ impl Default for UiState { color_guide: Default::default(), library_panels: vec![], flattener_preview: Default::default(), + fold_preview: Default::default(), color_guide_limit: String::new(), color_guide_base: None, align_to: Default::default(), diff --git a/docs/mcp.md b/docs/mcp.md index 044b452de5..f7075c4397 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13099,10 +13099,10 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are -`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch` and `addon.packaging.check`. In the -desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, -Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the selection, and Check Fold Lines runs -`addon.packaging.check`. +`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check` and +`addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, +Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the +selection, Check Fold Lines runs `addon.packaging.check`, and Fold Preview runs `ui.foldPreview`. ### Fold line roles @@ -13198,6 +13198,54 @@ The list is shown until the document changes. {"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} ``` +### Fold Preview + +`addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads +the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or +the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it +to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from +the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of +panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way, +whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of +hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything +else is an error. The command does not change the document. + +Result: `{ok, blank, blanks, base, panels: [{outline, frame: {x, y, z, origin}, parent, depth}], hinges: [{a, b, +angle, kind, closes, gap}], collisions: [[a, b]], issues}`. `outline` is the panel's SVG path data in document +coordinates. `frame` gives where the flat blank's x and y directions, its printed side and its origin end up, in points, +with x to the right, y up and z toward the printed side of the flat blank. `kind` is `tree` for the hinges the panels +turn about and `closing` for the others. `collisions` lists the panels that pass through each other; panels stacked in +one plane, such as the top flaps of a closed box, are not listed. Without a blank (`ok` false), `blank` and `base` are +null and the lists are empty; `issues` are those of `addon.packaging.check`. + +The Fold Preview window (Object › Plug-ins › Packaging Tools › Fold Preview, or the Fold Lines panel's Fold Preview +button) shows the blank that the document's shown fold lines make, folded, with the document's printed art on the +outside of each panel and the board's inside color on the back. The print leaves out the fold lines, unless Show Fold +Lines is on, and the layers that do not print. Under the view, the Fold slider sets the amount and the Zoom slider the +zoom; a status line gives the panels and hinges and says when a joint does not close, when two panels pass through each +other, when other blanks are not shown and when the fold lines have an error. Dragging in the view turns it, a +Shift-drag keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a panel makes it +the base, and the arrow keys turn the view by 5° when it has the keyboard focus. The view is drawn at the display's +pixel density up to 2,097,152 pixels (2,048 × 1,024) and 4,096 pixels along a side, and at a lower density past either, +and the print is a raster whose longest side is 2,048 pixels, rendered again when the document changes. + +`ui.foldPreview` (`{amount?, view?: front|back|left|right|top|bottom|threeQuarter, rotateX?, rotateY?, zoom?, +perspective?, inside?, showFoldLines?, base?}`) sets the window, shows it and draws it again. A second run leaves the +window open. `rotateX` (-180 to 180) tips the top toward the viewer and `rotateY` (-180 to 180) turns the right side +toward the viewer, in degrees; `zoom` is 0.1 to 8, where 1 fits the folded blank; `perspective` is the field of view, 0 to +160 degrees, 0 for none; `inside` is `#rrggbb` or the name of a swatch with a plain color; `base` is a point in a panel +of the document's blanks, or null for the largest panel. With perspective, the zoom of 1 keeps the eye at least twice +the folded blank's radius from its middle. A value of the wrong kind or out of range is an error and sets nothing. +VectorCraft's own defaults are a Three-Quarter view (`rotateX` 25, `rotateY` 35), no perspective, a white inside and the +fold lines hidden. Saved settings out of range are brought into range when the window is drawn. Result: the window's +settings, and `frame`: the last frame's `{width, height}` in pixels and how long the fold and the drawing took (`foldMs`, +`drawMs`), or null before the first frame. The view is folded and drawn again only when the document, the settings or +the window's size change. + +```json +{"name":"run_command","arguments":{"command":"ui.foldPreview","params":{"amount":0.5,"view":"threeQuarter","perspective":30}}} +``` + ## Image Tools add-on Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`, From 62ef2f4e6871c7abe29f458368444b9791496198 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 10:24:23 -0800 Subject: [PATCH 38/48] Docs: Tile counts each view of a document as a window window.arrange.tile counts windows for its two-window minimum, its grid columns and the panes of the 2-Up to 6-Up layouts. docs/mcp.md said documents. --- docs/mcp.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 4be2808189..b7372cec7a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7345,14 +7345,15 @@ document current, and its tool keeps its state; closing the current document mak current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first, to ask whether to save it. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document -area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to -its pane; with fewer than two documents open it leaves the view, `tiled` and the layout as they are. It returns +area, in a grid of as many columns as the square root of the number of windows, rounded up, and fits each document to +its pane. Each view of a document counts as a window (see `window.newWindow` below). With fewer than two windows open it +leaves the view, `tiled` and the layout as they are. It returns `{tiled, panes, layout}`. `window.arrange.tile {layout}` picks another layout, as the other Tile items of Window › Arrange and of the application bar's Arrange Documents button do: `grid` (the default), `vertical` (Tile All Vertically: side by side in one row), `horizontal` (Tile All Horizontally: stacked in one column), and `2up`, `3up`, -`4up` and `6up`, which show at most that many documents (2-Up and 3-Up side by side, 4-Up two by two, 6-Up three by -two) and leave the others under their tabs. Those layouts show the first documents in tab order, and the current -document takes the last pane when it is not among them, so a click on another tab brings that document into the last +`4up` and `6up`, which show at most that many windows (2-Up and 3-Up side by side, 4-Up two by two, 6-Up three by +two) and leave the others under their tabs. Those layouts show the first windows in tab order, and the current +window takes the last pane when it is not among them, so a click on another tab brings that window into the last pane. Any other `layout` is an error, and the view stays as it is. The set of layouts and how each one places the panes are VectorCraft's own. The current document's pane is the canvas, and a press in another pane makes its document the current one. `window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows, also first in Arrange From 46c8a86fbd81c9a52301efd04ec4c3f4d94a7618 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 12:01:11 -0800 Subject: [PATCH 39/48] Window: Arrange Documents tests find the search icon by its current label The command palette's search icon is labeled "Search commands, tools, panels and effects" since 44f75df965. The two application bar tests still looked for "Search commands and tools", so the narrow-bar test saw Arrange Documents without the search icon at every width. --- crates/ui-egui/src/canvas/panes/tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 24a4690b3c..8b3f7277b1 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -376,7 +376,7 @@ fn the_arrange_documents_button_tiles_and_consolidates() { crate::theme::install_fonts(&ctx); app_bar_frame(&mut app, &ctx, vec![]); let nodes = app_bar_frame(&mut app, &ctx, vec![]); - let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands and tools")); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands, tools, panels and effects")); let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search icon shows")); assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search icon: {arrange:?}, {search:?}"); click_app_bar(&mut app, &ctx, "Arrange Documents"); @@ -412,7 +412,8 @@ fn a_narrow_application_bar_keeps_search_before_arrange_documents() { for width in (200..=1400).rev().step_by(4) { app_bar_frame_in(&mut app, &ctx, vec![], width as f32); let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32); - let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands and tools").is_some()); + let (arrange, search) = + (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands, tools, panels and effects").is_some()); assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search icon"); search_alone |= search && !arrange; } From c0667364ed3dc86243842a4d4848f9991b024b0c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 12:22:19 -0800 Subject: [PATCH 40/48] Navigator: View Artboard Contents Only is on by default and hides art outside the artboards The Navigator panel menu item View Artboard Only is renamed View Artboard Contents Only and is now on by default. While it is on, the thumbnail fits the artboards and draws only the art inside them: art on the pasteboard and in the gaps between artboards is left out, and a shape that crosses an artboard's edge is cut there. Before, the option only narrowed the thumbnail to the artboards' bounding box, so art in the gaps and past an artboard's edge still showed. The choice is kept with the UI state for every document, instead of being lost on restart. UI state saved without it reads it as on, and a saved off stays off. A user who wants the pasteboard art in the thumbnail turns the menu item off, or runs ui.navigatorPanelOptions {viewArtboardContentsOnly: false}. - ui.navigatorPanelOptions takes viewArtboardContentsOnly (true or false; any other value is an error and changes nothing) and answers {color, solidDashes, viewArtboardContentsOnly}. - The renamed label has a row in every catalog that had the old one. Docs: docs/mcp.md (Navigator panel options), docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 2 +- .../src/dialogs/navigator_panel_options.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/gu.tsv | 2 +- crates/ui-egui/src/i18n/hi.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tests.rs | 14 ++ crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/navigator.rs | 161 ++++++++++++++++-- crates/ui-egui/src/state.rs | 3 +- docs/mcp.md | 20 ++- docs/target-app-parity.md | 1 + 36 files changed, 207 insertions(+), 54 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index f81ea2f7f9..feca4b0401 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1097,7 +1097,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.layersExpand", diff --git a/crates/ui-egui/src/dialogs/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs index c3582ae59a..c0988ec548 100644 --- a/crates/ui-egui/src/dialogs/navigator_panel_options.rs +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -85,7 +85,7 @@ mod tests { d.fields.insert("solidDashes".into(), json!(solid)); super::super::confirm(app) }; - assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true})); + assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true, "viewArtboardContentsOnly": true})); assert!(app.ui.dialog.is_none()); app.run("ui.navigatorPanelOptions", json!({})).unwrap(); set(&mut app, "#0000FF", true).unwrap(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 754ae856bd..14c1d4c773 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4012,7 +4012,7 @@ digits Malayalam Малаялам Vertical: Вертикално: Very High Много високо View Изглед - View Artboard Only Преглед само на работна област + View Artboard Contents Only Преглед само на съдържанието на работната област View Opacity Mask Преглед на маска за непрозрачност View PDF after saving Преглед на PDF след запазване View {n} Изглед {n} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6c741f000f..3883cb7abf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2031,7 +2031,7 @@ digits Malayalam Malajalam Stroke: click for swatches, Shift-click for the color mixer Potez: kliknite za uzorke boja, Shift-klik za mikser boja This panel is on the roadmap (see the parity plan). Ovaj panel je u planu (vidi plan usklađenosti). Open a document to navigate it. Otvorite dokument da se krećete kroz njega. - View Artboard Only Prikaži samo radnu ploču + View Artboard Contents Only Prikaži samo sadržaj radne ploče Contextual Alternates Kontekstualne alternative Default Figure Zadane brojke Discretionary Ligatures Diskrecione ligature diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2f823c2db0..59650406b6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5259,7 +5259,7 @@ digits Malayalam Malaiàlam Update While Dragging Actualitza mentre s’arrossega Video Thumbnail 1280×720 Miniatura de vídeo 1280×720 View Visualitza - View Artboard Only Visualitza només el tauler + View Artboard Contents Only Visualitza només el contingut del tauler View Opacity Mask Visualitza la màscara d’opacitat View PDF after saving Visualitza el PDF després de desar View {n} Vista {n} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 99a475d96d..4bb0696ae2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2104,7 +2104,7 @@ digits Malayalam Malajálamské Stroke: click for swatches, Shift-click for the color mixer Tah: kliknutím otevřete vzorník, Shift+kliknutím míchání barev This panel is on the roadmap (see the parity plan). Tento panel je v plánu (viz plán parity). Open a document to navigate it. Otevřete dokument, abyste v něm mohli navigovat. - View Artboard Only Zobrazit jen pracovní plochu + View Artboard Contents Only Zobrazit jen obsah pracovní plochy Contextual Alternates Kontextové alternativy Default Figure Výchozí číslice Discretionary Ligatures Volitelné ligatury diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 85aed446b2..b32939eaba 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4596,7 +4596,7 @@ digits Malayalam Malayalam Stroke: click for swatches, Shift-click for the color mixer Kontur: klik for farveprøver, Skift-klik for farveblanderen This panel is on the roadmap (see the parity plan). Dette panel er på vejkortet (se paritetsplanen). Open a document to navigate it. Åbn et dokument for at navigere i det. - View Artboard Only Vis kun tegnebræt + View Artboard Contents Only Vis kun tegnebrættets indhold Contextual Alternates Kontekstuelle alternativer Default Figure Standardcifre Discretionary Ligatures Valgfrie ligaturer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 091114c55d..7f611d2bc0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4070,7 +4070,7 @@ effect Points Punkte Vertical: Vertikal: Very High Sehr hoch View Ansicht - View Artboard Only Nur Zeichenfläche anzeigen + View Artboard Contents Only Nur Inhalt der Zeichenfläche anzeigen View Opacity Mask Deckkraftmaske anzeigen View PDF after saving PDF nach dem Speichern anzeigen View {n} Ansicht {n} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 560c5a91e3..f737049442 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4626,7 +4626,7 @@ digits Malayalam Μαλαγιάλαμ Vertical Scale % Κατακόρυφη κλίμακα % Vertical Type on a Path Tool Κατακόρυφο κείμενο σε διαδρομή (Vertical Type on a Path Tool) Very High Πολύ υψηλή - View Artboard Only Προβολή μόνο πίνακα σχεδίασης + View Artboard Contents Only Προβολή μόνο του περιεχομένου του πίνακα σχεδίασης View Opacity Mask Προβολή μάσκας αδιαφάνειας View PDF after saving Προβολή PDF μετά την αποθήκευση View {n} Προβολή {n} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ed20179e82..a44c36665b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4157,7 +4157,7 @@ digits Malayalam Malayálam Vertical: Vertical: Very High Muy alta View Ver - View Artboard Only Ver solo la mesa de trabajo + View Artboard Contents Only Ver solo el contenido de la mesa de trabajo View Opacity Mask Ver máscara de opacidad View PDF after saving Ver PDF después de guardar View {n} Vista {n} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f0b4039c83..f23a412336 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2065,7 +2065,7 @@ digits Malayalam Malajalam Stroke: click for swatches, Shift-click for the color mixer Viiva: napsauta avataksesi värimallit, Vaihto-napsauta avataksesi värisekoittimen This panel is on the roadmap (see the parity plan). Tämä paneeli on suunnitteilla (katso yhdenmukaisuussuunnitelma). Open a document to navigate it. Avaa asiakirja, niin voit liikkua siinä. - View Artboard Only Näytä vain piirtoalusta + View Artboard Contents Only Näytä vain piirtoalustan sisältö Contextual Alternates Kontekstuaaliset vaihtoehdot Default Figure Oletusnumerot Discretionary Ligatures Valinnaiset ligatuurit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 06a686c9ce..40efa1d794 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4144,7 +4144,7 @@ digits Malayalam Malayalam Vertical: Vertical : Very High Très élevée View Affichage - View Artboard Only Afficher le plan de travail uniquement + View Artboard Contents Only Afficher uniquement le contenu du plan de travail View Opacity Mask Afficher le masque d’opacité View PDF after saving Afficher le PDF après l’enregistrement View {n} Vue {n} diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 9bd0977cb5..fe5c4283dd 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4258,7 +4258,7 @@ Video વિડિયો Video Ruler Pixel Aspect Ratio: વિડિયો રૂલર પિક્સેલ ગુણોત્તર: View વ્યૂ - View Artboard Only માત્ર આર્ટબોર્ડ જુઓ + View Artboard Contents Only માત્ર આર્ટબોર્ડની સામગ્રી જુઓ View Opacity Mask ઓપેસિટી માસ્ક જુઓ View PDF after saving સાચવ્યા પછી PDF જુઓ Viewing Angle: જોવાનો ખૂણો: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index b977422495..6f66d52d8f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5681,7 +5681,7 @@ antiAlias Sharp शार्प Video Thumbnail 1280×720 वीडियो थंबनेल 1280 × 720 View व्यू View {n} {n} - View Artboard Only केवल आर्टबोर्ड देखें + View Artboard Contents Only केवल आर्टबोर्ड की सामग्री देखें View Opacity Mask ओपेसिटी मास्क देखें View PDF after saving सेव करने के बाद PDF देखें View: व्यू: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 42a4a81a6b..f92e921a6b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4891,7 +4891,7 @@ mark-style Japanese Japán Video Banner 2560×1440 Videós szalagcím 2560×1440 Video Thumbnail 1280×720 Videó-bélyegkép 1280×720 View Nézet - View Artboard Only Csak a rajztábla látszik + View Artboard Contents Only Csak a rajztábla tartalma látszik View Opacity Mask Átlátszósági maszk megtekintése View PDF after saving PDF megtekintése mentés után View {n} Nézet {n} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ebd1697020..eff9ea17fe 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1861,7 +1861,7 @@ digits Malayalam Malayalam Stroke: click for swatches, Shift-click for the color mixer Stroke: klik untuk swatch, Shift+klik untuk pencampur warna This panel is on the roadmap (see the parity plan). Panel ini masih dalam roadmap (lihat rencana paritas). Open a document to navigate it. Buka dokumen untuk menjelajahinya. - View Artboard Only Tampilkan artboard saja + View Artboard Contents Only Tampilkan isi artboard saja Contextual Alternates Alternatif kontekstual Default Figure Angka default Discretionary Ligatures Ligatur opsional diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 147e5bfe35..674e41e30d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4204,7 +4204,7 @@ digits Malayalam Malayalam Vertical: Verticale: Very High Molto alta View Visualizza - View Artboard Only Visualizza solo tavola da disegno + View Artboard Contents Only Visualizza solo il contenuto della tavola da disegno View Opacity Mask Visualizza maschera di opacità View PDF after saving Visualizza PDF dopo il salvataggio View {n} Vista {n} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6db09e8cfe..9e9090a8c2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3697,7 +3697,7 @@ mark-style Japanese 日本式 Vertical Type Tool 縦書き文字ツール Vertical Type on a Path Tool 縦書きパス上文字ツール Vertical: 垂直方向: - View Artboard Only アートボードのみ表示 + View Artboard Contents Only アートボードの内容のみ表示 View Opacity Mask 不透明マスクを表示 View PDF after saving 保存後に PDF を表示 Viewing Angle: 視角: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 858cb6f296..025af83a8d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3919,7 +3919,7 @@ digits Malayalam მალაიალამური Stroke: click for swatches, Shift-click for the color mixer კონტური: დაწკაპეთ ფერის ნიმუშებისთვის, Shift-დაწკაპუნებით — ფერის შემრევისთვის This panel is on the roadmap (see the parity plan). ეს პანელი სამომავლო გეგმაშია (იხ. პარიტეტის გეგმა). Open a document to navigate it. გახსენით დოკუმენტი მასში სანავიგაციოდ. - View Artboard Only მხოლოდ სამუშაო დაფის ჩვენება + View Artboard Contents Only მხოლოდ სამუშაო დაფის შიგთავსის ჩვენება Contextual Alternates კონტექსტური ალტერნატივები Default Figure ნაგულისხმევი ციფრები Discretionary Ligatures დამატებითი ლიგატურები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fa8686588f..f8db551d73 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3686,7 +3686,7 @@ mark-style Japanese 일본식 Vertical Type Tool 세로 문자 도구 Vertical Type on a Path Tool 패스 상의 세로 문자 도구 Vertical: 세로: - View Artboard Only 아트보드만 보기 + View Artboard Contents Only 아트보드 내용만 보기 View Opacity Mask 불투명 마스크 보기 View PDF after saving 저장 후 PDF 보기 Viewing Angle: 시야각: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 88c247c2f1..e4a4295d24 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2471,7 +2471,7 @@ digits Malayalam Malayalam Stroke: click for swatches, Shift-click for the color mixer Lijn: klik voor stalen, Shift-klik voor de kleurenmixer This panel is on the roadmap (see the parity plan). Dit paneel staat op de roadmap (zie het pariteitsplan). Open a document to navigate it. Open een document om erin te navigeren. - View Artboard Only Alleen tekengebied weergeven + View Artboard Contents Only Alleen inhoud van tekengebied weergeven Contextual Alternates Contextuele alternatieven Default Figure Standaardcijfer Discretionary Ligatures Optionele ligaturen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 4e36d0249a..0278fefc17 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2022,7 +2022,7 @@ digits Malayalam Malajalam Stroke: click for swatches, Shift-click for the color mixer Obrys: kliknij, aby wybrać próbkę, z Shift — mikser kolorów This panel is on the roadmap (see the parity plan). Ten panel jest w planach (patrz plan zgodności). Open a document to navigate it. Otwórz dokument, aby się po nim poruszać. - View Artboard Only Pokaż tylko obszar kompozycji + View Artboard Contents Only Pokaż tylko zawartość obszaru kompozycji Contextual Alternates Alternatywy kontekstowe Default Figure Cyfry domyślne Discretionary Ligatures Ligatury opcjonalne diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b5dc29791e..463e989c3c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3370,7 +3370,7 @@ digits Malayalam Malaiala Vertical Type on a Path Tool Ferramenta Texto Vertical em um Caminho Vertical: Vertical: View Exibir - View Artboard Only Exibir Somente a Mesa de Trabalho + View Artboard Contents Only Exibir Somente o Conteúdo da Mesa de Trabalho View Opacity Mask Exibir Máscara de Opacidade View PDF after saving Exibir PDF após salvar Viewing Angle: Ângulo de Visualização: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 92bf430f65..561d56b820 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4189,7 +4189,7 @@ digits Malayalam Малаялам Vertical: По вертикали: Very High Очень высокая View Просмотр - View Artboard Only Просмотр только монтажной области + View Artboard Contents Only Просмотр только содержимого монтажной области View Opacity Mask Просмотр непрозрачной маски View PDF after saving Просматривать PDF после сохранения View {n} Вид {n} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 7e51593cca..2c912de627 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4074,7 +4074,7 @@ digits Malayalam Malayalam Vertical: Vertikalt: Very High Mycket hög View Visa - View Artboard Only Visa endast rityta + View Artboard Contents Only Visa endast ritytans innehåll View Opacity Mask Visa opacitetsmask View PDF after saving Visa PDF efter sparning View {n} Vy {n} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ed4b44b0da..744ae3cedb 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -570,6 +570,20 @@ fn control_bar_panel_menu_labels_are_in_complete_catalogs() { } } +/// The Navigator panel menu's items are in every complete catalog, and no catalog keeps the +/// item's earlier name, View Artboard Only. +#[test] +fn navigator_panel_menu_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["View Artboard Contents Only", "Panel Options…"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + for lang in LANGUAGES.iter() { + assert!(lang.catalog().plain("View Artboard Only").is_none(), "{} keeps View Artboard Only", lang.code); + } +} + /// Document Info's labels: every category title, which the panel and its menu show, every count /// label of the Objects category, and the Document category's fixed row labels (the artboard rows /// show artboard names and are left out). diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e4dfebabc2..67b87d4d67 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3926,7 +3926,7 @@ digits Malayalam Malayalam Vertical: Dikey: Very High Çok Yüksek View Görünüm - View Artboard Only Yalnızca Çalışma Yüzeyini Görüntüle + View Artboard Contents Only Yalnızca Çalışma Yüzeyi İçeriğini Görüntüle View Opacity Mask Opaklık Maskesini Görüntüle View PDF after saving Kaydettikten sonra PDF'yi görüntüle View {n} {n}'yi görüntüle diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b7fe29b0f1..88ed1717f7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4197,7 +4197,7 @@ effect Points Точки Vertical: По вертикалі: Very High Дуже висока View Перегляд - View Artboard Only Перегляд лише монтажної області + View Artboard Contents Only Перегляд лише вмісту монтажної області View Opacity Mask Перегляд маски непрозорості View PDF after saving Переглядати PDF після збереження View {n} Вигляд {n} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8d8a2176aa..04e007a3ae 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4577,7 +4577,7 @@ mark-style Japanese Kiểu Nhật Very High Rất cao Video Video View Hiển thị - View Artboard Only Chỉ hiển thị bảng vẽ + View Artboard Contents Only Chỉ hiển thị nội dung bảng vẽ View Opacity Mask Hiển thị mặt nạ độ mờ View PDF after saving Xem PDF sau khi lưu View {n} Hiển thị {n} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9499ea301b..91511e0823 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4034,7 +4034,7 @@ digits Malayalam 马拉雅拉姆数字 Vertical: 垂直: Very High 极高 View 视图 - View Artboard Only 仅查看画板 + View Artboard Contents Only 仅查看画板内容 View Opacity Mask 查看不透明度蒙版 View PDF after saving 存储后查看 PDF View {n} 查看 {n} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6402da172c..d6f44597fa 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5350,7 +5350,7 @@ digits Malayalam 馬來亞拉姆數字 Vertical: 垂直: Very High 極高 View 檢視 - View Artboard Only 僅檢視工作區域 + View Artboard Contents Only 僅檢視工作區域內容 View Opacity Mask 檢視不透明度遮色片 View PDF after saving 儲存後檢視 PDF View {n} 檢視 {n} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 2b285c704b..62caaeb4fe 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1098,7 +1098,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.layersExpand", diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index 60eb4c18d0..927c7912ba 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -2,7 +2,8 @@ //! cached by document revision, off the UI thread for heavy documents and not during drags: see //! [`crate::thumb_worker`]) with the view box you drag to pan, zoom out/in buttons, a zoom slider //! and a zoom field. Panel Options… sets the view box's color and whether the thumbnail draws -//! dashed lines as solid lines ([`PanelOptions`]). +//! dashed lines as solid lines, and the panel menu's View Artboard Contents Only (on by default) +//! limits the thumbnail to the art inside the artboards ([`PanelOptions`]). use std::sync::Arc; @@ -13,7 +14,6 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use vectorcraft_geom::{Point, Rect as DRect}; -use super::{pstate, set_pstate}; use crate::VectorcraftApp; use crate::theme::Tokens; use crate::thumb_worker::{Settle, ThumbWorker}; @@ -39,7 +39,8 @@ pub fn resolve(color: &str) -> Option<[u8; 3]> { Some([byte(0)?, byte(2)?, byte(4)?]) } -/// Navigator panel options (≡ › Panel Options…), kept with the UI state. +/// Navigator panel options (≡ › Panel Options… and ≡ › View Artboard Contents Only), kept with the +/// UI state. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct PanelOptions { @@ -48,12 +49,16 @@ pub struct PanelOptions { /// Draw Dashed Lines as Solid Lines (off by default): the thumbnail draws dashed strokes /// without their dashes. The canvas, printing and exports keep the dashes. pub solid_dashes: bool, + /// View Artboard Contents Only (the panel menu; on by default, and on for UI state saved + /// without it): the thumbnail fits the artboards and draws only the art inside them, cut at + /// each artboard's edges. Off, it also fits and draws the art on the pasteboard. + pub view_artboard_contents_only: bool, } impl Default for PanelOptions { fn default() -> Self { let [r, g, b] = VIEW_BOX_RED; - Self { color: Color::rgb8(r, g, b).to_hex(), solid_dashes: false } + Self { color: Color::rgb8(r, g, b).to_hex(), solid_dashes: false, view_artboard_contents_only: true } } } @@ -65,11 +70,11 @@ impl PanelOptions { } } -/// `ui.navigatorPanelOptions {color?, solidDashes?}`: with neither, open Panel Options on the -/// panel's options; otherwise set the ones given and answer the options. +/// `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}`: with none, open +/// Panel Options on the panel's options; otherwise set the ones given and answer the options. pub fn set_options(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { - let (color, solid) = (p.get("color"), p.get("solidDashes")); - if color.is_none() && solid.is_none() { + let (color, solid, contents_only) = (p.get("color"), p.get("solidDashes"), p.get("viewArtboardContentsOnly")); + if color.is_none() && solid.is_none() && contents_only.is_none() { return crate::dialogs::navigator_panel_options::open(app); } let mut o = app.ui.navigator_panel.clone(); @@ -84,6 +89,10 @@ pub fn set_options(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> let key = "solidDashes"; o.solid_dashes = s.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?; } + if let Some(v) = contents_only { + let key = "viewArtboardContentsOnly"; + o.view_artboard_contents_only = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?; + } app.ui.navigator_panel = o; Ok(serde_json::to_value(&app.ui.navigator_panel).unwrap_or_default()) } @@ -218,10 +227,17 @@ impl Cache { } /// How the image `key` names is drawn: as exported (template layers and guides left out), -/// transparent, with images far smaller than they are sampling their mip levels, and with Draw -/// Dashed Lines as Solid Lines, dashed strokes without their dashes. +/// transparent, with images far smaller than they are sampling their mip levels, with Draw +/// Dashed Lines as Solid Lines, dashed strokes without their dashes, and with View Artboard +/// Contents Only, the art cut to the artboards (none in the gaps between them). fn image_options(key: ImageKey) -> vectorcraft_render::RenderOptions { - vectorcraft_render::RenderOptions { skip_templates: true, image_mips: true, solid_dashes: key.solid_dashes, ..Default::default() } + vectorcraft_render::RenderOptions { + skip_templates: true, + image_mips: true, + solid_dashes: key.solid_dashes, + trim: key.artboard_only, + ..Default::default() + } } thread_local! { @@ -296,7 +312,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { super::empty_state(ui, "map", tl!("No document"), tl!("Open a document to navigate it.")); return; }; - let artboard_only: bool = pstate(ui.ctx(), "nav-ab-only"); + let artboard_only = app.ui.navigator_panel.view_artboard_contents_only; let doc = st.doc.clone(); let (uid, revision) = (st.uid, st.revision); // A drag in progress: every pointer move makes a new revision. The image waits for its end. @@ -373,9 +389,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let ab: bool = pstate(ui.ctx(), "nav-ab-only"); - if menu_item(ui, tl!("View Artboard Only"), true, ab) { - set_pstate(ui.ctx(), "nav-ab-only", !ab); + let ab = app.ui.navigator_panel.view_artboard_contents_only; + if menu_item(ui, tl!("View Artboard Contents Only"), true, ab) { + app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": !ab})).ok(); } if menu_item(ui, tl!("Panel Options…"), true, false) { app.run("ui.navigatorPanelOptions", json!({})).ok(); @@ -547,7 +563,7 @@ mod tests { let shown = || CACHE.with(|c| c.borrow().shown.map(|(k, _)| k.solid_dashes)); assert_eq!(shown(), Some(false)); let set = app.run("ui.navigatorPanelOptions", json!({"color": "light blue", "solidDashes": true})).unwrap(); - assert_eq!(set, json!({"color": "#4f80ff", "solidDashes": true})); + assert_eq!(set, json!({"color": "#4f80ff", "solidDashes": true, "viewArtboardContentsOnly": true})); assert_eq!((boxes(&mut app, red), boxes(&mut app, blue)), (0, 1)); for _ in 0..12 { boxes(&mut app, blue); @@ -560,11 +576,15 @@ mod tests { json!({"color": "#f00"}), json!({"color": null}), json!({"color": "Red", "solidDashes": "yes"}), + json!({"color": "Red", "viewArtboardContentsOnly": "no"}), + json!({"solidDashes": false, "viewArtboardContentsOnly": 0}), + json!({"viewArtboardContentsOnly": null}), ]; for bad in bad { assert!(app.run("ui.navigatorPanelOptions", bad.clone()).is_err(), "{bad}"); } - assert_eq!(serde_json::to_value(&app.ui.navigator_panel).unwrap(), json!({"color": "#4f80ff", "solidDashes": true}), "nothing changed"); + let want = json!({"color": "#4f80ff", "solidDashes": true, "viewArtboardContentsOnly": true}); + assert_eq!(serde_json::to_value(&app.ui.navigator_panel).unwrap(), want, "nothing changed"); app.run("ui.navigatorPanelOptions", json!({"color": "#123456"})).unwrap(); assert!(app.ui.navigator_panel.solid_dashes, "an option left out keeps its value"); } @@ -600,6 +620,113 @@ mod tests { assert_eq!(draw(&line(false), on), solid, "a solid stroke draws as it did"); } + /// View Artboard Contents Only is on by default, and on for UI state saved without it, whether + /// the panel's options are missing or saved before the option existed; a saved off stays off. + #[test] + fn view_artboard_contents_only_is_on_by_default_and_a_saved_off_stays_off() { + assert!(PanelOptions::default().view_artboard_contents_only); + let none: crate::UiState = serde_json::from_value(json!({})).unwrap(); + assert!(none.navigator_panel.view_artboard_contents_only, "UI state saved without the panel's options"); + let older: crate::UiState = serde_json::from_value(json!({"navigator_panel": {"color": "#123456", "solidDashes": true}})).unwrap(); + let o = &older.navigator_panel; + assert!(o.view_artboard_contents_only && o.solid_dashes && o.color == "#123456", "options saved before the option existed: {o:?}"); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert!(app.ui.navigator_panel.view_artboard_contents_only); + let set = app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": false})).unwrap(); + assert_eq!(set, json!({"color": "#ff3030", "solidDashes": false, "viewArtboardContentsOnly": false})); + let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert!(!back.navigator_panel.view_artboard_contents_only, "a saved off stays off"); + } + + /// The panel menu's View Artboard Contents Only starts checked, and a click turns it off (the + /// same option `ui.navigatorPanelOptions` sets), then on again. + #[test] + fn view_artboard_contents_only_is_checked_in_the_panel_menu_and_a_click_toggles_it() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + named(&tree(|ui| menu(&mut app, ui)), "✓ View Artboard Contents Only"); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(240.0, 400.0))); + let raw = |events| egui::RawInput { events, screen_rect: screen, ..Default::default() }; + let click = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(raw(vec![]), |ui| menu(app, ui)); + out.textures_delta.clear(); + let item = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().ends_with("View Artboard Contents Only") => Some(t.visual_bounding_rect().center()), + _ => None, + }) + .expect("the menu item"); + let button = + |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + ctx.run_ui(raw(vec![egui::Event::PointerMoved(item), button(true), button(false)]), |ui| menu(app, ui)).textures_delta.clear(); + }; + click(&mut app); + assert!(!app.ui.navigator_panel.view_artboard_contents_only, "a click turns it off"); + named(&tree(|ui| menu(&mut app, ui)), " View Artboard Contents Only"); + click(&mut app); + assert!(app.ui.navigator_panel.view_artboard_contents_only, "a second click turns it on"); + } + + /// With View Artboard Contents Only the thumbnail draws only the art inside the artboards: a + /// shape in the gap between two artboards is left out and one that crosses an artboard's edge + /// is cut there. Without it both draw. + #[test] + fn the_thumbnail_draws_only_the_art_inside_the_artboards_with_the_option() { + use vectorcraft_color::Paint; + use vectorcraft_doc::{Appearance, Document, Node}; + let mut d = Document::new(100.0, 100.0); + let mut second = d.artboards[0].clone(); + second.id = d.artboards.iter().map(|a| a.id).max().unwrap_or(0) + 1; + second.rect = DRect::new(150.0, 0.0, 250.0, 100.0); + d.artboards.push(second); + let l = d.layers[0].id; + for (x0, y0, x1, y1) in [(110.0, 20.0, 140.0, 80.0), (20.0, 80.0, 60.0, 130.0)] { + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((x0, y0)); + bp.line_to((x1, y0)); + bp.line_to((x1, y1)); + bp.line_to((x0, y1)); + bp.close_path(); + let id = d.alloc_id(); + let n = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&bp), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + d.insert(Some(l), 0, n).unwrap(); + } + let alpha = |artboard_only: bool, x: u32, y: u32| { + let key = ImageKey { uid: 1, revision: 1, w: 260, h: 140, artboard_only, solid_dashes: false }; + vectorcraft_render::Renderer::new().render_region_with(&d, DRect::new(0.0, 0.0, 260.0, 140.0), 1.0, &image_options(key)).pixel(x, y)[3] + }; + assert_eq!([alpha(true, 125, 50), alpha(true, 40, 90), alpha(true, 40, 120)], [0, 255, 0], "the gap and below the artboard are empty"); + assert_eq!([alpha(false, 125, 50), alpha(false, 40, 90), alpha(false, 40, 120)], [255, 255, 255], "all the art draws"); + } + + /// Turning View Artboard Contents Only off makes the thumbnail again, fitted to the art on the + /// pasteboard as well as the artboards; turning it on fits it to the artboards again. + #[test] + fn the_thumbnail_is_made_again_when_view_artboard_contents_only_changes() { + use vectorcraft_engine::Session; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 400, "y": 50, "width": 50, "height": 50})).unwrap(); + let ctx = egui::Context::default(); + let frames = |app: &mut VectorcraftApp| { + for _ in 0..12 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); + out.textures_delta.clear(); + } + CACHE.with(|c| c.borrow().shown.map(|(k, r)| (k.artboard_only, r.x1))) + }; + let Some((true, right)) = frames(&mut app) else { panic!("an image of the artboards only") }; + assert!(right < 300.0, "fitted to the artboard: {right}"); + app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": false})).unwrap(); + let Some((false, right)) = frames(&mut app) else { panic!("an image with the pasteboard's art") }; + assert!(right > 450.0, "fitted to the art on the pasteboard too: {right}"); + app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": true})).unwrap(); + assert!(matches!(frames(&mut app), Some((true, r)) if r < 300.0)); + } + #[test] fn zoom_slider_roundtrip() { assert!((zoom_to_slider(3.13)).abs() < 1e-9); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d3698aaeef..99ffa98b66 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -850,7 +850,8 @@ pub struct UiState { /// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only, Locate Selected Objects). #[serde(default)] pub layers_panel: crate::panels::layers::PanelOptions, - /// Navigator panel › Panel Options… (the view box color, Draw Dashed Lines as Solid Lines). + /// Navigator panel › Panel Options… (the view box color, Draw Dashed Lines as Solid Lines) and + /// the panel menu's View Artboard Contents Only. #[serde(default)] pub navigator_panel: crate::panels::navigator::PanelOptions, /// The Layers panel's Filter (`ui.layersFilter`). It is not saved and lasts the session, as the diff --git a/docs/mcp.md b/docs/mcp.md index bee07110e6..bd288ee597 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3139,16 +3139,26 @@ dropped. ## Navigator panel options The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`), -and `ui.navigatorPanelOptions {color?, solidDashes?}` sets the options without it → `{color, solidDashes}`; with -neither key it opens the dialog. `color` is the color the panel's view box is drawn in: `#rrggbb` or a preset name. +and `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}` sets the options without it → +`{color, solidDashes, viewArtboardContentsOnly}`; with none of the keys it opens the dialog. `color` is the color the +panel's view box is drawn in: `#rrggbb` or a preset name. The presets are VectorCraft's own list: Light Red (`#ff3030`, the default), then the layer colors ("Light Blue", "Red", "Green" and the rest). `solidDashes` (Draw Dashed Lines as Solid Lines, off by default) makes the panel's -thumbnail draw dashed strokes without their dashes; the canvas, printing and exports keep the dashes. Both are kept -with the UI state. A `color` that is not a color, or a `solidDashes` that is not true or false, is an error and -changes neither option. Behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html). +thumbnail draw dashed strokes without their dashes; the canvas, printing and exports keep the dashes. +`viewArtboardContentsOnly` is the panel menu's View Artboard Contents Only, on by default: the thumbnail fits the +artboards and draws only the art inside them, so art on the pasteboard and in the gaps between artboards is left out +and a shape that crosses an artboard's edge is cut there. Off, the thumbnail also fits and draws the art outside the +artboards. The view box still shows the canvas's view either way. All three are kept with the UI state and apply to +every document; UI state saved without `viewArtboardContentsOnly` reads it as on, and a saved off stays off. Fitting +the thumbnail to the union of the artboards with a small margin, cutting the art at each artboard, and keeping the +choice with the UI state are VectorCraft's own rules. A `color` that is not a color, or a `solidDashes` or +`viewArtboardContentsOnly` that is not true or false, is an error and changes none of the options. Behavior +references: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) and +[Navigate and zoom artwork](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/navigate-and-zoom-artwork.html). ```json {"name":"invoke_menu","arguments":{"command":"ui.navigatorPanelOptions","params":{"color":"Light Blue","solidDashes":true}}} +{"name":"invoke_menu","arguments":{"command":"ui.navigatorPanelOptions","params":{"viewArtboardContentsOnly":false}}} ``` ## Info panel diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f506da06e1..adb77abd09 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1360,6 +1360,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Artboard click-to-fit (#1227):** a plain click fits the topmost editable object or group to a new artboard, including its stroke like Fit to Selected Art, and makes the new artboard active. Art and its selection stay unchanged; creation is one undo step. Handles, modified clicks, drags, Escape and tool changes retain their meaning. Tested inside an artboard and on the pasteboard (`crates/engine/tests/it/artboard_click.rs`); the public [CS6 Printing Guide](https://helpx.adobe.com/content/dam/help/en/indesign/pdf/CS6_PrintGuide.pdf) documents the object-click gesture. This legacy gesture adds evidence without regrading the 2026 canvas controls. - **Rotated views:** with the view rotated, Fit Artboard in Window, Fit All in Window and the status bar's artboard navigator fit the artboard or the art as the view turns it, and a Zoom tool marquee (Animated Zoom or GPU Performance off) zooms to the area dragged across. Ruler guides on no artboard turn with the view. The canvas draws the selection marquee where the tools select, Show Hidden Characters draws the marks of type partly inside the canvas, the Contextual Task Bar stays under the selection, and the Navigator's red box outlines what the window shows. - **Navigator panel options:** the Navigator panel menu's Panel Options… sets the color the view box is drawn in, from a preset list (VectorCraft's own: Light Red, the default, then the layer colors) or a custom color, and Draw Dashed Lines as Solid Lines, off by default, which draws dashed strokes without their dashes in the panel's thumbnail only (`ui.navigatorPanelOptions`; kept with the UI state; behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). +- **Navigator View Artboard Contents Only:** the Navigator panel menu's View Artboard Contents Only is on by default, and the thumbnail then shows only the art inside the artboards, with art on the pasteboard and in the gaps between artboards left out; turning it off shows the art outside the artboards too (`ui.navigatorPanelOptions {viewArtboardContentsOnly}`; kept with the UI state, read as on when it was never saved; the fit to the artboards' union and the cut at each artboard's edge are VectorCraft's own rules; behavior references: [Navigate and zoom artwork](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/navigate-and-zoom-artwork.html), [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). - **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). Outline view draws on a white canvas in every interface brightness and Canvas Color, pasteboard included, with the artboards as their edges and no paper (VectorCraft's own rule), so the black outlines of art on the pasteboard show. In Presentation Mode, → and ← go to the next and the previous artboard, and a click anywhere goes to the next one, as the status bar navigator's Next and Previous do (`view.goToArtboard`): on the last artboard → and a click leave the view as it is, and so does ← on the first. The arrow keys do not move the selection there, and the tool does not receive a click, so a click selects and draws nothing (behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). Full Screen Mode and Presentation Mode put the window full screen, covering the taskbar and the window's frame, and Normal Screen Mode or Full Screen Mode with Menu Bar puts it back (#4365); a window the user made full screen stays so. From d00e3b6ecd70da260f6f5fbd6b1a346864a8b721 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 11:26:11 -0800 Subject: [PATCH 41/48] Packaging Tools: Fold Preview picks the print level by a pixel's longer side and draws the board opaque A print tipped away from the view shrinks up and down but not across, so the level of the print raster is now chosen by the longer of a pixel's two sides in flat terms, not its width alone, and fine print lines no longer alias when the view is tipped. The board's inside and outside colors were premultiplied by their alpha and then drawn with full alpha, so a see-through color drew darker instead. The depth buffer treats every panel as opaque, so the board is now drawn opaque in its colors' RGB and their alpha is not used. The tray test now checks that each wall's print faces away from the base on its own side and that the walls fold below the base. --- .../src/cmd/addons/packaging/fold/tests.rs | 20 +++++++-- crates/three-d/src/fold/raster.rs | 15 ++++--- crates/three-d/src/fold/raster/tests.rs | 43 +++++++++++++++++++ 3 files changed, 69 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/addons/packaging/fold/tests.rs b/crates/engine/src/cmd/addons/packaging/fold/tests.rs index da7cd6a84e..4c423021f5 100644 --- a/crates/engine/src/cmd/addons/packaging/fold/tests.rs +++ b/crates/engine/src/cmd/addons/packaging/fold/tests.rs @@ -38,6 +38,14 @@ fn vector(v: &Value) -> [f64; 3] { [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] } +/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only). +fn middle(d: &str) -> [f64; 2] { + let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + let ((x0, x1), (y0, y1)) = (span(0), span(1)); + [(x0 + x1) / 2.0, (y0 + y1) / 2.0] +} + fn near(a: [f64; 3], b: [f64; 3]) -> bool { a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) } @@ -61,9 +69,15 @@ fn a_tray_folds_its_walls_up_round_the_base() { assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data"); for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) { assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}"); - // Each wall stands square to the base, its print facing out. - let z = vector(&p["frame"]["z"]); - assert!(z[2].abs() < 1e-9 && (z[0].hypot(z[1]) - 1.0).abs() < 1e-9, "wall {i}: {z:?}"); + // Each wall stands square to the base, below it (away from the print), its print facing out: + // away from the base's middle (190, 190), toward the side the wall lies on. + let [cx, cy] = middle(p["outline"].as_str().unwrap()); + let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"])); + let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy); + let (dx, dy) = (cx - 190.0, 190.0 - cy); + let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] }; + assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}"); + assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}"); } let hinges = r["hinges"].as_array().unwrap(); assert_eq!(hinges.len(), 4); diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs index 012a9621de..e481eee15d 100644 --- a/crates/three-d/src/fold/raster.rs +++ b/crates/three-d/src/fold/raster.rs @@ -179,7 +179,8 @@ impl Print { } /// What [`render`] draws: a folded blank, its print (if any), the color of the board's back and of -/// its printed side where the print has no art (straight RGBA), and the view. +/// its printed side where the print has no art (straight RGBA; the board is opaque, so their alpha +/// is not used), and the view. pub struct Scene<'a> { pub blank: &'a Blank, pub folded: &'a Folded, @@ -356,7 +357,9 @@ impl Fill<'_> { if !wins { continue; } - let footprint = self.flat_at(x + 1.0, y).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v)); + // The print's footprint is the longer of a pixel's two sides in flat terms. + let across = |dx: f64, dy: f64| self.flat_at(x + dx, y + dy).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v)); + let footprint = across(1.0, 0.0).max(across(0.0, 1.0)); let color = self.color(u, v, footprint); if let Some(px) = target.color.get_mut(i * 4..i * 4 + 4) { for (o, c) in px.iter_mut().zip(color) { @@ -408,9 +411,9 @@ impl Fill<'_> { } } -fn rgba(c: [u8; 4]) -> [f32; 4] { - let a = f32::from(c[3]) / 255.0; - [f32::from(c[0]) * a, f32::from(c[1]) * a, f32::from(c[2]) * a, f32::from(c[3])] +/// The board color `c` as drawn: its RGB, opaque. +fn opaque(c: [u8; 4]) -> [f32; 4] { + [f32::from(c[0]), f32::from(c[1]), f32::from(c[2]), 255.0] } /// The outline rings of `panel` in flat terms (u, v), flattened finely enough for `scale` pixels a @@ -433,7 +436,7 @@ pub fn render(scene: &Scene) -> Option<Image> { let pixels = width * height; let mut target = Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; - let (inside, outside) = (rgba(scene.inside), rgba(scene.outside)); + let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); let near = camera.eye().map(|(eye, _)| eye * NEAREST); for (rank, &pi) in scene.folded.order.iter().enumerate() { let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index 477040b571..551b671625 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -64,6 +64,49 @@ fn a_flat_panel_takes_the_print_s_color_under_each_pixel() { assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255]); } +#[test] +fn the_board_is_opaque_whatever_the_alpha_of_its_colors() { + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for a in [0, 128] { + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: [200, 100, 50, a], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255], "outside alpha {a}"); + } + // A transparent inside color draws opaque too, on the nearer of two panels seen from the back. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(5.0)]); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 200, 0, 0], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn a_print_squeezed_only_up_and_down_on_screen_samples_a_halved_level() { + // 64 × 64, rows alternating black and white: halved, they average to gray. + let mut px = vec![]; + for y in 0..64 { + for _ in 0..64 { + px.extend(if y % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // Tipped 80°: about 5.8 points a pixel up and down, 1 across. + let camera = Camera { rotate_x: 80.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let reds: Vec<u8> = (0..img.height) + .flat_map(|y| (0..img.width).map(move |x| (x, y))) + .filter(|&(x, y)| img.panel_at(x, y).is_some()) + .map(|(x, y)| pixel(&img, x, y)[0]) + .collect(); + assert!(!reds.is_empty()); + let (lo, hi) = (reds.iter().min().copied().unwrap_or(0), reds.iter().max().copied().unwrap_or(0)); + assert!(hi - lo <= 2, "an even gray, not black and white rows: {lo} to {hi}"); +} + #[test] fn the_back_of_a_panel_shows_the_inside_color() { let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); From 0b8794042155a5e6d6f4175025abab4d2e76e65d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 12:26:26 -0800 Subject: [PATCH 42/48] Packaging Tools: Fold Preview halves the print down to one pixel and reads #-named swatches The print raster stopped after two halvings, so a 2,048-pixel print seen far out sampled a 512-pixel level and fine art aliased. It is now halved down to one pixel, and each halving weighs an odd last row or column by the part of the print it covers, so an edge color does not spread across a small level. A swatch whose name starts with # could not be the inside color, and one named like a hex color drew that hex color. The inside is now looked up as a swatch first and read as #rrggbb only when no swatch with a plain color has that name. --- crates/three-d/src/fold/raster.rs | 40 ++++++++++++++----- crates/three-d/src/fold/raster/tests.rs | 37 ++++++++++++++++- .../ui-egui/src/addons/packaging/preview.rs | 12 +++--- .../src/addons/packaging/preview/tests.rs | 11 ++++- docs/mcp.md | 2 +- 5 files changed, 81 insertions(+), 21 deletions(-) diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs index e481eee15d..9cccbaf6d9 100644 --- a/crates/three-d/src/fold/raster.rs +++ b/crates/three-d/src/fold/raster.rs @@ -115,19 +115,35 @@ impl Level { out } - /// This level at half its size, rounded up, each pixel the mean of the four it covers (an odd - /// last row or column with itself). - fn half(&self) -> Option<Level> { + /// This level at half its size, rounded up, each pixel the mean of the pixels it covers weighted + /// by the area of the full print they cover. A pixel of this level is `step` pixels of the full + /// print (`base` pixels across and down) on a side, and fewer in the last column and row when + /// `base` is not a multiple of `step`. + fn half(&self, base: (u32, u32), step: u32) -> Option<Level> { let (w, h) = (self.width.div_ceil(2), self.height.div_ceil(2)); if (w, h) == (self.width, self.height) { return None; } + // The pixels of the full print that column or row `i` of this level covers, or 0 past it. + let covers = |i: u32, side: u32| u64::from(side).saturating_sub(u64::from(i) * u64::from(step)).min(u64::from(step)) as f32; let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); - for y in 0..i64::from(h) { - for x in 0..i64::from(w) { - let px = [self.at(2 * x, 2 * y), self.at(2 * x + 1, 2 * y), self.at(2 * x, 2 * y + 1), self.at(2 * x + 1, 2 * y + 1)]; - for k in 0..4 { - pixels.push((px.iter().map(|p| p[k]).sum::<f32>() / 4.0).round() as u8); + for y in 0..h { + for x in 0..w { + let mut sum = [0.0f32; 4]; + let mut area = 0.0; + for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] { + if sx >= self.width || sy >= self.height { + continue; + } + let a = covers(sx, base.0) * covers(sy, base.1); + let p = self.at(i64::from(sx), i64::from(sy)); + for (s, c) in sum.iter_mut().zip(p) { + *s += c * a; + } + area += a; + } + for s in sum { + pixels.push(if area > 0.0 { (s / area).round() as u8 } else { 0 }); } } } @@ -135,7 +151,8 @@ impl Level { } } -/// The flat print: the document rect it covers and its raster at full size and at two halvings. +/// The flat print: the document rect it covers and its raster at full size and halved again and +/// again down to one pixel. #[derive(Clone, Debug)] pub struct Print { pub region: Rect, @@ -152,9 +169,10 @@ impl Print { return None; } let mut levels = vec![Level { width, height, pixels }]; - while levels.len() < 3 { - let Some(next) = levels.last().and_then(Level::half) else { break }; + let mut step = 1; + while let Some(next) = levels.last().and_then(|l| l.half((width, height), step)) { levels.push(next); + step *= 2; } Some(Print { region, levels }) } diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index 551b671625..8639615a53 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -177,7 +177,7 @@ fn unusable_views_and_prints_are_refused() { assert!(Print::new(region, MAX_SIDE + 1, 1, vec![0; (MAX_SIDE as usize + 1) * 4]).is_none()); assert!(Print::new(Rect::new(0.0, 0.0, 0.0, 10.0), 1, 1, vec![0; 4]).is_none(), "an empty region"); let p = Print::new(region, 8, 4, vec![255; 8 * 4 * 4]).expect("a print"); - assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(8, 4), (4, 2), (2, 1)]); + assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(8, 4), (4, 2), (2, 1), (1, 1)]); } #[test] @@ -213,6 +213,41 @@ fn a_print_far_smaller_on_screen_samples_a_halved_level() { assert!((80..=150).contains(&r), "gray, not a black or white column: {r}"); } +#[test] +fn a_print_sixteen_times_smaller_on_screen_samples_a_level_halved_four_times() { + // 64 × 64, columns in bands of 4 alternating black and white: halved twice, they still alternate; + // halved four times, they average to gray. + let mut px = vec![]; + for _ in 0..64 { + for x in 0..64 { + px.extend(if (x / 4) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + assert_eq!(print.levels.len(), 7, "64 down to 1"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 3 pixels: about 21 print pixels a view pixel. + let camera = Camera { width: 3, height: 3, scale: 0.03, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 1); + assert!((90..=140).contains(&r), "gray, not a black or white band: {r}"); +} + +#[test] +fn a_halved_level_weighs_an_odd_last_column_by_the_area_it_covers() { + // 9 × 9, black but for a white last column: a ninth of the print, so the one-pixel level is + // a ninth white (255 / 9 is about 28), not half. + let mut px = vec![]; + for _ in 0..9 { + for x in 0..9 { + px.extend(if x == 8 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 9, 9, px).expect("a print"); + assert_eq!(print.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(9, 9), (5, 5), (3, 3), (2, 2), (1, 1)]); + assert_eq!(print.levels.last().map(|l| l.pixels.clone()), Some(vec![28, 28, 28, 255])); +} + #[test] fn the_bounds_take_in_every_folded_panel() { let (b, f) = diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs index a85b8650d9..0b0188f44c 100644 --- a/crates/ui-egui/src/addons/packaging/preview.rs +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -183,14 +183,12 @@ thread_local! { static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); } -/// The board's inside color (straight RGBA) for `inside`: `#rrggbb`, or a swatch of `d` with a -/// plain color; `None` for anything else. +/// The board's inside color (straight RGBA) for `inside`: a swatch of `d` with a plain color, or else +/// `#rrggbb`; `None` for anything else. fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> { - if inside.starts_with('#') { - return vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)); - } - match &d.swatch(inside)?.paint { - vectorcraft_color::Paint::Solid { color, .. } => Some(color.to_rgba8(1.0)), + match d.swatch(inside).map(|s| &s.paint) { + Some(vectorcraft_color::Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), + _ if inside.starts_with('#') => vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)), _ => None, } } diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index 9fdfb1972e..974556032b 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; -use super::{Cache, ID, PrintKey, Settings, last_image, last_rect, prints_rendered, show, status, work_done}; +use super::{Cache, ID, PrintKey, Settings, inside_color, last_image, last_rect, prints_rendered, show, status, work_done}; use crate::{VectorcraftApp, menus}; /// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each @@ -123,6 +123,15 @@ fn ui_fold_preview_sets_the_window_and_refuses_bad_values() { // A swatch with a plain color names the inside. app.run("ui.foldPreview", json!({"inside": "White"})).unwrap(); assert_eq!(app.ui.fold_preview.inside, "White"); + // So does one whose name starts with #, and a swatch's name comes before a #rrggbb that reads the same. + app.run("swatch.new", json!({"name": "#brand", "color": "#0000ff"})).unwrap(); + app.run("swatch.new", json!({"name": "#00ff00", "color": "#0000ff"})).unwrap(); + app.run("ui.foldPreview", json!({"inside": "#brand"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "#brand"); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, "#brand"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#00ff00"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#ff0000"), Some([255, 0, 0, 255])); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index ac07dd1799..4aa61fb48b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13235,7 +13235,7 @@ and the print is a raster whose longest side is 2,048 pixels, rendered again whe perspective?, inside?, showFoldLines?, base?}`) sets the window, shows it and draws it again. A second run leaves the window open. `rotateX` (-180 to 180) tips the top toward the viewer and `rotateY` (-180 to 180) turns the right side toward the viewer, in degrees; `zoom` is 0.1 to 8, where 1 fits the folded blank; `perspective` is the field of view, 0 to -160 degrees, 0 for none; `inside` is `#rrggbb` or the name of a swatch with a plain color; `base` is a point in a panel +160 degrees, 0 for none; `inside` is the name of a swatch with a plain color, or else `#rrggbb`; `base` is a point in a panel of the document's blanks, or null for the largest panel. With perspective, the zoom of 1 keeps the eye at least twice the folded blank's radius from its middle. A value of the wrong kind or out of range is an error and sets nothing. VectorCraft's own defaults are a Three-Quarter view (`rotateX` 25, `rotateY` 35), no perspective, a white inside and the From b33409d1a5470ea886052951b4e129a661e39bfe Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 15:56:02 -0800 Subject: [PATCH 43/48] MCP: the headless UI catalog lists ui.foldPreview Regenerated crates/mcp/src/ui_catalog.rs with `cargo xtask ui-commands` so it matches the ui.foldPreview row in crates/ui-egui/src/menus/ui_commands.rs. --- crates/mcp/src/ui_catalog.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index f81ea2f7f9..784ebbf11b 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1147,6 +1147,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.foldPreview", + "Fold Preview", + "", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb or the name of a swatch with a plain color (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + ), ( "ui.copyScriptConsole", "Copy Script Console", From 54c415468b30cc6351f081bd368ad787d7c8e6b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 16:40:36 -0800 Subject: [PATCH 44/48] i18n: dialog labels use the language's colon MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dialogs and the toolbar editors added a plain ":" after a translated label, so French showed "Points isolés:" without the no-break space before the colon. A new `i18n::colon` helper appends the catalog's ":" row instead. French writes U+00A0 before the colon, Chinese and Japanese write a full-width colon, and English and the other languages are unchanged. - Field labels: the generic parameter dialogs, Text Flow, Radial Blur's Horizontal and Vertical, the graph type dialog, and the headings of the toolbar drawer and the Add Tool menu. - A label followed by a value: Radial Blur's Blur Center value for screen readers, the Simplify point count, the Dimension preview, the Revolve reset tooltip, Smart Punctuation's report, the PDF and print option summaries, the PSD import layer count, the Recolor color share tooltip, the Revolve light names and the script check's problems. - The style dialogs' attribute list showed two colons ("Font Size:: 12"). It now shows one. Part of #7991 (reported by bortekfr). --- crates/ui-egui/src/custom_toolbars.rs | 4 +- .../ui-egui/src/dialogs/char_style_options.rs | 2 +- crates/ui-egui/src/dialogs/command.rs | 2 +- crates/ui-egui/src/dialogs/dimension.rs | 2 +- crates/ui-egui/src/dialogs/effect.rs | 12 +++- crates/ui-egui/src/dialogs/form.rs | 10 +++- crates/ui-egui/src/dialogs/graph_type.rs | 20 ++++++- crates/ui-egui/src/dialogs/new_text_style.rs | 2 +- .../ui-egui/src/dialogs/para_style_options.rs | 2 +- crates/ui-egui/src/dialogs/path_ops.rs | 2 +- crates/ui-egui/src/dialogs/psd_import.rs | 2 +- crates/ui-egui/src/dialogs/recolor.rs | 3 +- crates/ui-egui/src/dialogs/revolve.rs | 2 +- crates/ui-egui/src/dialogs/revolve_lights.rs | 3 +- crates/ui-egui/src/dialogs/save_pdf.rs | 2 +- crates/ui-egui/src/dialogs/script_check.rs | 2 +- .../ui-egui/src/dialogs/smart_punctuation.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 58 +++++++++++++++++++ crates/ui-egui/src/dialogs/tests_modal.rs | 8 +++ crates/ui-egui/src/edit_toolbar.rs | 2 +- crates/ui-egui/src/edit_toolbar/tests.rs | 30 ++++++++++ crates/ui-egui/src/i18n.rs | 7 +++ crates/ui-egui/src/i18n/tests.rs | 11 ++++ 23 files changed, 167 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index f8c3033a5e..e54085e304 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -1382,7 +1382,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect(); let heading = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).size(12.0).color(t.text_strong)); if !held.is_empty() { - heading(ui, &format!("{}:", tl!("Remove Tool"))); + heading(ui, &crate::i18n::colon(tl!("Remove Tool"))); for tool in held.iter().filter_map(|id| tool_info(id)) { if widgets::menu_item(ui, tool.label, true, false) { actions.push(Action::RemoveTool(bar.name.clone(), tool.id)); @@ -1391,7 +1391,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & ui.separator(); } for (cat, tools) in crate::edit_toolbar::sections() { - heading(ui, &format!("{}:", tl!(cat))); + heading(ui, &crate::i18n::colon(tl!(cat))); for tool in tools { if widgets::menu_item(ui, tool.label, !held.contains(&tool.id), false) { actions.push(Action::AddTool(bar.name.clone(), tool.id)); diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 02515a3b89..b4abf8c6e2 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1073,7 +1073,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index f5215092e8..052eb030d0 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -36,7 +36,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let mut rows = v.as_str() == Some("rows"); ui.add_space(4.0); egui::Grid::new("text-flow").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { - let row = ui.label(egui::RichText::new(format!("{}:", tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); ui.label_inputs_by(row.id, |ui| { ui.horizontal(|ui| { if widgets::radio(ui, tl!("By Rows"), rows, true) { diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 140ace0fde..1a08c4d377 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -211,7 +211,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { Ok(o) => { let sample = o.label(72.0, false).unwrap_or_default(); let t = Tokens::get(ui.ctx()); - ui.label(RichText::new(format!("{}: {sample}", tl!("Preview (1 inch on the page)"))).color(t.text)); + ui.label(RichText::new(format!("{} {sample}", crate::i18n::colon(tl!("Preview (1 inch on the page)")))).color(t.text)); } Err(e) => { ui.colored_label(Tokens::get(ui.ctx()).text, e); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index ac2798ec40..2ac68d5b9c 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -317,6 +317,13 @@ fn center_round(x: f64) -> f64 { (x * 1e4).round() / 1e4 } +/// The value screen readers give Blur Center at `c` (0 to 1 of the bounds): Horizontal and +/// Vertical in percent, each label followed by the UI language's colon. +pub(super) fn blur_center_value(c: [f64; 2]) -> String { + let percent = |v: f64| (v * 1000.0).round() / 10.0; + format!("{} {}%, {} {}%", crate::i18n::colon(tl!("Horizontal")), percent(c[0]), crate::i18n::colon(tl!("Vertical")), percent(c[1])) +} + /// Radial Blur's Blur Center: a box standing for the object's bounds, with the blur's pattern (rays /// for Zoom, rings for Spin) drawn about the center. A press or a drag in the box puts the center /// there; with the keyboard focus the arrow keys move it 1 % of the box (10 % with Shift). The @@ -334,9 +341,8 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { let (rect, _) = ui.allocate_exact_size(egui::vec2(CENTER_BOX, CENTER_BOX), Sense::hover()); let id = ui.scope_id().with("radial-blur-center"); let resp = ui.interact(rect, id, Sense::click_and_drag()); - let percent = |v: f64| (v * 1000.0).round() / 10.0; let name = tl!("Blur Center").to_string(); - let value = format!("{}: {}%, {}: {}%", tl!("Horizontal"), percent(c[0]), tl!("Vertical"), percent(c[1])); + let value = blur_center_value(c); let enabled = ui.is_enabled(); resp.widget_info(|| egui::WidgetInfo { current_text_value: Some(value.clone()), @@ -391,7 +397,7 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { ui.vertical(|ui| { egui::Grid::new("blur-center-fields").num_columns(2).spacing([8.0, 8.0]).show(ui, |ui| { for (i, label) in ["Horizontal", "Vertical"].into_iter().enumerate() { - let row = ui.label(egui::RichText::new(format!("{}:", tl!(label))).color(t.text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!(label))).color(t.text)); ui.label_inputs_by(row.id, |ui| { if let Some(x) = widgets::range_field_named(ui, ("blur-center", i), None, c[i] * 100.0, 0.0..=100.0, &form::unit_suffix("%"), 1, 72.0) diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index d386c1f028..6a99f4abed 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -832,11 +832,17 @@ pub(crate) fn humanize(k: &str) -> String { } } -/// [`humanize`] translated where it is painted: the ":" stays outside the translated text. +/// A style attribute as the style dialogs list it: the [`humanized`] key, then its value. +pub(super) fn attribute_line(key: &str, value: &Value) -> String { + format!("{} {value}", humanized(key)) +} + +/// [`humanize`] translated where it is painted: the ":" stays outside the translated text and is +/// written as the UI language writes a label's colon ([`crate::i18n::colon`]). pub(super) fn humanized(k: &str) -> String { let h = humanize(k); match h.strip_suffix(':') { - Some(base) => format!("{}:", tl!(base)), + Some(base) => crate::i18n::colon(tl!(base)), None => tl!(&h).to_string(), } } diff --git a/crates/ui-egui/src/dialogs/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 838ba066d9..766ae898ee 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -577,9 +577,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// `text` with the colon of a field label. +/// `text` with the colon of a field label, as the UI language writes it. fn colon(text: &str) -> String { - format!("{text}:") + crate::i18n::colon(text) } /// A checkbox bound to `d.fields[key]`, dimmed while the type picked has no use for it. @@ -977,6 +977,22 @@ mod tests { assert!(app.ui.dialog.is_none()); } + /// Field labels end in the UI language's colon: in French a no-break space and a colon (#7991). + #[test] + fn field_labels_use_the_language_colon() { + let mut app = app_with_graph("column"); + crate::menus::invoke(&mut app, COMMAND, json!({})); + set(&mut app, PAGE, json!("valueAxis")); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let mut h = harness(app); + h.run_steps(3); + let want = format!("{}\u{a0}:", crate::i18n::tr(fr, "Suffix")); + let found = h.query_by_role_and_label(Role::TextInput, &want).is_some(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(found, "a text field named {want:?}"); + } + /// A Type button changes the graph's type and keeps its data. #[test] fn a_type_button_changes_the_graph_type_and_keeps_its_data() { diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 4978a6a1f6..82f0c7d78b 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -77,7 +77,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); if let Ok(attrs) = super::char_style_options::edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } }); diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index d63d43be89..9a9da0c164 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -952,7 +952,7 @@ pub(crate) fn general_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 3a62eae1f4..3ffc496dd6 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -198,7 +198,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { && let Some(counts) = d.fields.get("__counts") && let (Some(before), Some(after)) = (counts["before"].as_u64(), counts["after"].as_u64()) { - ui.label(format!("{}: {before} → {after}", tl!("Anchor Points"))); + ui.label(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))); } } false diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs index 950b15c763..c5a4c905a0 100644 --- a/crates/ui-egui/src/dialogs/psd_import.rs +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -167,7 +167,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0); - widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers"))); + widgets::dim_label(ui, &format!("{} × {} px · {} {}", count("width"), count("height"), crate::i18n::colon(tl!("Layers")), count("layers"))); // Offered only for a file with slices, with either conversion. let sliced = count("slices") > 0; ui.add_space(8.0); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e3829f92b5..024de90241 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -357,7 +357,8 @@ fn prominent_bar(ui: &mut Ui, d: &mut Dialog, rows: &[Value]) { let c = to_color(&rows[*i]).or_else(|| from_colors(&rows[*i]).first().copied()).unwrap_or_default(); chip(ui, r, c, false); let share = (widths[n] * 100.0).round(); - ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()).on_hover_text(format!("{} {}: {share}%", tl!("Color"), i + 1)); + ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()) + .on_hover_text(format!("{} {share}%", crate::i18n::colon(&format!("{} {}", tl!("Color"), i + 1)))); left = right; } let mut ended = false; diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 77c5980ec0..c7c98a5de0 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -733,7 +733,7 @@ pub(super) fn reset_dot(ui: &mut egui::Ui, key: &str, changed: bool, default: &s ui.painter().rect_filled(r, 3.0, Tokens::get(ui.ctx()).hover); } dot(ui, r.center(), changed); - response.on_hover_text(format!("{}: {default}", tl!("Reset to default"))).clicked() + response.on_hover_text(format!("{} {default}", crate::i18n::colon(tl!("Reset to default")))).clicked() } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 3d522b624a..dadab71c70 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -75,7 +75,8 @@ impl Light { /// The name screen readers give the light at `index`: its number, Rotation, Height and side. fn name(self, index: usize) -> String { let side = if self.behind { format!(", {}", tl!("Light behind the object")) } else { String::new() }; - format!("{} {}: {} {:.1}°, {} {:.1}°{side}", c3("Light"), index + 1, tl!("Rotation"), self.rotation, tl!("Height"), self.height) + let light = crate::i18n::colon(&format!("{} {}", c3("Light"), index + 1)); + format!("{light} {} {:.1}°, {} {:.1}°{side}", tl!("Rotation"), self.rotation, tl!("Height"), self.height) } } diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 4f8bdf7667..d4fb4a8937 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -871,7 +871,7 @@ pub(super) fn option_rows<'a>(ui: &mut egui::Ui, changed: impl IntoIterator<Item Value::String(s) => s.clone(), other => other.to_string(), }; - ui.label(egui::RichText::new(format!("{}: {value}", label(c["option"].as_str().unwrap_or_default()))).color(t.text)); + ui.label(egui::RichText::new(format!("{} {value}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())))).color(t.text)); } } diff --git a/crates/ui-egui/src/dialogs/script_check.rs b/crates/ui-egui/src/dialogs/script_check.rs index 257227cc6f..e134cf1b39 100644 --- a/crates/ui-egui/src/dialogs/script_check.rs +++ b/crates/ui-egui/src/dialogs/script_check.rs @@ -271,7 +271,7 @@ fn report(ui: &mut egui::Ui, r: &Value, t: &Tokens) { for p in problems { let Some(label) = p["code"].as_str().and_then(problem_label) else { continue }; let label = match p["detail"].as_str() { - Some(detail) => format!("{label}: {detail}"), + Some(detail) => format!("{} {detail}", crate::i18n::colon(label)), None => label.to_string(), }; row(ui, t, &label, false, &place(p)); diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index 1ebe084e02..ce6f62c6a2 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -98,7 +98,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let lines: Vec<String> = options() .into_iter() .filter(|(key, ..)| d.bool(key)) - .map(|(_, count, label)| format!("{label}: {}", r["replaced"][count].as_u64().unwrap_or(0))) + .map(|(_, count, label)| format!("{} {}", crate::i18n::colon(label), r["replaced"][count].as_u64().unwrap_or(0))) .collect(); super::confirm::tell(app, tl!("Smart Punctuation"), &lines.join("\n")); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 201b34171d..e01668155f 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -178,6 +178,64 @@ fn effect_preview_is_kept_as_one_undo_step() { assert_eq!(app.session.doc().unwrap().doc, before); } +/// A field label's colon is written as the UI language writes it, in the generic parameter +/// dialogs and the effect dialogs alike (#7991): French puts a no-break space before it, Chinese +/// writes a full-width colon, and English is unchanged. +#[test] +fn field_label_colons_follow_the_ui_language() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let text = + app.run("text.create", json!({"x": 20, "y": 80, "text": "Hello", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap(); + // Each dialog, opened the way its menu item opens it, and the label it shows. + let entries = crate::menus::menu_entries(&app); + let clean_up = entries.iter().find(|e| e.path == ["Object", "Path"] && e.label == "Clean Up…").expect("listed"); + let clean_up = crate::menus::click_target(&clean_up.label, clean_up.command.as_deref().unwrap(), &clean_up.params); + let dialogs = [ + (clean_up.0, clean_up.1, "Stray Points"), + ("effect.dialog".to_string(), json!({"effect": "blur.radial"}), "Horizontal"), + ("text.areaOptions".to_string(), json!({}), "Text Flow"), + ]; + for (command, params, label) in dialogs { + app.run("select.set", json!({"ids": [text]})).unwrap(); + if command != "text.areaOptions" { + app.run("select.all", json!({})).unwrap(); + } + crate::menus::invoke(&mut app, &command, params); + assert!(app.ui.dialog.is_some(), "{command} opened no dialog"); + for (code, colon) in [("fr", "\u{a0}:"), ("zh-hans", ":"), ("en", ":")] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}{colon}", crate::i18n::tr(lang, label)); + assert!(shown.lines().any(|l| l.trim() == want), "{command}, {code}: {want:?} in {shown}"); + if code == "fr" { + let bare: Vec<_> = shown.lines().map(str::trim).filter(|l| l.ends_with(':') && !l.ends_with("\u{a0}:")).collect(); + assert!(bare.is_empty(), "{command}: French labels with a bare colon: {bare:?}"); + } + } + app.ui.dialog = None; + } + assert_eq!(super::form::humanized("strayPoints"), "Stray Points:", "English is unchanged"); +} + +/// A label followed by its value takes the UI language's colon too (#7991): Blur Center's value for +/// screen readers, and a style's attribute list, which no longer shows a second colon. +#[test] +fn label_and_value_colons_follow_the_ui_language() { + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let center = super::effect::blur_center_value([0.5, 0.25]); + let attribute = super::form::attribute_line("fontSize", &json!(12)); + crate::i18n::set_current(crate::i18n::Lang::EN); + let (h, v) = (crate::i18n::tr(fr, "Horizontal"), crate::i18n::tr(fr, "Vertical")); + assert_eq!(center, format!("{h}\u{a0}: 50%, {v}\u{a0}: 25%")); + assert_eq!(attribute, format!("{}\u{a0}: 12", crate::i18n::tr(fr, "Font Size"))); + assert_eq!(super::effect::blur_center_value([0.5, 0.25]), "Horizontal: 50%, Vertical: 25%"); + assert_eq!(super::form::attribute_line("fontSize", &json!(12)), "Font Size: 12"); +} + /// Drop Shadow's Color typed as text the effect can't draw: OK returns the error and keeps the /// dialog open, with Preview on or off, and the document stays as it was. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 06eef4d2c6..29a37ac4ad 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -678,6 +678,14 @@ fn simplify_dialog_preview_counts_and_cancel_restore_the_original() { let texts = frame(&ctx, &mut app, vec![]); let preview = texts.iter().find(|(t, _)| t == "Preview").map(|(_, r)| *r).expect("a Preview checkbox"); assert!(texts.iter().any(|(t, _)| t == "Anchor Points: 20 → 2"), "the reduction is visible: {texts:?}"); + // In French the label ends in a no-break space and a colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let french = frame(&ctx, &mut app, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}\u{a0}: 20 → 2", crate::i18n::tr(fr, "Anchor Points")); + assert!(french.iter().any(|(t, _)| *t == want), "{want:?} in {french:?}"); + frame(&ctx, &mut app, vec![]); assert!(app.session.in_interaction()); assert!(app.session.doc().unwrap().selection.anchors.is_empty()); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len); diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index d58351ac21..51155e710f 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -532,7 +532,7 @@ pub(crate) fn drawer(app: &mut VectorcraftApp, ctx: &egui::Context) { let inner = ui.available_width() - 10.0; for (cat, gs) in groups() { ui.add_space(6.0); - ui.label(egui::RichText::new(format!("{}:", tl!(cat))).size(12.0).color(t.text_strong)); + ui.label(egui::RichText::new(crate::i18n::colon(tl!(cat))).size(12.0).color(t.text_strong)); ui.add_space(4.0); for g in gs { // A flyout group: its tools framed together, as one toolbar button holds them. diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index fedfe9dcfd..ad6061e041 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -319,6 +319,25 @@ fn tools_in_the_toolbar_are_dimmed_in_the_drawer() { assert_eq!(cell_at(&shown, drawer, "Artboard Tool").1, dim); } +/// The drawer's headings end in the UI language's colon: in French a no-break space and a colon +/// (#7991), in English a plain colon. +#[test] +fn drawer_headings_use_the_language_colon() { + let mut app = app(); + let ctx = ctx(); + app.run("window.editToolbar", json!({"open": true})).unwrap(); + for (code, colon) in [("fr", "\u{a0}:"), ("en", ":")] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + frame(&mut app, &ctx, 0.0, vec![]); + let shown = frame(&mut app, &ctx, 0.1, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + let drawer = drawer_rect(&ctx).unwrap(); + let want = format!("{}{colon}", crate::i18n::tr(lang, "Select")); + assert!(shown.iter().any(|(s, p, _)| s.trim() == want && drawer.contains(*p)), "{code}: {want:?}"); + } +} + /// #1018: tools drag from the drawer onto the toolbar (between two tools, or onto one to join /// its group), from the toolbar into the drawer, and within the toolbar, only while the drawer /// is open. @@ -543,6 +562,17 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { click(&mut app, &ctx, 40.0, items(&shown, "Lasso Tool")[0].0); assert_eq!(mine(&app), [["magicWand"]]); assert_eq!(slots(&app), shipped); + // In French the menu's headings end in a no-break space and a colon (#7991). + open(&mut app, 49.0); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + frame(&mut app, &ctx, 49.7, vec![]); + let french = frame(&mut app, &ctx, 49.8, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + for heading in ["Remove Tool", "Select"] { + let want = format!("{}\u{a0}:", crate::i18n::tr(fr, heading)); + assert_eq!(items(&french, &want).len(), 1, "{want:?}"); + } } /// New Toolbar… in the drawer's menu opens the New Toolbar dialog, which asks for a name. diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index d54ea0178a..34a3773510 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -623,6 +623,13 @@ pub fn t(s: &str) -> &str { tr(current(), s) } +/// `label`, already in the current language, followed by a field label's colon as the current +/// language writes it (its catalog row for ":"): French puts a no-break space before the colon, and +/// Chinese and Japanese write a full-width colon. +pub fn colon(label: &str) -> String { + format!("{label}{}", t(":")) +} + /// Translate an English UI string; unknown strings come back unchanged. pub fn tr(lang: Lang, s: &str) -> &str { lang.catalog().plain(s).unwrap_or(s) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ed4b44b0da..8a64501801 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2041,6 +2041,17 @@ fn georgian_rows_have_no_mtavruli() { assert!(caps.is_empty(), "Mtavruli in ka.tsv: {caps:?}"); } +/// A field label's colon follows the catalog's ":" row: French puts a no-break space before it, +/// Chinese and Japanese write a full-width colon, and English and German write a plain colon. +#[test] +fn label_colons_follow_the_language() { + for (code, want) in [("fr", "X\u{a0}:"), ("zh-hans", "X:"), ("zh-hant", "X:"), ("ja", "X:"), ("de", "X:"), ("en", "X:")] { + set_current(Lang::from_code(code).expect("registered")); + assert_eq!(colon("X"), want, "{code}"); + } + set_current(Lang::EN); +} + /// French rows follow the typography fr.tsv's header sets: a no-break space before : ; ? ! and inside /// « », and the typographic apostrophe ’ in elisions. Text in backticks is code and is not checked, and /// a straight apostrophe inside double quotes is a literal value. From f84fc7a6aea429a425e50e841323e3e597b88566 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 17:44:20 -0800 Subject: [PATCH 45/48] Packaging Tools: Fold Preview's White inside stays white beside a swatch named #ffffff The built-in White inside is stored as an empty value instead of #ffffff, so a swatch named #ffffff no longer replaces it. ui.foldPreview takes an empty inside for white; a swatch's name still comes before a #rrggbb that reads the same. --- crates/mcp/src/ui_catalog.rs | 2 +- .../ui-egui/src/addons/packaging/preview.rs | 29 +++++++++++-------- .../src/addons/packaging/preview/tests.rs | 7 +++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 2 +- 5 files changed, 27 insertions(+), 15 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 784ebbf11b..bda3464573 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1151,7 +1151,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.foldPreview", "Fold Preview", "", - "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb or the name of a swatch with a plain color (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", ), ( "ui.copyScriptConsole", diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs index 0b0188f44c..97a8ebd988 100644 --- a/crates/ui-egui/src/addons/packaging/preview.rs +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -64,7 +64,7 @@ pub struct Settings { pub pan: [f64; 2], /// The field of view in degrees; 0 for none. pub perspective: f64, - /// The board's inside color: `#rrggbb` or the name of a swatch. + /// The board's inside color: `#rrggbb`, the name of a swatch, or empty for white. pub inside: String, /// Draw the fold lines on the print. pub show_fold_lines: bool, @@ -82,7 +82,7 @@ impl Default for Settings { zoom: 1.0, pan: [0.0; 2], perspective: 0.0, - inside: "#ffffff".into(), + inside: String::new(), show_fold_lines: false, base: None, } @@ -183,9 +183,12 @@ thread_local! { static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); } -/// The board's inside color (straight RGBA) for `inside`: a swatch of `d` with a plain color, or else -/// `#rrggbb`; `None` for anything else. +/// The board's inside color (straight RGBA) for `inside`: white when it is empty, a swatch of `d` +/// with a plain color, or else `#rrggbb`; `None` for anything else. fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> { + if inside.is_empty() { + return Some([255; 4]); + } match d.swatch(inside).map(|s| &s.paint) { Some(vectorcraft_color::Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), _ if inside.starts_with('#') => vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)), @@ -347,12 +350,14 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri match p.get("inside") { None | Some(Value::Null) => {} Some(v) => { - let inside = v.as_str().unwrap_or_default(); - let known = app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some() - || (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some()); - if !known { - return Err(format!("`inside` must be #rrggbb or the name of a swatch with a plain color, not {v}")); - } + let inside = v.as_str().filter(|inside| { + inside.is_empty() + || app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some() + || (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some()) + }); + let Some(inside) = inside else { + return Err(format!("`inside` must be #rrggbb, the name of a swatch with a plain color, or empty for white, not {v}")); + }; set.inside = inside.to_string(); } } @@ -413,10 +418,10 @@ fn toolbar(app: &VectorcraftApp, ui: &mut Ui, set: &mut Settings) { }); let mut names: Vec<&str> = vec![tl!("White")]; names.extend(swatches.iter().map(String::as_str)); - let shown = if set.inside == "#ffffff" { tl!("White") } else { set.inside.as_str() }; + let shown = if set.inside.is_empty() { tl!("White") } else { set.inside.as_str() }; ui.label(tl!("Inside")); if let Some(i) = widgets::dropdown_names_named(ui, "fold-preview-inside", Some(tl!("Inside")), shown, &names, 110.0) { - set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_else(|| "#ffffff".into()); + set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_default(); } if widgets::check(ui, tl!("Show Fold Lines"), set.show_fold_lines, true) { set.show_fold_lines = !set.show_fold_lines; diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index 974556032b..c3c69c3f31 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -132,6 +132,13 @@ fn ui_fold_preview_sets_the_window_and_refuses_bad_values() { assert_eq!(inside_color(doc, "#brand"), Some([0, 0, 255, 255])); assert_eq!(inside_color(doc, "#00ff00"), Some([0, 0, 255, 255])); assert_eq!(inside_color(doc, "#ff0000"), Some([255, 0, 0, 255])); + // White, the default, stays white beside a swatch named #ffffff. + app.run("swatch.new", json!({"name": "#ffffff", "color": "#0000ff"})).unwrap(); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, &Settings::default().inside), Some([255; 4])); + assert_eq!(inside_color(doc, "#ffffff"), Some([0, 0, 255, 255])); + app.run("ui.foldPreview", json!({"inside": ""})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, ""); } #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index af7f870f83..4b5cb8b95d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1152,7 +1152,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.foldPreview", "Fold Preview", "", - "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb or the name of a swatch with a plain color (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", ), ( "ui.copyScriptConsole", diff --git a/docs/mcp.md b/docs/mcp.md index 657c6f2e35..e915486698 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13251,7 +13251,7 @@ and the print is a raster whose longest side is 2,048 pixels, rendered again whe perspective?, inside?, showFoldLines?, base?}`) sets the window, shows it and draws it again. A second run leaves the window open. `rotateX` (-180 to 180) tips the top toward the viewer and `rotateY` (-180 to 180) turns the right side toward the viewer, in degrees; `zoom` is 0.1 to 8, where 1 fits the folded blank; `perspective` is the field of view, 0 to -160 degrees, 0 for none; `inside` is the name of a swatch with a plain color, or else `#rrggbb`; `base` is a point in a panel +160 degrees, 0 for none; `inside` is the name of a swatch with a plain color, or else `#rrggbb`, or `""` for white; `base` is a point in a panel of the document's blanks, or null for the largest panel. With perspective, the zoom of 1 keeps the eye at least twice the folded blank's radius from its middle. A value of the wrong kind or out of range is an error and sets nothing. VectorCraft's own defaults are a Three-Quarter view (`rotateX` 25, `rotateY` 35), no perspective, a white inside and the From e38bfffad7dbc4a23ea4b7755109f5ce7ab0180b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 04:14:41 -0800 Subject: [PATCH 46/48] i18n: French messages use the narrow no-break space before colons The five French script file messages added on this branch put an ordinary space before ":" and ";". They now use U+202F, which french_catalog_uses_nonbreaking_prose_punctuation accepts. --- crates/ui-egui/src/i18n/fr.tsv | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4ca3b9a58a..4234ce6876 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4590,7 +4590,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l’application, la personne répond à chaque boîte de dialogue @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 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 @@ -4603,14 +4603,14 @@ liquify-list-end {0}, {1} {0} et {1} @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 {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 `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 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 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 Copied the link info Informations sur le lien copiées @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} From 7cabf5647137d5ca7c2cf9984f0f2c4a412a4ce5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 06:50:42 -0800 Subject: [PATCH 47/48] Scripts: the app idles while a run waits at its file dialog While a script waited at File.openDialog, File.saveDialog or Folder.selectDialog, the frame logic asked for a new frame on every frame. It now skips that request while a file dialog waits, as it does for alert, confirm and prompt; picks::poll still looks for the dialog's answer. --- crates/ui-egui/src/app.rs | 9 +++++++-- crates/ui-egui/src/tests/script_run.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 5319defaa2..f8c608cc28 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -356,8 +356,13 @@ impl VectorcraftApp { // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); - if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() { - // A script in `$.sleep` goes on when its time is up; until then the app can idle. + if self.session.script_running() + && !self.session.script_waiting() + && self.session.script_dialog().is_none() + && self.session.script_picker().is_none() + { + // A script in `$.sleep` goes on when its time is up; until then the app can idle. A + // script at a file dialog goes on when the dialog answers, and `picks::poll` looks for that. match self.session.script_sleep_left() { Some(left) => ctx.request_repaint_after(left), None => ctx.request_repaint(), diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 882799385e..fee27caa13 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -281,6 +281,32 @@ fn a_stop_names_the_files_the_run_left_written() { let _ = std::fs::remove_dir_all(&dir); } +/// While a run waits at its file dialog, the app's frame logic does not ask for a frame on every +/// frame. +#[test] +fn a_run_waiting_at_its_file_dialog_lets_the_app_idle() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "Folder.selectDialog('Folder');" })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_picker().is_some(), "the run waits at its folder dialog"); + let ctx = egui::Context::default(); + let mut wait = std::time::Duration::ZERO; + for frame in 0..4 { + let time = f64::from(frame); + app.now_override = Some(time); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| app.logic(ui.ctx())); + out.textures_delta.clear(); + wait = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay); + } + assert!(app.session.script_picker().is_some(), "the run still waits"); + assert!(wait > std::time::Duration::from_millis(100), "{wait:?}: {:?}", ctx.repaint_causes()); + assert!(app.session.script_request_stop()); + finish(&mut app); +} + /// 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] From af09fc206449a8d49400e0efeb9f9a775bcd5e7d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 07:14:42 -0800 Subject: [PATCH 48/48] Scripts: open files are written in the order they were opened When two File objects held changes to the same file, copy, length, a new open of the file and a withdrawn grant wrote them in no fixed order, so the copy or the file could end up with the older object's bytes. They now write them in the order the objects were opened, as the end of the run does. --- crates/engine/src/script/files.rs | 21 +++++++---- crates/engine/src/tests/script_io.rs | 54 ++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 05f148e714..6eecfeabf8 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -407,8 +407,10 @@ impl Disk { self.writes.remove(&g.path, g.folder); } } - let ids: Vec<u32> = + let mut ids: Vec<u32> = self.open.iter().filter(|(_, o)| o.target.as_deref().is_some_and(|t| !self.writes.allows(t))).map(|(id, _)| *id).collect(); + // In the order the files were opened, as `flush_all` writes them. + ids.sort_unstable(); for id in ids { let written = self.flush(id).is_ok(); if let Some(o) = self.open.get_mut(&id) { @@ -701,8 +703,9 @@ impl Disk { 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<u32> = self.open.iter().filter(|(_, o)| o.target.as_deref() == Some(real.as_path())).map(|(id, _)| *id).collect(); + // they do not later replace what this one writes, in the order they were opened. + let mut ids: Vec<u32> = self.open.iter().filter(|(_, o)| o.target.as_deref() == Some(real.as_path())).map(|(id, _)| *id).collect(); + ids.sort_unstable(); if let Err(m) = ids.iter().try_for_each(|id| self.flush(*id)) { return fail(m); } @@ -1795,8 +1798,10 @@ fn copy(host: &Host, a: &[Data]) -> Result<Data, HostError> { // 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<u32> = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(source.as_path())).map(|(id, _)| *id).collect(); + // The source's open objects write what they hold first, in the order they were opened, so the + // copy has it. + let mut ids: Vec<u32> = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(source.as_path())).map(|(id, _)| *id).collect(); + ids.sort_unstable(); if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { return Ok(error(m)); } @@ -1988,8 +1993,10 @@ fn set_length(host: &Host, a: &[Data]) -> Result<Data, HostError> { let len = usize::try_from(n).unwrap_or(usize::MAX); let held = disk.open.values().filter(|o| o.holds(&target)).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<u32> = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(target.as_path())).map(|(id, _)| *id).collect(); + // The file's open objects write what they hold first, in the order they were opened, and + // then hold the new length. + let mut ids: Vec<u32> = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(target.as_path())).map(|(id, _)| *id).collect(); + ids.sort_unstable(); 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)) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index eca6dd5638..7c8c167527 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -908,6 +908,29 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// Two objects that changed the same file write it in the order they were opened, so the one opened +/// last is written last, before the file is copied, given a new length or opened again. +#[test] +fn script_files_changed_by_two_objects_are_written_in_the_order_they_were_opened() { + let base = folder("twowriters"); + let r = run( + &base, + "var d = Folder.temp.fsName, out = [];\n\ + function two(name) { var p = d + '/' + name, s = new File(p); s.open('w'); s.write('xx'); s.close();\n\ + var a = new File(p), b = new File(p); a.open('e'); b.open('e'); a.write('A'); b.write('B'); return [a, b, p]; }\n\ + function done(h) { h[0].close(); h[1].close(); }\n\ + function text(p) { var f = new File(p); f.open('r'); var t = f.read(); f.close(); return t; }\n\ + for (var i = 0; i < 24; i++) {\n\ + var h = two('c' + i + '.txt'); h[0].copy(d + '/copy.txt'); out.push(text(d + '/copy.txt')); done(h);\n\ + h = two('l' + i + '.txt'); new File(h[2]).length = 1; done(h); out.push(text(h[2]));\n\ + h = two('o' + i + '.txt'); var c = new File(h[2]); c.open('e'); out.push(c.read()); c.close(); done(h);\n\ + }\n\ + vc.log(out.join(','));", + ); + assert_eq!(r["log"], json!([vec!["Bx,B,Bx"; 24].join(",")]), "{r}"); + let _ = std::fs::remove_dir_all(base); +} + /// An object that has a file open for reading holds what `copy` writes over the file and the length /// `length` sets, as an object open for writing does, also after the file is renamed, and not after /// it is removed. @@ -1995,6 +2018,37 @@ fn script_files_open_under_a_withdrawn_grant_keep_their_unwritten_changes() { let _ = std::fs::remove_dir_all(base); } +/// Files opened for writing under a kept grant that new code withdraws are written in the order +/// they were opened, so the object opened last is written last. +#[test] +fn script_files_open_under_a_withdrawn_grant_are_written_in_the_order_they_were_opened() { + let base = folder("grantwithdrawnorder"); + 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('x'); var all = [f];\n\ + for (var i = 1; i < 64; i++) {{ var g = new File(f.fsName); g.open('e'); all.push(g); }}\n\ + for (var i = 0; i < 64; i++) all[i].write(('0' + i).slice(-2));\n\ + eval('1'); vc.log(['wrote']); }}", + 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(); + assert!(r.is_ok(), "{report}"); + assert_eq!(report["log"], json!([["wrote"]]), "{report}"); + assert_eq!(std::fs::read(&out).unwrap(), b"63", "{report}"); + let _ = std::fs::remove_dir_all(base); +} + /// A file opened for reading under a kept grant that new code withdraws gives no more of what it /// holds. #[test]