From fb8a9b9417ef51578f74d386884e0bffc3ade410 Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Sun, 1 Nov 2026 15:30:57 -0300 Subject: [PATCH 1/3] Send to Slicer: network folder targets for commands (#2304) A network folder is a mounted share (SMB, NFS) that a slicer on another computer reads. file.slicers.add_remote, file.slicers.remove_remote and file.slicers.test manage them; the session keeps the list, never the design. file.slicers lists them first with remote: true, and file.send_to_slicer and file.save_mesh {slicer} copy the mesh there under a readable name, adding a number instead of replacing a file. The copy goes through a hidden .part file, is bounded in time and size, and every failure comes back as an error. file.send_to_slicer also takes ascii and quality. --- assets/icons/ui/design/requested_icons.txt | 1 + .../ui/design/svg/model/network_folder.svg | 8 + .../pending/slicer-network-folder.json | 47 ++ attribution/pending/slicer-network-folder.md | 1 + crates/engine/src/cmd/file.rs | 28 +- crates/engine/src/cmd/file_easyprint.rs | 12 +- crates/engine/src/cmd/file_remote.rs | 105 +++ crates/engine/src/cmd/file_send.rs | 78 +- crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/lib.rs | 8 + crates/engine/src/remote_slicers.rs | 685 ++++++++++++++++++ crates/engine/src/schema/file_remote.rs | 100 +++ crates/engine/src/schema/mod.rs | 1 + crates/engine/src/schema/save_mesh.rs | 32 +- crates/engine/src/schema/save_mesh_tests.rs | 25 + crates/engine/src/schema/slicers.rs | 35 +- crates/engine/src/schema/slicers_tests.rs | 24 + crates/engine/src/slicer_files.rs | 6 +- crates/engine/src/tests/mesh_convert.rs | 231 ++++++ crates/ui-egui/src/dialogs_save_mesh.rs | 2 +- tests/kernel-cases/EXEMPT | 3 + 21 files changed, 1397 insertions(+), 37 deletions(-) create mode 100644 assets/icons/ui/design/svg/model/network_folder.svg create mode 100644 assets/locales/pending/slicer-network-folder.json create mode 100644 attribution/pending/slicer-network-folder.md create mode 100644 crates/engine/src/cmd/file_remote.rs create mode 100644 crates/engine/src/remote_slicers.rs create mode 100644 crates/engine/src/schema/file_remote.rs diff --git a/assets/icons/ui/design/requested_icons.txt b/assets/icons/ui/design/requested_icons.txt index 07bc4681f40..6ff548b8966 100644 --- a/assets/icons/ui/design/requested_icons.txt +++ b/assets/icons/ui/design/requested_icons.txt @@ -164,6 +164,7 @@ mirror false motion_link false move false nav_settings false +network_folder false new false normal false offset false diff --git a/assets/icons/ui/design/svg/model/network_folder.svg b/assets/icons/ui/design/svg/model/network_folder.svg new file mode 100644 index 00000000000..17a7d856256 --- /dev/null +++ b/assets/icons/ui/design/svg/model/network_folder.svg @@ -0,0 +1,8 @@ + + Network folder + + + + + + diff --git a/assets/locales/pending/slicer-network-folder.json b/assets/locales/pending/slicer-network-folder.json new file mode 100644 index 00000000000..60763368e7b --- /dev/null +++ b/assets/locales/pending/slicer-network-folder.json @@ -0,0 +1,47 @@ +{ + "en": { + "cmd.file_slicers_add_remote": "Add Network Folder", + "cmd.file_slicers_remove_remote": "Remove Network Folder", + "cmd.file_slicers_test": "Test Network Folder" + }, + "de": { + "cmd.file_slicers_add_remote": "Netzwerkordner hinzufügen", + "cmd.file_slicers_remove_remote": "Netzwerkordner entfernen", + "cmd.file_slicers_test": "Netzwerkordner testen" + }, + "ar": { + "cmd.file_slicers_add_remote": "إضافة مجلد شبكة", + "cmd.file_slicers_remove_remote": "إزالة مجلد شبكة", + "cmd.file_slicers_test": "اختبار مجلد شبكة" + }, + "he": { + "cmd.file_slicers_add_remote": "הוספת תיקיית רשת", + "cmd.file_slicers_remove_remote": "הסרת תיקיית רשת", + "cmd.file_slicers_test": "בדיקת תיקיית רשת" + }, + "ja": { + "cmd.file_slicers_add_remote": "ネットワークフォルダーを追加", + "cmd.file_slicers_remove_remote": "ネットワークフォルダーを削除", + "cmd.file_slicers_test": "ネットワークフォルダーをテスト" + }, + "ko": { + "cmd.file_slicers_add_remote": "네트워크 폴더 추가", + "cmd.file_slicers_remove_remote": "네트워크 폴더 제거", + "cmd.file_slicers_test": "네트워크 폴더 테스트" + }, + "pt-BR": { + "cmd.file_slicers_add_remote": "Adicionar pasta de rede", + "cmd.file_slicers_remove_remote": "Remover pasta de rede", + "cmd.file_slicers_test": "Testar pasta de rede" + }, + "vi": { + "cmd.file_slicers_add_remote": "Thêm thư mục mạng", + "cmd.file_slicers_remove_remote": "Xóa thư mục mạng", + "cmd.file_slicers_test": "Kiểm tra thư mục mạng" + }, + "zh": { + "cmd.file_slicers_add_remote": "添加网络文件夹", + "cmd.file_slicers_remove_remote": "移除网络文件夹", + "cmd.file_slicers_test": "测试网络文件夹" + } +} diff --git a/attribution/pending/slicer-network-folder.md b/attribution/pending/slicer-network-folder.md new file mode 100644 index 00000000000..55d650ec82c --- /dev/null +++ b/attribution/pending/slicer-network-folder.md @@ -0,0 +1 @@ +| assets/icons/ui/design/svg/model/network_folder.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index feda485b644..07cd8c2eb26 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -32,7 +32,7 @@ use crate::schema::new_design::{NewDesignParams, NewDesignResult}; use crate::schema::save::{SaveAsParams, SaveParams, SaveResult}; #[cfg(not(target_arch = "wasm32"))] use crate::schema::save_mesh::{SaveMeshResult, SlicerDelivery}; -use crate::schema::slicers::{SlicerInfo, SlicersParams, SlicersResult}; +use crate::schema::slicers::{SlicerEntry, SlicerInfo, SlicersParams, SlicersResult}; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -138,13 +138,13 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .contract(&SAVE_MESH_CONTRACT) .output(crate::schema::output_schema_for::) - .params("path; format?: stl|3mf|3mf-tagged (default from the extension, else stl; 3mf-tagged: docs/formats/3mf-face-tags.md); bodies?: [names] (default: all); ascii?: bool (STL); slicer?: id or name from file.slicers, the program path it lists, or a program the user added under Custom… (send the saved file there, through the same steps as file.send_to_slicer: a slicer that has to be started first is waited for; may be deprecated later in favour of file.send_to_slicer or a Send to App workflow, kept for scripts); single_instance?: bool (default true; see file.send_to_slicer); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"), + .params("path; format?: stl|3mf|3mf-tagged (default from the extension, else stl; 3mf-tagged: docs/formats/3mf-face-tags.md); bodies?: [names] (default: all); ascii?: bool (STL); slicer?: id or name from file.slicers, the program path it lists, a program the user added under Custom…, or a network folder the user added (a copy of the file goes there, under the file's name, numbered rather than replacing one) (send the saved file there, through the same steps as file.send_to_slicer: a slicer that has to be started first is waited for; may be deprecated later in favour of file.send_to_slicer or a Send to App workflow, kept for scripts); single_instance?: bool (default true; see file.send_to_slicer); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"), CommandSpec::new("file.send_to_slicer", "Send to Slicer", send_to_slicer) .enabled(starts_programs) .at("INSERT", "FILES") .icon("mesh_export") .noundo() - .params("slicer: id or name from file.slicers, or a program the user added under Custom…; bodies?: [names] (default: the selected bodies); wait?: block|return|no (default block: a slicer that drops a file at a cold start is started alone and the call waits up to 10 s for it to be ready, then sends; return: start it and answer {starting}; no: send now); single_instance?: bool (default true: PrusaSlicer, SuperSlicer and Cura load the file in the window that is open); format?: 3mf|stl|3mf-tagged (default 3mf, in millimetres; STL if that can't be written) → saves the bodies in this user's slicer folder and opens the file in the slicer. The file name stays the same for the same design and bodies, so sending again replaces it (use the slicer's Reload from disk)"), + .params("slicer: id or name from file.slicers: a slicer found on this machine, a program the user added under Custom…, or a network folder the user added (remote:, or its name); bodies?: [names] (default: the selected bodies); wait?: block|return|no (default block: a slicer that drops a file at a cold start is started alone and the call waits up to 10 s for it to be ready, then sends; return: start it and answer {starting}; no: send now); single_instance?: bool (default true: PrusaSlicer, SuperSlicer and Cura load the file in the window that is open); format?: 3mf|stl|3mf-tagged (default 3mf, in millimetres; STL if that can't be written); ascii?: bool (STL; default binary); quality?: standard|fine|finest (how closely the mesh follows curved faces, as file.save_mesh; default standard) → saves the bodies in this user's slicer folder and opens the file in the slicer. The file name stays the same for the same design and bodies, so sending again replaces it (use the slicer's Reload from disk). A network folder starts no program: the file is copied there under the design's name (and the body's, for one body), with (2), (3)… added rather than replacing a file → remote: true, target (its name), sent_to, renamed, or slicer_error; with wait: return the copy goes on in the background and the answer has sending (a ticket) instead"), CommandSpec::new("file.open_in_easyprint", "Open with EasyPrint", easyprint::open_in_easyprint) .icon("mesh_export") .noundo() @@ -154,7 +154,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .contract(&SLICERS_CONTRACT) .output(output_schema_for::) - .params("→ the slicers found on this machine: [{id, name, program, icon?}]; pass an id, a name or the program path as file.send_to_slicer's or file.save_mesh's `slicer`"), + .params("→ the network folders the user added, then the slicers found on this machine: [{id, name, program, icon?}] for a slicer, [{id: remote:, name, remote: true, kind: folder, folder}] for a network folder (file.slicers.add_remote); pass an id, a name or the program path as file.send_to_slicer's or file.save_mesh's `slicer`"), ]; fn new_doc(s: &mut Session, p: &Value) -> Result { @@ -1400,8 +1400,9 @@ fn starts_programs(_: &Session) -> std::result::Result<(), String> { if cfg!(target_arch = "wasm32") { Err("a slicer can't be started from the browser".into()) } else { Ok(()) } } -/// Save the bodies to this user's slicer folder and start the slicer with the file. The file -/// name stays the same for the same design and bodies, so sending again replaces it. +/// Save the bodies to this user's slicer folder and start the slicer with the file, or copy it to a +/// network folder. The file name stays the same for the same design and bodies, so sending again +/// replaces it. fn send_to_slicer(s: &mut Session, p: &Value) -> Result { let cmd = "file.send_to_slicer"; #[cfg(target_arch = "wasm32")] @@ -1413,10 +1414,12 @@ fn send_to_slicer(s: &mut Session, p: &Value) -> Result { { let format = match str_(p, "format").map(str::to_ascii_lowercase).as_deref() { None | Some("3mf") => Format::ThreeMf, + Some("stl") if bool_(p, "ascii").unwrap_or(false) => Format::StlAscii, Some("stl") => Format::StlBinary, Some("3mf-tagged") => Format::ThreeMfTagged, Some(other) => return Err(bad(cmd, format!("unknown mesh format `{other}` (stl, 3mf, 3mf-tagged)"))), }; + let quality = mesh_quality(p, cmd)?; let spec = str_(p, "slicer").ok_or_else(|| bad(cmd, "give `slicer` (see file.slicers)"))?; let wait = send::Wait::parse(str_(p, "wait")).ok_or_else(|| bad(cmd, "`wait` is block, return or no"))?; send::send( @@ -1428,7 +1431,7 @@ fn send_to_slicer(s: &mut Session, p: &Value) -> Result { bodies: string_list(cmd, p, "bodies")?, parts: Vec::new(), format, - quality: Default::default(), + quality, dest: send::Dest::Folder, single_instance: bool_(p, "single_instance").unwrap_or(true), wait, @@ -1437,16 +1440,17 @@ fn send_to_slicer(s: &mut Session, p: &Value) -> Result { } } -fn slicers(_: &mut Session, _: &Value) -> Result { - let slicers = crate::slicers::detect() - .iter() - .map(|d| SlicerInfo { +fn slicers(s: &mut Session, _: &Value) -> Result { + // The network folders first, as the Send to Slicer list shows them. + let mut slicers: Vec = s.network_folders.iter().map(|t| SlicerEntry::Folder(t.listing())).collect(); + slicers.extend(crate::slicers::detect().iter().map(|d| { + SlicerEntry::Slicer(SlicerInfo { id: d.id.clone(), name: d.name.clone(), program: d.command.first().cloned(), icon: d.icon.as_ref().map(|i| i.path().to_string_lossy().into_owned()), }) - .collect(); + })); serde_json::to_value(SlicersResult { slicers, param_warnings: Vec::new() }).map_err(|e| bad("file.slicers", e.to_string())) } diff --git a/crates/engine/src/cmd/file_easyprint.rs b/crates/engine/src/cmd/file_easyprint.rs index ec9bcc959df..37009bc9bad 100644 --- a/crates/engine/src/cmd/file_easyprint.rs +++ b/crates/engine/src/cmd/file_easyprint.rs @@ -25,9 +25,9 @@ pub(super) struct Exported { pub laid: super::print_face::Laid, } -/// Export the bodies (the selected ones when none are named), each laid on its print face. A -/// 3MF that can't be written is written as an STL, and `fell_back` says so. -pub(super) fn export_bodies(s: &Session, cmd: &str, named: &[String], format: Format) -> Result { +/// Export the bodies (the selected ones when none are named), each laid on its print face and +/// meshed at `quality`. A 3MF that can't be written is written as an STL, and `fell_back` says so. +pub(super) fn export_bodies(s: &Session, cmd: &str, named: &[String], format: Format, quality: solidcraft_io::MeshQuality) -> Result { let mut bodies = named.to_vec(); if bodies.is_empty() { bodies = s.selection.iter().filter_map(|x| if let crate::Sel::Body { name } = x { Some(name.clone()) } else { None }).collect(); @@ -37,10 +37,10 @@ pub(super) fn export_bodies(s: &Session, cmd: &str, named: &[String], format: Fo } let mut doc = s.doc.painted(&*s.world_state()?); let laid = super::print_face::lay_on_print_faces(s, &mut doc, &bodies, &[]); - let write = |format| solidcraft_io::export_with_metadata(&doc, &bodies, format, &s.doc.name, &s.doc.metadata); + let write = |format| solidcraft_io::export_with_quality(&doc, &bodies, format, &s.doc.name, &s.doc.metadata, quality); let mut fell_back = false; let (bytes, ext) = match (format, write(format)) { - (_, Ok(b)) => (b, if format == Format::StlBinary { "stl" } else { "3mf" }), + (_, Ok(b)) => (b, if matches!(format, Format::StlBinary | Format::StlAscii) { "stl" } else { "3mf" }), (Format::ThreeMf, Err(_)) => { fell_back = true; (write(Format::StlBinary)?, "stl") @@ -61,7 +61,7 @@ pub(super) fn open_in_easyprint(s: &mut Session, p: &Value) -> Result { if !bool_(p, "consent").unwrap_or(false) { return Err(bad(cmd, "this uploads the model to Printables' servers: ask the user, then pass `consent: true`")); } - let Exported { bytes, ext, fell_back, laid, .. } = export_bodies(s, cmd, &string_list(cmd, p, "bodies")?, format)?; + let Exported { bytes, ext, fell_back, laid, .. } = export_bodies(s, cmd, &string_list(cmd, p, "bodies")?, format, Default::default())?; if bytes.len() > MAX_BYTES { let mb = bytes.len().div_ceil(1_000_000); return Err(bad(cmd, format!("the model is {mb} MB and EasyPrint takes {} MB at most: send fewer bodies", MAX_BYTES / 1_000_000))); diff --git a/crates/engine/src/cmd/file_remote.rs b/crates/engine/src/cmd/file_remote.rs new file mode 100644 index 00000000000..6c9f373c8c7 --- /dev/null +++ b/crates/engine/src/cmd/file_remote.rs @@ -0,0 +1,105 @@ +//! Network folders for Send to Slicer (#2304): add, remove and test the folders a mesh can be +//! sent to (`crate::remote_slicers`). They are the session's (`Session::network_folders`); the +//! desktop app stores them in the user's preferences when these commands succeed and puts them back +//! at the next start. Run without an app (CLI, scripts), a folder lasts as long as the session. + +use serde_json::{Value, json}; + +use super::CommandSpec; +use crate::params::{bad, str_}; +use crate::remote_slicers::{self, RemoteTarget}; +use crate::schema::file_remote::{AddRemoteParams, RemoteFolderReply, RemoveRemoteParams, RemoveRemoteReply, TestRemoteParams, TestRemoteReply}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{Result, Session}; + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("file.slicers.add_remote", "Add Network Folder", crate::checked!("file.slicers.add_remote", add_remote)) + .icon("network_folder") + .noundo() + .doc_only() + .enabled(reaches_folders) + .contract(&ADD_CONTRACT) + .output(output_schema_for::) + .params("name: 1..64 characters (shown in the Send to Slicer list); folder: the folder's whole path, such as a mounted SMB or NFS share that a slicer on another computer reads → {id: remote:, name, kind: folder, folder, replaced}: adds a network folder to Send to Slicer, replacing one of the same name. Nothing is written until a mesh is sent; file.slicers.test checks the folder. The app keeps it in the user's preferences; without an app it lasts as long as the session"), + CommandSpec::new("file.slicers.remove_remote", "Remove Network Folder", crate::checked!("file.slicers.remove_remote", remove_remote)) + .icon("delete") + .noundo() + .doc_only() + .enabled(reaches_folders) + .contract(&REMOVE_CONTRACT) + .output(output_schema_for::) + .params("name: a network folder's name or id (file.slicers) → {name, removed: true}; the files sent there stay"), + CommandSpec::new("file.slicers.test", "Test Network Folder", crate::checked!("file.slicers.test", test)) + .icon("inspect") + .noundo() + .doc_only() + .enabled(reaches_folders) + .contract(&TEST_CONTRACT) + .output(output_schema_for::) + .params("name?: a network folder's name or id, or folder?: a folder's whole path (one of the two) → {ok, folder, name?, error?}: writes a small file in the folder and deletes it again, giving up after 30 s; error says what went wrong (not there, no permission, full, no answer)"), +]; + +const ADD_CONTRACT: TypedContract = TypedContract::new(); +const REMOVE_CONTRACT: TypedContract = TypedContract::new(); +const TEST_CONTRACT: TypedContract = TypedContract::new(); + +/// The browser build has no folders to write to. +fn reaches_folders(_: &Session) -> std::result::Result<(), String> { + if cfg!(target_arch = "wasm32") { Err("network folders can't be reached from the browser".into()) } else { Ok(()) } +} + +/// A folder an agent's commands may use: one in the folders it was allowed (`--allow-path`). The +/// app's own calls have no such limit. +fn allowed(cmd: &str, folder: &str) -> Result<()> { + solidcraft_io::vfs::check(folder).map_err(|e| bad(cmd, e.to_string())) +} + +fn add_remote(s: &mut Session, p: &Value) -> Result { + let cmd = "file.slicers.add_remote"; + reaches_folders(s).map_err(|e| bad(cmd, e))?; + let name = remote_slicers::check_name(str_(p, "name").unwrap_or_default()).map_err(|e| bad(cmd, e))?; + let folder = remote_slicers::check_folder(str_(p, "folder").unwrap_or_default()).map_err(|e| bad(cmd, e))?; + allowed(cmd, folder)?; + let target = RemoteTarget::folder_target(name, folder); + let replaced = remote_slicers::add(&mut s.network_folders, target.clone()).map_err(|e| bad(cmd, e))?; + Ok(json!({"id": target.id(), "name": target.name, "kind": target.kind(), "folder": target.folder(), "replaced": replaced})) +} + +fn remove_remote(s: &mut Session, p: &Value) -> Result { + let cmd = "file.slicers.remove_remote"; + reaches_folders(s).map_err(|e| bad(cmd, e))?; + let spec = str_(p, "name").filter(|n| !n.trim().is_empty()).ok_or_else(|| bad(cmd, "give `name` (see file.slicers)"))?; + let gone = + remote_slicers::remove(&mut s.network_folders, spec).ok_or_else(|| bad(cmd, format!("no network folder `{spec}` (see file.slicers)")))?; + Ok(json!({"name": gone.name, "removed": true})) +} + +fn test(s: &mut Session, p: &Value) -> Result { + let cmd = "file.slicers.test"; + reaches_folders(s).map_err(|e| bad(cmd, e))?; + let (name, folder) = match (str_(p, "name"), str_(p, "folder")) { + (Some(spec), None) => { + let target = remote_slicers::resolve(&s.network_folders, spec) + .ok_or_else(|| bad(cmd, format!("no network folder `{spec}` (see file.slicers)")))?; + if let Some(folder) = target.on_this_computer() { + allowed(cmd, folder)?; + } + (Some(target.name.clone()), target.folder().to_string()) + } + (None, Some(folder)) => { + let folder = remote_slicers::check_folder(folder).map_err(|e| bad(cmd, e))?; + allowed(cmd, folder)?; + (None, folder.to_string()) + } + _ => return Err(bad(cmd, "give `name` or `folder`, one of the two")), + }; + let mut out = json!({"ok": true, "folder": folder}); + if let Some(name) = name { + out["name"] = json!(name); + } + if let Err(e) = remote_slicers::probe(&folder) { + out["ok"] = json!(false); + out["error"] = json!(e); + } + Ok(out) +} diff --git a/crates/engine/src/cmd/file_send.rs b/crates/engine/src/cmd/file_send.rs index 01b2a4b69f3..1939c738a01 100644 --- a/crates/engine/src/cmd/file_send.rs +++ b/crates/engine/src/cmd/file_send.rs @@ -6,6 +6,10 @@ //! //! It takes a [`TargetKind`], and slicers are the only kind there is; a later Send to App would add //! one (see `slicers::TargetKind`) and send through this same function. +//! +//! A network folder the user added (`crate::remote_slicers`, #2304) is a target too: the file is +//! written as for any slicer, then copied into the folder under the design's (and body's) name, +//! numbered rather than replacing a file there, and no program is started. use serde_json::{Value, json}; use solidcraft_io::Format; @@ -13,6 +17,7 @@ use solidcraft_io::Format; use super::easyprint::{Exported, export_bodies}; use super::export_laid_to; use crate::params::bad; +use crate::remote_slicers::{self, RemoteTarget}; use crate::schema::save_mesh::SlicerDelivery; use crate::slicers::{self, Slicer, TargetKind}; use crate::{EngineError, Result, Session}; @@ -57,7 +62,7 @@ pub(super) struct Send<'a> { /// 3MF objects with parts (`objects: "component"`, #8139). Only for [`Dest::Path`]. pub parts: Vec<(String, Vec)>, pub format: Format, - /// Only for [`Dest::Path`]; the slicer folder's file is always standard. + /// How closely the mesh follows curved faces. pub quality: solidcraft_io::MeshQuality, pub dest: Dest<'a>, pub single_instance: bool, @@ -75,6 +80,13 @@ fn format_name(f: Format) -> &'static str { /// Send the bodies to the target named by `r.spec`. pub(super) fn send(s: &mut Session, r: Send<'_>) -> Result { // The target is found before anything is written, so a name that matches nothing writes nothing. + // A network folder's name comes first: the user gave it, so a script naming it means it. + if let Some(folder) = remote_slicers::resolve(&s.network_folders, r.spec).cloned() { + return send_to_folder(s, &r, &folder); + } + if remote_slicers::is_id(r.spec) { + return Err(bad(r.cmd, format!("no network folder `{}` (see file.slicers)", r.spec))); + } let target = slicers::resolve_for(r.kind, r.spec).ok_or_else(|| { bad(r.cmd, format!("no slicer `{}` (see file.slicers; a program works only once the user has added it under Custom…)", r.spec)) })?; @@ -83,23 +95,77 @@ pub(super) fn send(s: &mut Session, r: Send<'_>) -> Result { } let mut out = match r.dest { Dest::Path(path) => export_laid_to(s, path, r.format, &r.bodies, &r.parts, r.quality)?, - Dest::Folder => write_in_folder(s, &r)?, + Dest::Folder => write_in_folder(s, &r)?.0, }; let path = out.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); deliver(&target, &path, r.single_instance, r.wait, &mut out); Ok(out) } -/// Write the bodies into the slicer folder. -fn write_in_folder(s: &mut Session, r: &Send<'_>) -> Result { +/// Send the bodies to a network folder: write the file as for a slicer, then copy it into the +/// folder. The name there is the design's (and the body's, for one body) for the slicer folder, and +/// the file's own name for a path the caller gave. +fn send_to_folder(s: &mut Session, r: &Send<'_>, folder: &RemoteTarget) -> Result { + // An agent limited to folders (`--allow-path`) sends only into one it was allowed, checked + // here, before anything is written or a copy starts in the background. + if let Some(dir) = folder.on_this_computer() { + solidcraft_io::vfs::check(dir).map_err(|e| bad(r.cmd, e.to_string()))?; + } + let (mut out, stem) = match r.dest { + Dest::Path(path) => { + let out = export_laid_to(s, path, r.format, &r.bodies, &r.parts, r.quality)?; + let stem = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + (out, remote_slicers::safe_stem(&stem)) + } + Dest::Folder => write_in_folder(s, r)?, + }; + let path = out.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); + let ext = std::path::Path::new(&path) + .extension() + .map(|e| e.to_string_lossy().to_ascii_lowercase()) + .filter(|e| !e.is_empty()) + .unwrap_or_else(|| if matches!(r.format, Format::StlBinary | Format::StlAscii) { "stl".into() } else { "3mf".into() }); + deliver_to_folder(folder, &path, &stem, &ext, r.wait == Wait::Return, &mut out); + Ok(out) +} + +/// Copy the file at `path` into a network folder and say what happened in `out`: `slicer` (the +/// folder's name), `sent_to` and `renamed` when it went, `slicer_error` when it didn't; `remote` either way. +/// In the background, the answer is `sending`: the ticket to ask `remote_slicers::poll` about. +fn deliver_to_folder(folder: &RemoteTarget, path: &str, stem: &str, ext: &str, background: bool, out: &mut Value) { + let Some(obj) = out.as_object_mut() else { return }; + let at = SlicerDelivery { remote: true, target: Some(folder.name.clone()), ..Default::default() }; + let delivery = if background { + SlicerDelivery { sending: Some(remote_slicers::deliver_in_background(folder, std::path::Path::new(path), stem, ext)), ..at } + } else { + // The file is saved either way; a folder that can't be written is reported, not fatal. + match remote_slicers::deliver(folder, std::path::Path::new(path), stem, ext) { + Ok(sent) => SlicerDelivery { + slicer: Some(folder.name.clone()), + sent_to: Some(sent.path.to_string_lossy().into_owned()), + renamed: Some(sent.numbered), + ..at + }, + Err(e) => SlicerDelivery { slicer_error: Some(format!("couldn't send to {}: {e}; the file is saved at {path}", folder.name)), ..at }, + } + }; + // What happened, as the typed value the reply's schema describes. + if let Ok(Value::Object(keys)) = serde_json::to_value(delivery) { + obj.extend(keys); + } +} + +/// Write the bodies into the slicer folder; the reply, and the readable name for a network folder. +fn write_in_folder(s: &mut Session, r: &Send<'_>) -> Result<(Value, String)> { use crate::slicer_files; - let Exported { bytes, ext, fell_back, bodies, laid } = export_bodies(s, r.cmd, &r.bodies, r.format)?; + let Exported { bytes, ext, fell_back, bodies, laid } = export_bodies(s, r.cmd, &r.bodies, r.format, r.quality)?; + let readable = remote_slicers::readable_stem(&s.doc.name, &bodies); let dir = slicer_files::dir().ok_or_else(|| bad(r.cmd, "no per-user folder on this system"))?; let stem = slicer_files::stem(&s.doc.name, s.path.as_deref(), s.uid, &bodies); let (file, numbered) = slicer_files::write(&dir, &stem, ext, &bytes).map_err(|e| EngineError::Other(format!("{}: {e}", dir.display())))?; let mut out = json!({"path": file.to_string_lossy(), "bytes": bytes.len(), "format": ext, "numbered": numbered, "stl_fallback": fell_back}); laid.report(&mut out); - Ok(out) + Ok((out, readable)) } /// Hand the file at `path` to `target`, starting it first if it has to be, and say what happened in diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 6e6385c838b..a16bf1123cd 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -70,6 +70,7 @@ pub use component_link::resolve_design_links; mod config; mod design_link; mod file; +mod file_remote; mod frame; mod frame_end_cap; pub(crate) mod inspect; @@ -370,6 +371,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(parameters::COMMANDS.iter()); v.extend(parameter_sweep::COMMANDS.iter()); v.extend(file::COMMANDS.iter()); + v.extend(file_remote::COMMANDS.iter()); v.extend(print_face::COMMANDS.iter()); v.extend(metadata::COMMANDS.iter()); v.extend(inspect::COMMANDS.iter()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b073b42e509..dcd5d456a1b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,6 +26,7 @@ pub mod panels; pub mod params; pub mod product_scene; pub mod recovery; +pub mod remote_slicers; pub mod render_jobs; pub mod render_lights; pub mod render_preparation; @@ -530,6 +531,9 @@ pub struct Session { /// How the host uploads a model to EasyPrint (`file.open_in_easyprint`); `None`: it can't. It /// belongs to the session like `param_check`, so it survives opening and starting designs. pub easyprint_upload: Option, + /// Send to Slicer's network folders (#2304): the user's, which the app keeps in its preferences. + /// They belong to the session like `param_check`, so they survive opening and starting designs. + pub network_folders: Vec, /// After a live frame: its sketch, the document it left and the revision. Its links were /// brought up to date by that frame, so the gesture's next frame needn't project them again /// while nothing else has run (#3222). @@ -835,6 +839,7 @@ impl Session { project_construction: false, param_check: schema::ParamCheck::Off, easyprint_upload: None, + network_folders: Vec::new(), live_links: None, active_component: 0, active_occurrence_path: None, @@ -901,6 +906,7 @@ impl Session { let single_surface_analysis = self.single_surface_analysis; let param_check = self.param_check; let easyprint_upload = self.easyprint_upload.take(); + let network_folders = std::mem::take(&mut self.network_folders); let render_viewport = self.render_viewport.clone(); let render_jobs = self.render_jobs.scratch(); let checkpoints = std::mem::take(&mut self.checkpoints); @@ -921,6 +927,7 @@ impl Session { self.set_single_surface_analysis(single_surface_analysis); self.param_check = param_check; self.easyprint_upload = easyprint_upload; + self.network_folders = network_folders; self.render_viewport = render_viewport; self.render_jobs = render_jobs; self.checkpoints = checkpoints; @@ -1977,6 +1984,7 @@ impl Session { project_construction: self.project_construction, param_check: self.param_check, easyprint_upload: self.easyprint_upload.clone(), + network_folders: self.network_folders.clone(), live_links: None, active_component: self.active_component, active_occurrence_path: self.active_occurrence_path.clone(), diff --git a/crates/engine/src/remote_slicers.rs b/crates/engine/src/remote_slicers.rs new file mode 100644 index 00000000000..f2b71a089f0 --- /dev/null +++ b/crates/engine/src/remote_slicers.rs @@ -0,0 +1,685 @@ +//! Network folders for Send to Slicer (#2304): a folder the user picked once, usually a mounted +//! SMB or NFS share that a slicer on another computer reads (OrcaSlicer in a container on a home +//! server, say). Sending to one copies the mesh there under a name a person can read, never +//! replacing a file that is already there, and starts no program. +//! +//! The list belongs to the session (`Session::network_folders`), like the parameter checks: the +//! application keeps it in the user's preferences and puts it there, the +//! `file.slicers.add_remote` and `file.slicers.remove_remote` commands change it, and the +//! application stores the result. Run without an app (CLI, scripts), a folder lasts as long as +//! the session. Nothing here scans the network or talks to it: the operating system +//! does the share, and SolidCraft writes files. + +#[cfg(not(target_arch = "wasm32"))] +use std::io::{self, ErrorKind}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +/// Most network folders kept. +pub const MAX_TARGETS: usize = 32; +/// Most characters in a network folder's name. +pub const MAX_NAME: usize = 64; +/// Most bytes in a folder's path. +pub const MAX_FOLDER: usize = 4096; +/// Largest file copied to a network folder. +pub const MAX_BYTES: u64 = 1 << 30; +/// Longest a copy to a network folder may take before the command answers without it: a share +/// whose server has gone can keep a file call waiting for minutes. +pub const TIME_LIMIT: Duration = Duration::from_secs(30); +/// Most numbered names (`Part (2).3mf`, …) tried before giving up. +#[cfg(not(target_arch = "wasm32"))] +const MAX_NUMBERED: u32 = 999; +/// Most characters of a file name taken from the design and body names. +const MAX_STEM: usize = 80; +/// At most this many bytes of a readable name: with ` (999)` and an extension it stays within +/// the 255 bytes a file name may have, in any language. +const MAX_STEM_BYTES: usize = 200; +/// What a network folder's id starts with in `file.slicers`. +pub const ID_PREFIX: &str = "remote:"; + +/// A network folder a mesh can be sent to. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoteTarget { + /// The name the user gave it, shown in the slicer list. + pub name: String, + /// Where the file goes. + #[serde(flatten)] + pub dest: Dest, +} + +/// Where a network folder's files go. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum Dest { + /// A folder on this computer, usually a mounted share. + Folder { folder: String }, +} + +impl RemoteTarget { + /// A folder target. + pub fn folder_target(name: &str, folder: &str) -> RemoteTarget { + RemoteTarget { name: name.to_string(), dest: Dest::Folder { folder: folder.to_string() } } + } + + /// Its id in `file.slicers`: `remote:`. + pub fn id(&self) -> String { + format!("{ID_PREFIX}{}", self.name) + } + + /// The kind, as `file.slicers` names it. + pub fn kind(&self) -> &'static str { + match self.dest { + Dest::Folder { .. } => "folder", + } + } + + /// The folder the files go to. + pub fn folder(&self) -> &str { + match &self.dest { + Dest::Folder { folder } => folder, + } + } + + /// Its entry in `file.slicers`. + pub fn listing(&self) -> crate::schema::slicers::NetworkFolderInfo { + crate::schema::slicers::NetworkFolderInfo { + id: self.id(), + name: self.name.clone(), + remote: true, + kind: self.kind().to_string(), + folder: self.folder().to_string(), + } + } + + /// The folder on this computer the files go to: what an agent limited to folders + /// (`--allow-path`) must be allowed before sending there or testing it. + pub fn on_this_computer(&self) -> Option<&str> { + match &self.dest { + Dest::Folder { folder } => Some(folder), + } + } +} + +/// A network folder's name as given: trimmed, 1 to [`MAX_NAME`] characters, no control characters. +pub fn check_name(name: &str) -> Result<&str, String> { + let name = name.trim(); + if name.is_empty() { + Err("give the network folder a name".into()) + } else if name.chars().count() > MAX_NAME { + Err(format!("a network folder's name has {MAX_NAME} characters at most")) + } else if name.chars().any(char::is_control) { + Err("a network folder's name can't hold control characters".into()) + } else { + Ok(name) + } +} + +/// A folder's path as given: trimmed, whole (absolute), at most [`MAX_FOLDER`] bytes, no control +/// characters. Whether it is there is not looked at: a share may be mounted later. +pub fn check_folder(folder: &str) -> Result<&str, String> { + let folder = folder.trim(); + if folder.is_empty() { + Err("give the folder".into()) + } else if folder.len() > MAX_FOLDER { + Err(format!("a folder's path has {MAX_FOLDER} bytes at most")) + } else if folder.chars().any(char::is_control) { + Err("a folder's path can't hold control characters".into()) + } else if !Path::new(folder).is_absolute() { + Err(format!("{folder}: give the folder's whole path")) + } else { + Ok(folder) + } +} + +fn same_name(a: &str, b: &str) -> bool { + a.trim().to_lowercase() == b.trim().to_lowercase() +} + +/// The network folders of `list` the commands may use (the application's preferences, which a +/// person can edit): one that is not valid, or repeats a name, is left out, and so is any past +/// [`MAX_TARGETS`]. +pub fn sanitized(list: &[RemoteTarget]) -> Vec { + let mut kept: Vec = Vec::new(); + for t in list { + let (Ok(name), Ok(folder)) = (check_name(&t.name), check_folder(t.folder())) else { continue }; + if kept.len() < MAX_TARGETS && !kept.iter().any(|k| same_name(&k.name, name)) { + kept.push(RemoteTarget::folder_target(name, folder)); + } + } + kept +} + +/// Add a network folder to `list`, replacing the one of the same name (true when it did). +pub fn add(list: &mut Vec, target: RemoteTarget) -> Result { + if let Some(old) = list.iter_mut().find(|t| same_name(&t.name, &target.name)) { + *old = target; + return Ok(true); + } + if list.len() >= MAX_TARGETS { + return Err(format!("there are {MAX_TARGETS} network folders already: remove one first")); + } + list.push(target); + Ok(false) +} + +/// Remove the network folder `spec` names (its name or id) from `list`; the one removed. +pub fn remove(list: &mut Vec, spec: &str) -> Option { + let name = spec.trim().strip_prefix(ID_PREFIX).unwrap_or(spec); + let at = list.iter().position(|t| same_name(&t.name, name))?; + Some(list.remove(at)) +} + +/// The network folder of `list` that `spec` names: its id (`remote:`) or its name, in any case. +pub fn resolve<'a>(list: &'a [RemoteTarget], spec: &str) -> Option<&'a RemoteTarget> { + let name = spec.trim().strip_prefix(ID_PREFIX).unwrap_or(spec); + list.iter().find(|t| same_name(&t.name, name)) +} + +/// Whether `spec` is written as a network folder's id, so it names nothing else. +pub fn is_id(spec: &str) -> bool { + spec.trim().starts_with(ID_PREFIX) +} + +/// A file name (no extension) a person can read for `bodies` of a design: the design's name, and +/// the body's after it when one body other than the design's namesake is sent. +pub fn readable_stem(design: &str, bodies: &[String]) -> String { + let design = design.trim(); + let name = match bodies { + [one] if !one.trim().is_empty() && one.trim() != design => { + if design.is_empty() { + one.trim().to_string() + } else { + format!("{design} - {}", one.trim()) + } + } + _ => design.to_string(), + }; + safe_stem(&name) +} + +/// `name` as a file name every system takes: the characters Windows and SMB refuse and control +/// characters become `_`, leading and trailing dots and spaces go (no hidden files), at most +/// [`MAX_STEM`] characters, `design` when nothing is left, and an `_` after a Windows device name. +pub fn safe_stem(name: &str) -> String { + let mut bytes = 0; + let cleaned: String = name + .chars() + .take(MAX_STEM) + .map(|c| if c.is_control() || "<>:\"/\\|?*".contains(c) { '_' } else { c }) + .take_while(|c| { + bytes += c.len_utf8(); + bytes <= MAX_STEM_BYTES + }) + .collect(); + let stem = cleaned.trim_matches(|c: char| c == '.' || c.is_whitespace()); + let stem = if stem.is_empty() { "design" } else { stem }; + let device = stem.split('.').next().unwrap_or_default().trim().to_ascii_uppercase(); + let numbered_device = (device.starts_with("COM") || device.starts_with("LPT")) + && device.len() == 4 + && device.as_bytes().get(3).is_some_and(|b| (b'1'..=b'9').contains(b)); + if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered_device { format!("{stem}_") } else { stem.to_string() } +} + +/// `.` for the first name, then ` (2).` and so on. +#[cfg(not(target_arch = "wasm32"))] +fn numbered(stem: &str, ext: &str, n: u32) -> String { + if n <= 1 { format!("{stem}.{ext}") } else { format!("{stem} ({n}).{ext}") } +} + +/// Where a file went. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Delivered { + pub path: PathBuf, + /// A file of the first name was there, so a number was added. + pub numbered: bool, +} + +/// Copy the file at `src` into the network folder as `.` (numbered when that name is +/// taken), within [`copy_limit`] and [`MAX_BYTES`]. The error says what went wrong in words. +pub fn deliver(target: &RemoteTarget, src: &Path, stem: &str, ext: &str) -> Result { + let size = std::fs::metadata(src).map(|m| m.len()).unwrap_or_default(); + deliver_within(Path::new(target.folder()), src, stem, ext, max_bytes(), copy_limit(size)) +} + +/// The slowest a share may copy, in bytes a second, before it is given up on. +pub const MIN_RATE: u64 = 64 * 1024; + +/// How long copying `size` bytes may take: [`TIME_LIMIT`] for a share that doesn't answer, and +/// more for a large file, at [`MIN_RATE`]. A large mesh on a slow share was reported as failed +/// while it still arrived, and sending it again left a second copy. +pub fn copy_limit(size: u64) -> Duration { + TIME_LIMIT.saturating_add(Duration::from_secs(size / MIN_RATE)) +} + +/// The size cap of [`deliver`]; tests of the commands make it small. +fn max_bytes() -> u64 { + #[cfg(test)] + if let Some(made_up) = *TEST_MAX_BYTES.lock().unwrap_or_else(std::sync::PoisonError::into_inner) { + return made_up; + } + MAX_BYTES +} + +/// Tests of the commands set the size cap to one they made up. +#[cfg(test)] +pub(crate) static TEST_MAX_BYTES: std::sync::Mutex> = std::sync::Mutex::new(None); +/// The size cap is process-wide: tests that change it, or send to a network folder, take turns. +#[cfg(test)] +pub(crate) static TEST_TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// [`deliver`] into `folder` with a size cap and a time limit of its own. +pub fn deliver_within(folder: &Path, src: &Path, stem: &str, ext: &str, max: u64, limit: Duration) -> Result { + #[cfg(target_arch = "wasm32")] + { + let _ = (folder, src, stem, ext, max, limit); + Err("network folders can't be reached from the browser".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let (folder, src, stem, ext) = (folder.to_path_buf(), src.to_path_buf(), stem.to_string(), ext.to_string()); + let shown = folder.display().to_string(); + within(limit, &shown, move || copy_into(&folder, &src, &stem, &ext, max)) + } +} + +/// Copies going on in the background, by ticket (`file.send_to_slicer` with `wait: "return"`, which +/// the window uses so a share that does not answer never holds it up). +#[cfg(not(target_arch = "wasm32"))] +type Copying = std::sync::mpsc::Receiver>; +#[cfg(not(target_arch = "wasm32"))] +static SENDING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// Most copies kept going at once; past it, the oldest one's answer is dropped. +#[cfg(not(target_arch = "wasm32"))] +const MAX_SENDING: usize = 16; + +/// [`deliver`] on a thread of its own; the ticket to ask [`poll`] about it. +pub fn deliver_in_background(target: &RemoteTarget, src: &Path, stem: &str, ext: &str) -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let ticket = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + #[cfg(target_arch = "wasm32")] + let _ = (target, src, stem, ext); + #[cfg(not(target_arch = "wasm32"))] + { + let (tx, rx) = std::sync::mpsc::channel(); + let (target, src, stem, ext) = (target.clone(), src.to_path_buf(), stem.to_string(), ext.to_string()); + let started = std::thread::Builder::new().name("network-folder-send".into()).spawn(move || { + let _ = tx.send(deliver(&target, &src, &stem, &ext)); + }); + let mut sending = SENDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + match started { + Ok(_) => { + if sending.len() >= MAX_SENDING { + sending.remove(0); + } + sending.push((ticket, rx)); + } + // No thread: the answer is that it could not start (the receiver is dropped with its sender). + Err(e) => { + let (tx, rx) = std::sync::mpsc::channel(); + let _ = tx.send(Err(format!("couldn't start the copy ({e})"))); + sending.push((ticket, rx)); + } + } + } + ticket +} + +/// How the copy of `ticket` went: `None` while it goes on, then its answer, once. +pub fn poll(ticket: u64) -> Option> { + #[cfg(target_arch = "wasm32")] + { + let _ = ticket; + Some(Err("network folders can't be reached from the browser".into())) + } + #[cfg(not(target_arch = "wasm32"))] + { + use std::sync::mpsc::TryRecvError; + let mut sending = SENDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(at) = sending.iter().position(|(t, _)| *t == ticket) else { + return Some(Err("the copy is no longer followed".into())); + }; + let answer = match sending.get(at).map(|(_, rx)| rx.try_recv()) { + Some(Err(TryRecvError::Empty)) => return None, + Some(Ok(answer)) => answer, + Some(Err(TryRecvError::Disconnected)) | None => Err("the copy stopped unexpectedly".into()), + }; + sending.remove(at); + Some(answer) + } +} + +/// Write a small file in `folder` and delete it again, within [`TIME_LIMIT`]: whether a mesh can be +/// sent there. The error says what went wrong in words. +pub fn probe(folder: &str) -> Result<(), String> { + probe_within(Path::new(folder), TIME_LIMIT) +} + +/// [`probe`] with a time limit of its own. +pub fn probe_within(folder: &Path, limit: Duration) -> Result<(), String> { + #[cfg(target_arch = "wasm32")] + { + let _ = (folder, limit); + Err("network folders can't be reached from the browser".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let folder = folder.to_path_buf(); + let shown = folder.display().to_string(); + within(limit, &shown, move || probe_now(&folder)) + } +} + +/// Run `work` on a thread of its own and wait at most `limit` for it. A file call on a share whose +/// server has gone can block for minutes; the thread is left to finish on its own then. +#[cfg(not(target_arch = "wasm32"))] +fn within(limit: Duration, folder: &str, work: impl FnOnce() -> Result + Send + 'static) -> Result { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .name("network-folder".into()) + .spawn(move || { + let _ = tx.send(work()); + }) + .map_err(|e| format!("couldn't start writing to {folder} ({e})"))?; + match rx.recv_timeout(limit) { + Ok(result) => result, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + Err(format!("{folder} did not answer within {} s (is its server on?); the file may still arrive", limit.as_secs())) + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(format!("writing to {folder} stopped unexpectedly")), + } +} + +/// What went wrong with `folder`, in words. +#[cfg(not(target_arch = "wasm32"))] +fn explain(folder: &str, e: &io::Error) -> String { + match e.kind() { + ErrorKind::NotFound => format!("{folder} is not there (is the share mounted?)"), + ErrorKind::PermissionDenied => format!("{folder}: no permission to write there"), + ErrorKind::StorageFull => format!("{folder} is full"), + ErrorKind::ReadOnlyFilesystem => format!("{folder} is read-only"), + ErrorKind::NotADirectory => format!("{folder} is not a folder"), + _ => format!("{folder}: {e}"), + } +} + +/// A folder that is there and is a folder. A folder is never made: at an unmounted share's mount +/// point that would put the files on this computer instead. +#[cfg(not(target_arch = "wasm32"))] +fn existing_folder(folder: &Path) -> Result { + let shown = folder.display().to_string(); + match std::fs::metadata(folder) { + Ok(m) if m.is_dir() => Ok(shown), + Ok(_) => Err(format!("{shown} is not a folder")), + Err(e) => Err(explain(&shown, &e)), + } +} + +/// A suffix for temporary names that no other send, in this process or another, uses at once. +#[cfg(not(target_arch = "wasm32"))] +fn unique() -> String { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or_default(); + format!("{}-{n}-{nanos}", std::process::id()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn copy_into(folder: &Path, src: &Path, stem: &str, ext: &str, max: u64) -> Result { + let shown = existing_folder(folder)?; + let size = std::fs::metadata(src).map_err(|e| format!("{}: {e}", src.display()))?.len(); + if size > max { + let mb = |b: u64| b.div_ceil(1_000_000); + return Err(format!("the file is {} MB, more than the {} MB a network folder takes", mb(size), mb(max))); + } + // Copied under a hidden temporary name first, so a slicer watching the folder never reads half a file. + // A fixed short name, so a long readable one can't make it too long for the share. + let tmp = folder.join(format!(".solidcraft-{}.{ext}.part", unique())); + if let Err(e) = std::fs::copy(src, &tmp) { + let _ = std::fs::remove_file(&tmp); + return Err(explain(&shown, &e)); + } + let placed = place(&tmp, folder, stem, ext); + if placed.is_err() { + let _ = std::fs::remove_file(&tmp); + } + placed.map_err(|e| explain(&shown, &e)) +} + +/// Give the temporary file `tmp` the first free name, never replacing a file. A hard link takes a +/// name only when it is free, in one step; a share without hard links gets the name reserved with +/// an empty file first, which the temporary file then replaces. +#[cfg(not(target_arch = "wasm32"))] +fn place(tmp: &Path, folder: &Path, stem: &str, ext: &str) -> io::Result { + let mut link = true; + for n in 1..=MAX_NUMBERED { + let path = folder.join(numbered(stem, ext, n)); + if link { + match std::fs::hard_link(tmp, &path) { + Ok(()) => { + let _ = std::fs::remove_file(tmp); + return Ok(Delivered { path, numbered: n > 1 }); + } + Err(e) if e.kind() == ErrorKind::AlreadyExists => continue, + Err(_) => link = false, + } + } + match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) { + Ok(_) => { + if let Err(e) = std::fs::rename(tmp, &path) { + let _ = std::fs::remove_file(&path); + return Err(e); + } + return Ok(Delivered { path, numbered: n > 1 }); + } + Err(e) if e.kind() == ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + Err(io::Error::new(ErrorKind::AlreadyExists, format!("{MAX_NUMBERED} files named {stem} are there already"))) +} + +#[cfg(not(target_arch = "wasm32"))] +fn probe_now(folder: &Path) -> Result<(), String> { + use std::io::Write; + let shown = existing_folder(folder)?; + let file = folder.join(format!(".solidcraft-test-{}.tmp", unique())); + let data = b"SolidCraft checks that it can write here; this file is deleted at once.\n"; + let written = + std::fs::OpenOptions::new().write(true).create_new(true).open(&file).and_then(|mut f| f.write_all(data).and_then(|()| f.sync_all())); + let read = written.and_then(|()| std::fs::metadata(&file)).map(|m| m.len()); + let _ = std::fs::remove_file(&file); + match read { + Ok(len) if len == data.len() as u64 => Ok(()), + Ok(len) => Err(format!("{shown}: wrote {} bytes and found {len}", data.len())), + Err(e) => Err(explain(&shown, &e)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("solidcraft-remote-slicers-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn names(dir: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + } + + #[test] + fn file_names_are_readable_and_safe_everywhere() { + let one = |b: &str| vec![b.to_string()]; + assert_eq!(readable_stem("Bracket", &one("Arm")), "Bracket - Arm"); + assert_eq!(readable_stem("Bracket", &one("Bracket")), "Bracket", "the body named after the design adds nothing"); + assert_eq!(readable_stem("Bracket", &[]), "Bracket"); + assert_eq!(readable_stem("Bracket", &["Arm".to_string(), "Base".to_string()]), "Bracket"); + assert_eq!(readable_stem("", &one("Arm")), "Arm"); + assert_eq!(safe_stem("a/b:c*d?\"eg|h\\i"), "a_b_c_d__e_f_g_h_i"); + assert_eq!(safe_stem(" ..hidden. "), "hidden", "no hidden files, no trailing dots Windows drops"); + assert_eq!(safe_stem("tab\there"), "tab_here"); + assert_eq!(safe_stem(""), "design"); + assert_eq!(safe_stem("..."), "design"); + assert_eq!(safe_stem("con"), "con_"); + assert_eq!(safe_stem("LPT1.part"), "LPT1.part_"); + assert_eq!(safe_stem("COM0"), "COM0", "COM0 is not a device"); + assert_eq!(safe_stem("Console"), "Console"); + assert_eq!(copy_limit(0), TIME_LIMIT, "a share that doesn't answer is given up on after 30 s"); + assert_eq!(copy_limit(MAX_BYTES), TIME_LIMIT + Duration::from_secs(MAX_BYTES / MIN_RATE), "1 GB may take its time"); + assert_eq!(safe_stem(&"x".repeat(200)).chars().count(), MAX_STEM); + // Letters of four bytes each: 50 of them fill the bytes a readable name may take. + let wide = safe_stem(&"\u{1d4d0}".repeat(80)); + assert_eq!((wide.chars().count(), wide.len()), (MAX_STEM_BYTES / 4, MAX_STEM_BYTES)); + assert!(numbered(&wide, "3mf", 999).len() <= 255); + assert_eq!(safe_stem("Peça"), "Peça", "letters of any language are kept"); + } + + #[test] + fn names_and_folders_are_checked() { + assert_eq!(check_name(" Orca on homelab "), Ok("Orca on homelab")); + assert!(check_name(" ").is_err()); + assert!(check_name(&"n".repeat(MAX_NAME + 1)).is_err()); + assert!(check_name("a\u{7}b").is_err()); + assert!(check_folder("relative/folder").is_err()); + assert!(check_folder("").is_err()); + assert!(check_folder(&format!("/{}", "a".repeat(MAX_FOLDER))).is_err()); + let abs = std::env::temp_dir(); + assert!(check_folder(&abs.to_string_lossy()).is_ok()); + } + + #[test] + fn the_list_adds_replaces_resolves_and_removes_by_name_or_id() { + let folder = std::env::temp_dir().to_string_lossy().into_owned(); + let mut list = sanitized(&[ + RemoteTarget::folder_target(" Orca ", &folder), + RemoteTarget::folder_target("orca", &folder), + RemoteTarget::folder_target("", &folder), + RemoteTarget::folder_target("Relative", "not/whole"), + ]); + assert_eq!(list, [RemoteTarget::folder_target("Orca", &folder)], "trimmed; a repeated name and invalid entries are left out"); + assert_eq!(resolve(&list, "ORCA").map(|t| t.name.as_str()), Some("Orca")); + assert_eq!(resolve(&list, "remote:Orca").map(RemoteTarget::id), Some("remote:Orca".into())); + assert!(resolve(&list, "Cura").is_none()); + assert_eq!(add(&mut list, RemoteTarget::folder_target("Cura", &folder)), Ok(false)); + assert_eq!(add(&mut list, RemoteTarget::folder_target("CURA", "/elsewhere")), Ok(true)); + assert_eq!(resolve(&list, "cura").map(RemoteTarget::folder), Some("/elsewhere")); + assert_eq!(remove(&mut list, "remote:cura").map(|t| t.name), Some("CURA".into())); + assert!(remove(&mut list, "cura").is_none()); + let mut full = sanitized(&(0..MAX_TARGETS + 5).map(|i| RemoteTarget::folder_target(&format!("T{i}"), &folder)).collect::>()); + assert_eq!(full.len(), MAX_TARGETS); + assert!(add(&mut full, RemoteTarget::folder_target("One more", &folder)).is_err()); + } + + #[test] + fn a_target_round_trips_through_the_preferences_json() { + let t = RemoteTarget::folder_target("Orca", "/mnt/orca"); + let v = serde_json::to_value(&t).unwrap(); + assert_eq!(v, serde_json::json!({"name": "Orca", "kind": "folder", "folder": "/mnt/orca"})); + assert_eq!(serde_json::from_value::(v).unwrap(), t); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_taken_name_gets_a_number_and_nothing_is_replaced_or_left_behind() { + let root = scratch("numbered"); + let (src, share) = (root.join("part.3mf"), root.join("share")); + std::fs::create_dir_all(&share).unwrap(); + std::fs::write(share.join("Bracket.3mf"), b"theirs").unwrap(); + std::fs::write(&src, b"ours").unwrap(); + let send = || deliver_within(&share, &src, "Bracket", "3mf", 1 << 20, Duration::from_secs(10)); + let first = send().unwrap(); + let second = send().unwrap(); + assert_eq!((first.path.file_name().unwrap(), first.numbered), (std::ffi::OsStr::new("Bracket (2).3mf"), true)); + assert_eq!(second.path.file_name().unwrap(), "Bracket (3).3mf"); + assert_eq!(std::fs::read(share.join("Bracket.3mf")).unwrap(), b"theirs", "the file that was there is untouched"); + assert_eq!(std::fs::read(&second.path).unwrap(), b"ours"); + assert_eq!(names(&share), ["Bracket (2).3mf", "Bracket (3).3mf", "Bracket.3mf"], "no temporary file is left"); + let fresh = deliver_within(&share, &src, "Base", "stl", 1 << 20, Duration::from_secs(10)).unwrap(); + assert_eq!((fresh.path.file_name().unwrap(), fresh.numbered), (std::ffi::OsStr::new("Base.stl"), false)); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_missing_folder_a_file_and_a_big_file_are_refused_in_words() { + let root = scratch("refused"); + let src = root.join("part.3mf"); + std::fs::write(&src, vec![0u8; 2_000]).unwrap(); + let gone = root.join("not-mounted"); + let e = deliver_within(&gone, &src, "Part", "3mf", 1 << 20, Duration::from_secs(10)).unwrap_err(); + assert!(e.contains("is not there") && e.contains("mounted"), "{e}"); + assert!(!gone.exists(), "a missing folder is never made"); + let e = deliver_within(&src, &src, "Part", "3mf", 1 << 20, Duration::from_secs(10)).unwrap_err(); + assert!(e.contains("not a folder"), "{e}"); + let share = root.join("share"); + std::fs::create_dir_all(&share).unwrap(); + let e = deliver_within(&share, &src, "Part", "3mf", 1_000, Duration::from_secs(10)).unwrap_err(); + assert!(e.contains("MB"), "{e}"); + assert!(names(&share).is_empty(), "nothing was written"); + assert!(probe_within(&gone, Duration::from_secs(10)).unwrap_err().contains("is not there")); + probe_within(&share, Duration::from_secs(10)).unwrap(); + assert!(names(&share).is_empty(), "the test file is deleted"); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn a_folder_without_write_permission_is_reported() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("readonly"); + let (src, share) = (root.join("part.3mf"), root.join("share")); + std::fs::write(&src, b"ours").unwrap(); + std::fs::create_dir_all(&share).unwrap(); + std::fs::set_permissions(&share, std::fs::Permissions::from_mode(0o555)).unwrap(); + // Root may write anywhere; the check means nothing then. + if std::fs::write(share.join("probe"), b"x").is_err() { + let e = deliver_within(&share, &src, "Part", "3mf", 1 << 20, Duration::from_secs(10)).unwrap_err(); + assert!(e.contains("no permission"), "{e}"); + assert!(probe_within(&share, Duration::from_secs(10)).unwrap_err().contains("no permission")); + } + std::fs::set_permissions(&share, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_copy_in_the_background_is_answered_once() { + let root = scratch("background"); + let (src, share) = (root.join("part.3mf"), root.join("share")); + std::fs::create_dir_all(&share).unwrap(); + std::fs::write(&src, b"ours").unwrap(); + let target = RemoteTarget::folder_target("Share", &share.to_string_lossy()); + let ticket = deliver_in_background(&target, &src, "Bracket", "3mf"); + let answer = (0..500) + .find_map(|_| { + let answer = poll(ticket); + if answer.is_none() { + std::thread::sleep(Duration::from_millis(10)); + } + answer + }) + .unwrap(); + assert_eq!(answer.unwrap().path, share.join("Bracket.3mf")); + assert!(poll(ticket).unwrap().is_err(), "answered once"); + assert!(poll(u64::MAX).unwrap().is_err(), "a ticket nobody was given"); + std::fs::remove_dir_all(root).unwrap(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_that_does_not_answer_is_given_up_on() { + let e = within(Duration::from_millis(50), "/mnt/gone", || { + std::thread::sleep(Duration::from_millis(500)); + Ok(()) + }) + .unwrap_err(); + assert!(e.contains("did not answer") && e.contains("/mnt/gone"), "{e}"); + } +} diff --git a/crates/engine/src/schema/file_remote.rs b/crates/engine/src/schema/file_remote.rs new file mode 100644 index 00000000000..3b4e6f6f34f --- /dev/null +++ b/crates/engine/src/schema/file_remote.rs @@ -0,0 +1,100 @@ +//! Contracts and result types for the commands in `cmd/file_remote.rs`: the network folders of +//! Send to Slicer (#2304). + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Add a network folder to Send to Slicer, replacing one of the same name. Nothing is written +/// until a mesh is sent there. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AddRemoteParams { + /// The name shown in the Send to Slicer list: 1 to 64 characters. + pub name: String, + /// The folder's whole path, such as a mounted SMB or NFS share that a slicer on another computer + /// reads. It need not be there yet; `file.slicers.test` checks it. + pub folder: String, +} + +/// What `file.slicers.add_remote` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RemoteFolderReply { + /// The id to pass as `slicer`: `remote:`. + pub id: String, + /// The name, trimmed. + pub name: String, + /// Always `folder`. + pub kind: String, + /// The folder, trimmed. + pub folder: String, + /// A network folder of that name was there and is replaced. + pub replaced: bool, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Remove a network folder from Send to Slicer. The files sent there stay. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct RemoveRemoteParams { + /// The network folder's name or id (`file.slicers`). + pub name: String, +} + +/// What `file.slicers.remove_remote` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RemoveRemoteReply { + /// The name of the network folder removed. + pub name: String, + /// Always true: a name that matches nothing is refused. + pub removed: bool, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// Check that a mesh can be sent to a folder: write a small file there and delete it again, +/// giving up after 30 s. Give one of `name` and `folder`. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct TestRemoteParams { + /// A network folder's name or id (`file.slicers`). + #[serde(default)] + pub name: Option, + /// A folder's whole path, to check before adding it. + #[serde(default)] + pub folder: Option, +} + +/// What `file.slicers.test` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct TestRemoteReply { + /// The file could be written there. + pub ok: bool, + /// The folder checked. + pub folder: String, + /// The network folder's name, when one was named. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// What went wrong, in words, when `ok` is false: not there, no permission, full, no answer. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +mod tests { + use super::{AddRemoteParams, RemoveRemoteParams, TestRemoteParams}; + use crate::schema::input_schema_for; + use crate::schema::tests::assert_keys; + + #[test] + fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["folder", "name"]); + assert_keys(input_schema_for::(), &["name"]); + assert_keys(input_schema_for::(), &["folder", "name"]); + } +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index a3709359c78..2713191da4e 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -72,6 +72,7 @@ pub mod end_cap; pub mod features; pub mod features_more; pub mod file; +pub mod file_remote; pub mod frame; pub mod insert_mesh; pub mod inspect; diff --git a/crates/engine/src/schema/save_mesh.rs b/crates/engine/src/schema/save_mesh.rs index 4d32f08db5a..74004bd6054 100644 --- a/crates/engine/src/schema/save_mesh.rs +++ b/crates/engine/src/schema/save_mesh.rs @@ -53,9 +53,10 @@ pub struct SaveMeshKeys { pub ascii: Option, /// A slicer to send the saved file to, after it is written where `path` says, through the /// same steps as `file.send_to_slicer`: an id or a name from `file.slicers`, the program path - /// it lists, or a program the user added under Custom…. A slicer that has to be started first - /// is waited for. Kept for scripts; may be deprecated later in favour of `file.send_to_slicer` - /// or a Send to App workflow. Default: none. + /// it lists, a program the user added under Custom…, or a network folder the user added (a + /// copy of the file goes there, under the file's name, numbered rather than replacing one). A + /// slicer that has to be started first is waited for. Kept for scripts; may be deprecated later + /// in favour of `file.send_to_slicer` or a Send to App workflow. Default: none. #[serde(default)] pub slicer: Option, /// Read only when `slicer` is given: true opens the file in the window the slicer already has @@ -317,13 +318,15 @@ impl JsonSchema for MeshObjects { } } -/// What happened when the saved file was handed to `slicer`. Only the one that applies is there. +/// What happened when the saved file was handed to `slicer`. Only the one that applies is there, +/// with `remote` and `target` too for a network folder. #[derive(Debug, Default, Serialize, JsonSchema)] pub struct SlicerDelivery { - /// The slicer's name: the file was opened there. + /// The slicer's or the network folder's name: the file was opened there, or copied there. #[serde(skip_serializing_if = "Option::is_none")] pub slicer: Option, - /// Why the program would not open the file. The file is saved either way. + /// Why the program would not open the file, or the copy to a network folder failed. The file + /// is saved either way. #[serde(skip_serializing_if = "Option::is_none")] pub slicer_error: Option, /// The slicer's name: the slicer had to be started first and was not ready (never for @@ -334,6 +337,23 @@ pub struct SlicerDelivery { /// not sent. The file is saved. #[serde(skip_serializing_if = "Option::is_none")] pub slicer_timeout: Option, + /// True when `slicer` named a network folder: the file was copied there, and no program was + /// started. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub remote: bool, + /// The network folder's name, whether the copy went or not. + #[serde(skip_serializing_if = "Option::is_none")] + pub target: Option, + /// Where the copy went in the network folder. + #[serde(skip_serializing_if = "Option::is_none")] + pub sent_to: Option, + /// True when a file of that name was already there, so the copy got a number. + #[serde(skip_serializing_if = "Option::is_none")] + pub renamed: Option, + /// The copy runs in the background: the ticket that says when it is done (never for + /// `file.save_mesh`, which waits for it). + #[serde(skip_serializing_if = "Option::is_none")] + pub sending: Option, } /// What `file.save_mesh` returns. diff --git a/crates/engine/src/schema/save_mesh_tests.rs b/crates/engine/src/schema/save_mesh_tests.rs index 014b5e34baf..55e235ec3e2 100644 --- a/crates/engine/src/schema/save_mesh_tests.rs +++ b/crates/engine/src/schema/save_mesh_tests.rs @@ -271,6 +271,31 @@ fn replies_with_a_slicer_match_the_output_schema() { let _ = std::fs::remove_dir_all(&dir); } +/// With a network folder as the `slicer`: the reply says where the copy went, and the output schema +/// describes each of its keys. +#[test] +fn replies_with_a_network_folder_match_the_output_schema() { + let dir = temp_dir("network-folder"); + let share = dir.join("share"); + std::fs::create_dir_all(&share).unwrap(); + let mut s = with_box(ParamCheck::Warn); + s.network_folders = vec![crate::remote_slicers::RemoteTarget::folder_target("NAS", &share.to_string_lossy())]; + let out = dir.join("part.stl").to_string_lossy().into_owned(); + let first = s.execute("file.save_mesh", &json!({"path": out, "slicer": "NAS"})).unwrap(); + let again = s.execute("file.save_mesh", &json!({"path": out, "slicer": "NAS"})).unwrap(); + let schema = output_schema_for::(); + let described: BTreeSet = schema.as_value()["properties"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); + for r in [&first, &again] { + matches(r); + assert_eq!(keys(r), ["bytes", "format", "path", "remote", "renamed", "sent_to", "slicer", "target"].map(String::from).into(), "{r}"); + assert!(keys(r).is_subset(&described), "{r} has keys {schema:?} doesn't describe"); + assert_eq!((&r["remote"], &r["slicer"], &r["target"]), (&json!(true), &json!("NAS"), &json!("NAS")), "{r}"); + assert!(r["sent_to"].as_str().is_some_and(|p| std::path::Path::new(p).starts_with(&share)), "{r}"); + } + assert_eq!((&first["renamed"], &again["renamed"]), (&json!(false), &json!(true)), "the second copy is numbered"); + let _ = std::fs::remove_dir_all(&dir); +} + /// The typed reply serializes to the keys the handler's JSON had, and nothing for what is unset. #[test] fn the_reply_type_serializes_as_before() { diff --git a/crates/engine/src/schema/slicers.rs b/crates/engine/src/schema/slicers.rs index 7ceff8f6e90..d90fa4c5c28 100644 --- a/crates/engine/src/schema/slicers.rs +++ b/crates/engine/src/schema/slicers.rs @@ -12,18 +12,43 @@ use serde::{Deserialize, Serialize}; #[schemars(deny_unknown_fields)] pub struct SlicersParams {} -/// What `file.slicers` returns: the slicers found on this machine, known ones in a fixed order -/// (empty in the browser). Pass an entry's `id`, its `name` or its `program` as -/// `file.send_to_slicer`'s or `file.save_mesh`'s `slicer`. +/// What `file.slicers` returns: the network folders the user added, then the slicers found on +/// this machine, known ones in a fixed order (no slicer in the browser). Pass an entry's `id`, +/// its `name` or a slicer's `program` as `file.send_to_slicer`'s or `file.save_mesh`'s `slicer`. #[derive(Debug, Serialize, JsonSchema)] pub struct SlicersResult { - /// The slicers installed on this machine. - pub slicers: Vec, + /// The network folders, then the slicers installed on this machine. + pub slicers: Vec, /// In the warn parameter-check mode: what the call's parameters got wrong. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub param_warnings: Vec, } +/// One entry of the list: a network folder or an installed slicer. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum SlicerEntry { + /// A network folder the user added (`file.slicers.add_remote`). + Folder(NetworkFolderInfo), + /// An installed slicer, or a program the user added under Custom…. + Slicer(SlicerInfo), +} + +/// One network folder the user added: a send copies the file there and starts no program. +#[derive(Debug, Serialize, JsonSchema)] +pub struct NetworkFolderInfo { + /// `remote:`. + pub id: String, + /// The name the user gave it. + pub name: String, + /// Always true: this entry is a network folder, not a slicer. + pub remote: bool, + /// `folder`: a folder on this computer, usually a mounted share. + pub kind: String, + /// The folder the files go to. + pub folder: String, +} + /// One installed slicer. #[derive(Debug, Serialize, JsonSchema)] pub struct SlicerInfo { diff --git a/crates/engine/src/schema/slicers_tests.rs b/crates/engine/src/schema/slicers_tests.rs index 44a764d20ed..d20767ba973 100644 --- a/crates/engine/src/schema/slicers_tests.rs +++ b/crates/engine/src/schema/slicers_tests.rs @@ -108,3 +108,27 @@ fn replies_match_the_output_schema() { let schema = output_schema_for::(); assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{warned}"); } + +/// A network folder the user added comes first in the list, with its own keys and no program, and +/// the reply still matches the output schema. +#[cfg(unix)] +#[test] +fn a_network_folder_is_listed_first_and_matches_the_output_schema() { + use crate::slicers::{Slicer, TEST_DETECTED}; + use crate::tests::mesh_convert::{CHOSEN_PROGRAMS, MadeUp}; + let _turn = CHOSEN_PROGRAMS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let _reset = MadeUp; + *TEST_DETECTED.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = + Some(vec![Slicer { id: "prusa".into(), name: "PrusaSlicer".into(), command: vec!["/opt/prusa".into()], icon: None, prusa_major: None }]); + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + s.network_folders = vec![crate::remote_slicers::RemoteTarget::folder_target("NAS", "/mnt/nas")]; + let listed = s.execute("file.slicers", &json!({})).unwrap_or_else(|e| panic!("{e}")); + assert_eq!( + listed, + json!({"slicers": [ + {"id": "remote:NAS", "name": "NAS", "remote": true, "kind": "folder", "folder": "/mnt/nas"}, + {"id": "prusa", "name": "PrusaSlicer", "program": "/opt/prusa", "icon": null}, + ]}) + ); + matches(&listed); +} diff --git a/crates/engine/src/slicer_files.rs b/crates/engine/src/slicer_files.rs index 872c8e7ef03..3c51fa15291 100644 --- a/crates/engine/src/slicer_files.rs +++ b/crates/engine/src/slicer_files.rs @@ -67,7 +67,11 @@ pub fn stem(design: &str, path: Option<&str>, uid: u64, bodies: &[String]) -> St /// file the slicer has open locked) the next free `-2.`, … is used; the flag says so. pub fn write(dir: &Path, stem: &str, ext: &str, bytes: &[u8]) -> io::Result<(PathBuf, bool)> { make_private(dir)?; - let tmp = dir.join(format!(".{stem}.{ext}.{}.tmp", std::process::id())); + // One temporary name per call: two sends at once (on copies of the design, #2304) shared one + // and the second found it gone. + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!(".{stem}.{ext}.{}-{n}.tmp", std::process::id())); std::fs::write(&tmp, bytes)?; let mut failure = None; for n in 1..=MAX_COPIES { diff --git a/crates/engine/src/tests/mesh_convert.rs b/crates/engine/src/tests/mesh_convert.rs index b8047425c81..8e030f76ae2 100644 --- a/crates/engine/src/tests/mesh_convert.rs +++ b/crates/engine/src/tests/mesh_convert.rs @@ -640,3 +640,234 @@ fn conversion_from_another_branch_names_the_component_to_activate() { assert_eq!(s.doc.to_json(), before); assert_eq!((s.active_component, s.active_occurrence_path.clone()), context); } + +/// The size cap of a copy to a network folder (#2304) is process-wide: a test that sends to one +/// holds this, and leaves the cap as it was however it ends. +struct NetworkFolders { + _turn: std::sync::MutexGuard<'static, ()>, + root: std::path::PathBuf, +} + +impl NetworkFolders { + fn new(tag: &str) -> NetworkFolders { + let turn = crate::remote_slicers::TEST_TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let root = std::env::temp_dir().join(format!("solidcraft-network-folder-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("share")).unwrap(); + NetworkFolders { _turn: turn, root } + } + + fn share(&self) -> std::path::PathBuf { + self.root.join("share") + } + + fn files(&self) -> Vec { + let mut v: Vec = std::fs::read_dir(self.share()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + } +} + +impl Drop for NetworkFolders { + fn drop(&mut self) { + *crate::remote_slicers::TEST_MAX_BYTES.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None; + let _ = std::fs::remove_dir_all(&self.root); + } +} + +#[test] +fn network_folders_are_added_listed_tested_and_removed_by_command() { + let net = NetworkFolders::new("commands"); + let mut s = imported_box(); + let share = net.share().to_string_lossy().into_owned(); + let added = s.execute("file.slicers.add_remote", &json!({"name": " Orca on homelab ", "folder": share})).unwrap(); + assert_eq!(added["id"], "remote:Orca on homelab"); + assert_eq!((added["kind"].as_str(), added["replaced"].as_bool()), (Some("folder"), Some(false))); + let listed = s.execute("file.slicers", &json!({})).unwrap(); + let first = &listed["slicers"][0]; + assert_eq!( + (first["id"].as_str(), first["remote"].as_bool(), first["folder"].as_str()), + (Some("remote:Orca on homelab"), Some(true), Some(share.as_str())) + ); + let again = s.execute("file.slicers.add_remote", &json!({"name": "orca on HOMELAB", "folder": share})).unwrap(); + assert_eq!(again["replaced"], true, "the same name in another case replaces it"); + assert_eq!(s.network_folders.len(), 1); + + let ok = s.execute("file.slicers.test", &json!({"name": "remote:orca on homelab"})).unwrap(); + assert_eq!((ok["ok"].as_bool(), ok["error"].is_null()), (Some(true), true)); + assert!(net.files().is_empty(), "the test file is deleted"); + let gone = net.root.join("not-mounted").to_string_lossy().into_owned(); + let missing = s.execute("file.slicers.test", &json!({"folder": gone})).unwrap(); + assert_eq!(missing["ok"], false); + assert!(missing["error"].as_str().unwrap().contains("mounted"), "{missing}"); + + // An agent limited to other folders (--allow-path) can neither test the folder the user added + // nor send there, in the foreground or the background; one allowed it can. + let elsewhere = net.root.join("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + solidcraft_io::vfs::scoped(Some(solidcraft_io::vfs::PathScope::new([elsewhere])), || { + let tested = s.execute("file.slicers.test", &json!({"name": "Orca on homelab"})).unwrap_err().to_string(); + assert!(tested.contains("--allow-path"), "{tested}"); + for wait in ["block", "return"] { + let send = json!({"slicer": "Orca on homelab", "bodies": ["Mesh"], "wait": wait}); + let sent = s.execute("file.send_to_slicer", &send).unwrap_err().to_string(); + assert!(sent.contains("--allow-path"), "{wait}: {sent}"); + } + }); + assert!(net.files().is_empty(), "nothing sent: {:?}", net.files()); + solidcraft_io::vfs::scoped(Some(solidcraft_io::vfs::PathScope::new([net.root.clone()])), || { + assert_eq!(s.execute("file.slicers.test", &json!({"name": "Orca on homelab"})).unwrap()["ok"], true); + }); + + for bad in [ + json!({"name": "", "folder": share}), + json!({"name": "x".repeat(65), "folder": share}), + json!({"name": "Relative", "folder": "some/folder"}), + json!({"name": "No folder"}), + ] { + assert!(s.execute("file.slicers.add_remote", &bad).is_err(), "{bad}"); + } + // A key the command doesn't take is kept nowhere: warned about, or refused when checks are strict. + let extra = json!({"name": "Extra", "folder": share, "password": "never"}); + s.param_check = crate::schema::ParamCheck::Warn; + let warned = s.execute("file.slicers.add_remote", &extra).unwrap(); + assert!(warned["param_warnings"].to_string().contains("password"), "{warned}"); + assert!(!serde_json::to_string(&s.network_folders).unwrap().contains("never")); + s.execute("file.slicers.remove_remote", &json!({"name": "remote:Extra"})).unwrap(); + s.param_check = crate::schema::ParamCheck::Strict; + assert!(s.execute("file.slicers.add_remote", &extra).is_err()); + assert!(crate::remote_slicers::resolve(&s.network_folders, "Extra").is_none()); + s.param_check = crate::schema::ParamCheck::Off; + assert!(s.execute("file.slicers.test", &json!({})).is_err()); + assert!(s.execute("file.slicers.test", &json!({"name": "Orca on homelab", "folder": share})).is_err()); + assert!(s.execute("file.slicers.test", &json!({"name": "Nobody"})).is_err()); + + // The user's, not the design's: they stay when another design is started. + assert!(!s.doc.to_json().contains(&share), "never saved in the design"); + s.execute("file.new", &json!({})).unwrap(); + assert_eq!(s.network_folders.len(), 1, "kept across designs"); + + let removed = s.execute("file.slicers.remove_remote", &json!({"name": "Orca on homelab"})).unwrap(); + assert_eq!(removed["removed"], true); + assert!(s.execute("file.slicers.remove_remote", &json!({"name": "Orca on homelab"})).is_err()); + assert!(s.execute("file.slicers", &json!({})).unwrap()["slicers"].as_array().unwrap().iter().all(|t| t["remote"].is_null())); +} + +#[test] +fn sending_to_a_network_folder_writes_a_readable_name_and_never_replaces_a_file() { + let net = NetworkFolders::new("send"); + let mut s = imported_box(); + let share = net.share().to_string_lossy().into_owned(); + s.execute("file.slicers.add_remote", &json!({"name": "Orca", "folder": share})).unwrap(); + // A file of the readable name is already there, from someone else. + std::fs::write(net.share().join("Untitled - Mesh.3mf"), b"theirs").unwrap(); + let send = |s: &mut Session, p: Value| s.execute("file.send_to_slicer", &p).unwrap(); + let first = send(&mut s, json!({"slicer": "remote:Orca", "bodies": ["Mesh"]})); + assert_eq!((first["remote"].as_bool(), first["slicer"].as_str(), first["renamed"].as_bool()), (Some(true), Some("Orca"), Some(true))); + assert!(first["slicer_error"].is_null(), "{first}"); + let second = send(&mut s, json!({"slicer": "orca", "bodies": ["Mesh"]})); + assert!(second["sent_to"].as_str().unwrap().ends_with("Untitled - Mesh (3).3mf"), "{second}"); + assert_eq!(std::fs::read(net.share().join("Untitled - Mesh.3mf")).unwrap(), b"theirs"); + let sent = std::fs::read(first["sent_to"].as_str().unwrap()).unwrap(); + assert!(sent.starts_with(b"PK"), "a 3MF, as the slicer folder's file"); + assert_eq!(sent, std::fs::read(first["path"].as_str().unwrap()).unwrap(), "the same bytes as the file saved here"); + + // Format and STL encoding are kept. + let stl = send(&mut s, json!({"slicer": "Orca", "bodies": ["Mesh"], "format": "stl"})); + let ascii = send(&mut s, json!({"slicer": "Orca", "bodies": ["Mesh"], "format": "stl", "ascii": true})); + assert!(stl["sent_to"].as_str().unwrap().ends_with("Untitled - Mesh.stl"), "{stl}"); + assert!(ascii["sent_to"].as_str().unwrap().ends_with("Untitled - Mesh (2).stl"), "{ascii}"); + assert!(!std::fs::read(stl["sent_to"].as_str().unwrap()).unwrap().starts_with(b"solid")); + assert!(std::fs::read(ascii["sent_to"].as_str().unwrap()).unwrap().starts_with(b"solid")); + assert_eq!( + net.files(), + ["Untitled - Mesh (2).3mf", "Untitled - Mesh (3).3mf", "Untitled - Mesh (2).stl", "Untitled - Mesh.3mf", "Untitled - Mesh.stl"] + .map(String::from) + .into_iter() + .collect::>() + .into_iter() + .collect::>() + ); + + // file.save_mesh with a network folder keeps the file's own name. + let path = net.root.join("bracket v2.stl"); + let saved = s.execute("file.save_mesh", &json!({"path": path, "slicer": "Orca", "bodies": ["Mesh"]})).unwrap(); + assert!(saved["sent_to"].as_str().unwrap().ends_with("bracket v2.stl"), "{saved}"); + assert!(path.exists()); + + // wait: return, as the window sends: answered at once, and the copy goes on in the background. + let r = send(&mut s, json!({"slicer": "Orca", "bodies": ["Mesh"], "format": "stl", "wait": "return"})); + assert!(r["sent_to"].is_null() && r["remote"] == true, "{r}"); + let ticket = r["sending"].as_u64().unwrap(); + let done = (0..500) + .find_map(|_| { + let answer = crate::remote_slicers::poll(ticket); + if answer.is_none() { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + answer + }) + .unwrap() + .unwrap(); + assert_eq!(done.path, net.share().join("Untitled - Mesh (3).stl")); +} + +#[test] +fn quality_reaches_the_file_sent_to_a_network_folder() { + let net = NetworkFolders::new("quality"); + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"diameter": 20, "height": 10})); + let share = net.share().to_string_lossy().into_owned(); + s.execute("file.slicers.add_remote", &json!({"name": "Orca", "folder": share})).unwrap(); + let size = |s: &mut Session, quality: &str| { + let r = s.execute("file.send_to_slicer", &json!({"slicer": "Orca", "format": "stl", "quality": quality, "bodies": ["Body1"]})).unwrap(); + std::fs::metadata(r["sent_to"].as_str().unwrap()).unwrap().len() + }; + let (standard, finest) = (size(&mut s, "standard"), size(&mut s, "finest")); + assert!(finest > standard, "finest follows the curve more closely: {finest} > {standard} bytes"); + assert!(s.execute("file.send_to_slicer", &json!({"slicer": "Orca", "quality": "coarse", "bodies": ["Body1"]})).is_err()); +} + +#[test] +fn a_network_folder_that_cannot_take_the_file_is_reported_and_nothing_crashes() { + let net = NetworkFolders::new("errors"); + let mut s = imported_box(); + let gone = net.root.join("not-mounted"); + s.execute("file.slicers.add_remote", &json!({"name": "Gone", "folder": gone})).unwrap(); + s.execute("file.slicers.add_remote", &json!({"name": "Small", "folder": net.share()})).unwrap(); + + // Not mounted: the file is saved here, the folder is not made, and the reply says why. + let r = s.execute("file.send_to_slicer", &json!({"slicer": "Gone", "bodies": ["Mesh"]})).unwrap(); + let e = r["slicer_error"].as_str().unwrap(); + assert!(e.contains("Gone") && e.contains("mounted"), "{e}"); + assert!(r["sent_to"].is_null() && std::path::Path::new(r["path"].as_str().unwrap()).exists()); + assert!(!gone.exists(), "a missing folder is never made"); + + // Over the size cap: refused before anything is copied. + *crate::remote_slicers::TEST_MAX_BYTES.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(100); + let r = s.execute("file.send_to_slicer", &json!({"slicer": "Small", "bodies": ["Mesh"]})).unwrap(); + assert!(r["slicer_error"].as_str().unwrap().contains("MB"), "{r}"); + assert!(net.files().is_empty()); + *crate::remote_slicers::TEST_MAX_BYTES.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None; + + // No permission to write there. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(net.share(), std::fs::Permissions::from_mode(0o555)).unwrap(); + // Root may write anywhere; the check means nothing then. + if std::fs::write(net.share().join("probe"), b"x").is_err() { + let r = s.execute("file.send_to_slicer", &json!({"slicer": "Small", "bodies": ["Mesh"]})).unwrap(); + assert!(r["slicer_error"].as_str().unwrap().contains("no permission"), "{r}"); + } + std::fs::set_permissions(net.share(), std::fs::Permissions::from_mode(0o755)).unwrap(); + } + + // A network folder that isn't there is refused before anything is written. + let before = s.execute("file.slicers", &json!({})).unwrap(); + assert!(s.execute("file.send_to_slicer", &json!({"slicer": "remote:Nobody", "bodies": ["Mesh"]})).is_err()); + let path = net.root.join("unknown.stl"); + assert!(s.execute("file.save_mesh", &json!({"path": path, "slicer": "remote:Nobody"})).is_err()); + assert!(!path.exists()); + assert_eq!(s.execute("file.slicers", &json!({})).unwrap(), before); +} diff --git a/crates/ui-egui/src/dialogs_save_mesh.rs b/crates/ui-egui/src/dialogs_save_mesh.rs index 40c6f129ba0..cf92729131b 100644 --- a/crates/ui-egui/src/dialogs_save_mesh.rs +++ b/crates/ui-egui/src/dialogs_save_mesh.rs @@ -1043,7 +1043,7 @@ mod tests { assert_eq!(bodies(&mut h, id), one, "{id}"); } let (_, p) = commands( - &SaveMesh { format: 0, quality: 0, open: false, slicer: String::new(), stale: true, shown: None }, + &SaveMesh { format: 0, send_format: 0, quality: 0, open: false, slicer: String::new(), stale: true, shown: None }, &h.app.dialog.as_ref().unwrap().inputs, ) .map(|mut c| c.remove(0)) diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT index ad72180eab4..de0e22de10d 100644 --- a/tests/kernel-cases/EXEMPT +++ b/tests/kernel-cases/EXEMPT @@ -84,6 +84,9 @@ file.save_as saving the design file.save_mesh saving a display mesh file.send_to_slicer hands the file to a slicer file.slicers a listing of slicers +file.slicers.add_remote a network folder for Send to Slicer; crates/engine/src/tests/mesh_convert.rs +file.slicers.remove_remote a network folder for Send to Slicer; crates/engine/src/tests/mesh_convert.rs +file.slicers.test a network folder for Send to Slicer; crates/engine/src/tests/mesh_convert.rs frame.end_cap plates on member ends; tested in crates/engine/src/cmd/frame_tests.rs frame.profile.list a listing of the profile library frame.profile.properties a profile's section properties from the library From 28c23314a27a57e431c2fa8db8cdadc3517a8dc2 Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Sun, 1 Nov 2026 15:37:10 -0300 Subject: [PATCH 2/3] Send to Slicer: Format and Quality rows, and a Network folder window (#2304) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Send to Slicer gets the Format (3MF, STL binary, STL ASCII) and Quality (Standard, Fine, Finest) rows Save as Mesh has, remembered on their own; the defaults stay 3MF and Standard, and EasyPrint keeps 3MF without them. "Network folder…" under "Custom…" opens a small window with a name, a folder (typed or picked) and Test, which writes and deletes a probe file. Saved folders are listed first with a network icon, Delete removes one, and Preferences > General > Slicer lists them to edit or remove. They are kept in the preferences; the browser build offers none. A copy runs in the background and the status line says where the file went or why not. --- apps/solidcraft/src/main.rs | 5 + .../pending/slicer-network-folder.json | 288 +++++++++++- crates/ui-egui/src/control_job.rs | 102 +++- crates/ui-egui/src/dialogs_save_mesh.rs | 438 ++++++++++++++++-- crates/ui-egui/src/file_picker.rs | 9 + .../ui-egui/src/history_off_thread_tests.rs | 81 ++++ crates/ui-egui/src/lib.rs | 29 +- crates/ui-egui/src/network_folder_ui.rs | 348 ++++++++++++++ crates/ui-egui/src/prefs.rs | 46 ++ crates/ui-egui/src/prefs/general.rs | 4 + 10 files changed, 1290 insertions(+), 60 deletions(-) create mode 100644 crates/ui-egui/src/network_folder_ui.rs diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index ef5e3ad9ff2..b70c1b6b6c6 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -506,6 +506,7 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services let chooser_ctx = cc.egui_ctx.clone(); let open_parent = parent.clone(); let program_parent = parent.clone(); + let folder_parent = parent.clone(); let file_parent = parent.clone(); let (open_folder, file_folder, save_folder) = (folder.clone(), folder.clone(), folder.clone()); Services { @@ -553,6 +554,10 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services let future = dialog.pick_file(); Box::pin(async move { future.await.map(|p| p.path().to_string_lossy().into_owned()) }) })), + pick_folder: Some(Box::new(move || { + let future = folder_parent.clone().set_title("Choose the network folder").pick_folder(); + Box::pin(async move { future.await.map(|p| p.path().to_string_lossy().into_owned()) }) + })), pick_save: Some(Box::new(move |name: &str, exts: &[&str]| { let dialog = save_folder.start(parent.clone()).set_file_name(name); let dialog = if exts == [io::DESIGN_EXT, "json"] { diff --git a/assets/locales/pending/slicer-network-folder.json b/assets/locales/pending/slicer-network-folder.json index 60763368e7b..fc4e8c006ef 100644 --- a/assets/locales/pending/slicer-network-folder.json +++ b/assets/locales/pending/slicer-network-folder.json @@ -2,46 +2,316 @@ "en": { "cmd.file_slicers_add_remote": "Add Network Folder", "cmd.file_slicers_remove_remote": "Remove Network Folder", - "cmd.file_slicers_test": "Test Network Folder" + "cmd.file_slicers_test": "Test Network Folder", + "ui.mesh_format_stl_binary": "STL (binary)", + "ui.mesh_format_stl_ascii": "STL (ASCII)", + "ui.network_folder_row": "Network folder…", + "ui.network_folder_tip": "Add a folder that a slicer on another computer reads, such as a mounted SMB or NFS share", + "ui.network_folder_delete_tip": "{folder}\nPress Delete to remove it from the list", + "ui.network_folder_title": "Add Network Folder", + "ui.network_folder_edit_title": "Edit Network Folder", + "ui.network_folder_note": "Send to Slicer copies the file into this folder and starts no program. Choose a shared folder mounted on this computer, such as an SMB or NFS share that a slicer on your server reads. A file already there is never replaced.", + "ui.network_folder_name": "Name", + "ui.network_folder_name_hint": "Orca on the server", + "ui.network_folder_folder": "Folder", + "ui.network_folder_folder_hint": "/mnt/printer-share", + "ui.network_folder_browse": "Browse…", + "ui.network_folder_test": "Test", + "ui.network_folder_testing": "Writing a test file…", + "ui.network_folder_test_ok": "A file can be written there.", + "ui.network_folder_test_stopped": "The test stopped unexpectedly.", + "ui.network_folder_name_taken": "A network folder already has this name.", + "ui.network_folder_add": "Add", + "ui.network_folder_save": "Save", + "ui.network_folder_added": "Network folder {name} saved: {folder}", + "ui.network_folder_sending": "Copying to {target}…", + "ui.network_folder_still_sending": "Still copying to {target}. Nothing else was sent.", + "ui.sent_to_network_folder": "Sent to {target}: {path}", + "ui.network_folder_send_failed": "Couldn't send to {target}: {error}. The file is saved at {path}", + "ui.network_folders": "Network folders", + "ui.network_folders_none": "None yet. Add a folder that a slicer on another computer reads; it appears at the top of the Send to Slicer list.", + "ui.network_folder_edit": "Edit", + "ui.network_folder_remove": "Remove", + "ui.network_folder_add_button": "Add network folder…" }, "de": { "cmd.file_slicers_add_remote": "Netzwerkordner hinzufügen", "cmd.file_slicers_remove_remote": "Netzwerkordner entfernen", - "cmd.file_slicers_test": "Netzwerkordner testen" + "cmd.file_slicers_test": "Netzwerkordner testen", + "ui.mesh_format_stl_binary": "STL (binär)", + "ui.mesh_format_stl_ascii": "STL (ASCII)", + "ui.network_folder_row": "Netzwerkordner…", + "ui.network_folder_tip": "Einen Ordner hinzufügen, den ein Slicer auf einem anderen Computer liest, etwa eine eingebundene SMB- oder NFS-Freigabe", + "ui.network_folder_delete_tip": "{folder}\nMit Entf aus der Liste entfernen", + "ui.network_folder_title": "Netzwerkordner hinzufügen", + "ui.network_folder_edit_title": "Netzwerkordner bearbeiten", + "ui.network_folder_note": "An Slicer senden kopiert die Datei in diesen Ordner und startet kein Programm. Wählen Sie einen auf diesem Computer eingebundenen freigegebenen Ordner, etwa eine SMB- oder NFS-Freigabe, die ein Slicer auf Ihrem Server liest. Eine vorhandene Datei wird nie ersetzt.", + "ui.network_folder_name": "Name", + "ui.network_folder_name_hint": "Orca auf dem Server", + "ui.network_folder_folder": "Ordner", + "ui.network_folder_folder_hint": "/mnt/printer-share", + "ui.network_folder_browse": "Durchsuchen…", + "ui.network_folder_test": "Testen", + "ui.network_folder_testing": "Testdatei wird geschrieben…", + "ui.network_folder_test_ok": "Dort kann eine Datei geschrieben werden.", + "ui.network_folder_test_stopped": "Der Test wurde unerwartet beendet.", + "ui.network_folder_name_taken": "Ein Netzwerkordner mit diesem Namen existiert bereits.", + "ui.network_folder_add": "Hinzufügen", + "ui.network_folder_save": "Speichern", + "ui.network_folder_added": "Netzwerkordner {name} gespeichert: {folder}", + "ui.network_folder_sending": "Wird nach {target} kopiert…", + "ui.network_folder_still_sending": "Es wird noch nach {target} kopiert. Sonst wurde nichts gesendet.", + "ui.sent_to_network_folder": "An {target} gesendet: {path}", + "ui.network_folder_send_failed": "Senden an {target} nicht möglich: {error}. Die Datei ist unter {path} gespeichert", + "ui.network_folders": "Netzwerkordner", + "ui.network_folders_none": "Noch keine. Fügen Sie einen Ordner hinzu, den ein Slicer auf einem anderen Computer liest; er erscheint oben in der Liste von An Slicer senden.", + "ui.network_folder_edit": "Bearbeiten", + "ui.network_folder_remove": "Entfernen", + "ui.network_folder_add_button": "Netzwerkordner hinzufügen…" }, "ar": { "cmd.file_slicers_add_remote": "إضافة مجلد شبكة", "cmd.file_slicers_remove_remote": "إزالة مجلد شبكة", - "cmd.file_slicers_test": "اختبار مجلد شبكة" + "cmd.file_slicers_test": "اختبار مجلد شبكة", + "ui.mesh_format_stl_binary": "STL (ثنائي)", + "ui.mesh_format_stl_ascii": "STL (ASCII)", + "ui.network_folder_row": "مجلد شبكة…", + "ui.network_folder_tip": "أضف مجلدًا يقرؤه برنامج تقطيع على حاسوب آخر، مثل مشاركة SMB أو NFS مركّبة", + "ui.network_folder_delete_tip": "{folder}\nاضغط Delete لإزالته من القائمة", + "ui.network_folder_title": "إضافة مجلد شبكة", + "ui.network_folder_edit_title": "تعديل مجلد الشبكة", + "ui.network_folder_note": "ينسخ «إرسال إلى برنامج التقطيع» الملف إلى هذا المجلد ولا يشغّل أي برنامج. اختر مجلدًا مشتركًا مركّبًا على هذا الحاسوب، مثل مشاركة SMB أو NFS يقرؤها برنامج تقطيع على خادمك. لا يُستبدل أي ملف موجود فيه.", + "ui.network_folder_name": "الاسم", + "ui.network_folder_name_hint": "Orca على الخادم", + "ui.network_folder_folder": "المجلد", + "ui.network_folder_folder_hint": "/mnt/printer-share", + "ui.network_folder_browse": "استعراض…", + "ui.network_folder_test": "اختبار", + "ui.network_folder_testing": "جارٍ كتابة ملف اختبار…", + "ui.network_folder_test_ok": "يمكن كتابة ملف هناك.", + "ui.network_folder_test_stopped": "توقف الاختبار على نحو غير متوقع.", + "ui.network_folder_name_taken": "يوجد مجلد شبكة بهذا الاسم بالفعل.", + "ui.network_folder_add": "إضافة", + "ui.network_folder_save": "حفظ", + "ui.network_folder_added": "حُفظ مجلد الشبكة {name}: {folder}", + "ui.network_folder_sending": "جارٍ النسخ إلى {target}…", + "ui.network_folder_still_sending": "لا يزال النسخ إلى {target} جاريًا. لم يُرسل أي شيء آخر.", + "ui.sent_to_network_folder": "أُرسل إلى {target}: {path}", + "ui.network_folder_send_failed": "تعذّر الإرسال إلى {target}: {error}. الملف محفوظ في {path}", + "ui.network_folders": "مجلدات الشبكة", + "ui.network_folders_none": "لا يوجد أي مجلد بعد. أضف مجلدًا يقرؤه برنامج تقطيع على حاسوب آخر؛ وسيظهر في أعلى قائمة «إرسال إلى برنامج التقطيع».", + "ui.network_folder_edit": "تعديل", + "ui.network_folder_remove": "إزالة", + "ui.network_folder_add_button": "إضافة مجلد شبكة…" }, "he": { "cmd.file_slicers_add_remote": "הוספת תיקיית רשת", "cmd.file_slicers_remove_remote": "הסרת תיקיית רשת", - "cmd.file_slicers_test": "בדיקת תיקיית רשת" + "cmd.file_slicers_test": "בדיקת תיקיית רשת", + "ui.mesh_format_stl_binary": "STL (בינארי)", + "ui.mesh_format_stl_ascii": "STL (ASCII)", + "ui.network_folder_row": "תיקיית רשת…", + "ui.network_folder_tip": "הוספת תיקייה שסלייסר במחשב אחר קורא ממנה, כמו שיתוף SMB או NFS מחובר", + "ui.network_folder_delete_tip": "{folder}\nיש ללחוץ על Delete כדי להסיר מהרשימה", + "ui.network_folder_title": "הוספת תיקיית רשת", + "ui.network_folder_edit_title": "עריכת תיקיית רשת", + "ui.network_folder_note": "שליחה לסלייסר מעתיקה את הקובץ לתיקייה הזו ולא מפעילה שום תוכנה. יש לבחור תיקייה משותפת שמחוברת למחשב הזה, כמו שיתוף SMB או NFS שסלייסר בשרת קורא ממנו. קובץ שכבר נמצא שם אף פעם לא מוחלף.", + "ui.network_folder_name": "שם", + "ui.network_folder_name_hint": "Orca בשרת", + "ui.network_folder_folder": "תיקייה", + "ui.network_folder_folder_hint": "/mnt/printer-share", + "ui.network_folder_browse": "עיון…", + "ui.network_folder_test": "בדיקה", + "ui.network_folder_testing": "כותב קובץ בדיקה…", + "ui.network_folder_test_ok": "אפשר לכתוב קובץ לשם.", + "ui.network_folder_test_stopped": "הבדיקה נעצרה באופן בלתי צפוי.", + "ui.network_folder_name_taken": "כבר קיימת תיקיית רשת בשם הזה.", + "ui.network_folder_add": "הוספה", + "ui.network_folder_save": "שמירה", + "ui.network_folder_added": "תיקיית הרשת {name} נשמרה: {folder}", + "ui.network_folder_sending": "מעתיק אל {target}…", + "ui.network_folder_still_sending": "עדיין מעתיק אל {target}. שום דבר נוסף לא נשלח.", + "ui.sent_to_network_folder": "נשלח ל־{target}: {path}", + "ui.network_folder_send_failed": "לא ניתן היה לשלוח ל־{target}: {error}. הקובץ שמור ב־{path}", + "ui.network_folders": "תיקיות רשת", + "ui.network_folders_none": "עדיין אין. יש להוסיף תיקייה שסלייסר במחשב אחר קורא ממנה; היא תופיע בראש הרשימה של שליחה לסלייסר.", + "ui.network_folder_edit": "עריכה", + "ui.network_folder_remove": "הסרה", + "ui.network_folder_add_button": "הוספת תיקיית רשת…" }, "ja": { "cmd.file_slicers_add_remote": "ネットワークフォルダーを追加", "cmd.file_slicers_remove_remote": "ネットワークフォルダーを削除", - "cmd.file_slicers_test": "ネットワークフォルダーをテスト" + "cmd.file_slicers_test": "ネットワークフォルダーをテスト", + "ui.mesh_format_stl_binary": "STL(バイナリ)", + "ui.mesh_format_stl_ascii": "STL(ASCII)", + "ui.network_folder_row": "ネットワークフォルダー…", + "ui.network_folder_tip": "別のコンピューターのスライサーが読み込むフォルダー(マウントした SMB や NFS の共有など)を追加", + "ui.network_folder_delete_tip": "{folder}\nDelete キーでリストから削除", + "ui.network_folder_title": "ネットワークフォルダーを追加", + "ui.network_folder_edit_title": "ネットワークフォルダーを編集", + "ui.network_folder_note": "スライサーに送ると、ファイルをこのフォルダーにコピーします。プログラムは起動しません。このコンピューターにマウントされた共有フォルダー(サーバーのスライサーが読み込む SMB や NFS の共有など)を選んでください。既にあるファイルは置き換えません。", + "ui.network_folder_name": "名前", + "ui.network_folder_name_hint": "サーバーの Orca", + "ui.network_folder_folder": "フォルダー", + "ui.network_folder_folder_hint": "/mnt/printer-share", + "ui.network_folder_browse": "参照…", + "ui.network_folder_test": "テスト", + "ui.network_folder_testing": "テストファイルを書き込んでいます…", + "ui.network_folder_test_ok": "このフォルダーにファイルを書き込めます。", + "ui.network_folder_test_stopped": "テストが予期せず停止しました。", + "ui.network_folder_name_taken": "この名前のネットワークフォルダーは既にあります。", + "ui.network_folder_add": "追加", + "ui.network_folder_save": "保存", + "ui.network_folder_added": "ネットワークフォルダー {name} を保存しました: {folder}", + "ui.network_folder_sending": "{target} にコピーしています…", + "ui.network_folder_still_sending": "まだ {target} にコピーしています。他には何も送信していません。", + "ui.sent_to_network_folder": "{target} に送信しました: {path}", + "ui.network_folder_send_failed": "{target} に送信できませんでした: {error}。ファイルは {path} に保存されています", + "ui.network_folders": "ネットワークフォルダー", + "ui.network_folders_none": "まだありません。別のコンピューターのスライサーが読み込むフォルダーを追加すると、「スライサーに送る」のリストの先頭に表示されます。", + "ui.network_folder_edit": "編集", + "ui.network_folder_remove": "削除", + "ui.network_folder_add_button": "ネットワークフォルダーを追加…" }, "ko": { "cmd.file_slicers_add_remote": "네트워크 폴더 추가", "cmd.file_slicers_remove_remote": "네트워크 폴더 제거", - "cmd.file_slicers_test": "네트워크 폴더 테스트" + "cmd.file_slicers_test": "네트워크 폴더 테스트", + "ui.mesh_format_stl_binary": "STL(바이너리)", + "ui.mesh_format_stl_ascii": "STL(ASCII)", + "ui.network_folder_row": "네트워크 폴더…", + "ui.network_folder_tip": "다른 컴퓨터의 슬라이서가 읽는 폴더(마운트된 SMB 또는 NFS 공유 등)를 추가", + "ui.network_folder_delete_tip": "{folder}\nDelete 키로 목록에서 제거", + "ui.network_folder_title": "네트워크 폴더 추가", + "ui.network_folder_edit_title": "네트워크 폴더 편집", + "ui.network_folder_note": "슬라이서로 보내기는 파일을 이 폴더에 복사하며 프로그램을 시작하지 않습니다. 서버의 슬라이서가 읽는 SMB 또는 NFS 공유처럼 이 컴퓨터에 마운트된 공유 폴더를 선택하세요. 이미 있는 파일은 절대 바꾸지 않습니다.", + "ui.network_folder_name": "이름", + "ui.network_folder_name_hint": "서버의 Orca", + "ui.network_folder_folder": "폴더", + "ui.network_folder_folder_hint": "/mnt/printer-share", + "ui.network_folder_browse": "찾아보기…", + "ui.network_folder_test": "테스트", + "ui.network_folder_testing": "테스트 파일을 쓰는 중…", + "ui.network_folder_test_ok": "이 폴더에 파일을 쓸 수 있습니다.", + "ui.network_folder_test_stopped": "테스트가 예기치 않게 중지되었습니다.", + "ui.network_folder_name_taken": "같은 이름의 네트워크 폴더가 이미 있습니다.", + "ui.network_folder_add": "추가", + "ui.network_folder_save": "저장", + "ui.network_folder_added": "네트워크 폴더 {name} 저장됨: {folder}", + "ui.network_folder_sending": "{target}(으)로 복사하는 중…", + "ui.network_folder_still_sending": "아직 {target}(으)로 복사하는 중입니다. 다른 것은 보내지 않았습니다.", + "ui.sent_to_network_folder": "{target}(으)로 보냈습니다: {path}", + "ui.network_folder_send_failed": "{target}(으)로 보낼 수 없습니다: {error}. 파일은 {path}에 저장되어 있습니다", + "ui.network_folders": "네트워크 폴더", + "ui.network_folders_none": "아직 없습니다. 다른 컴퓨터의 슬라이서가 읽는 폴더를 추가하면 슬라이서로 보내기 목록 맨 위에 표시됩니다.", + "ui.network_folder_edit": "편집", + "ui.network_folder_remove": "제거", + "ui.network_folder_add_button": "네트워크 폴더 추가…" }, "pt-BR": { "cmd.file_slicers_add_remote": "Adicionar pasta de rede", "cmd.file_slicers_remove_remote": "Remover pasta de rede", - "cmd.file_slicers_test": "Testar pasta de rede" + "cmd.file_slicers_test": "Testar pasta de rede", + "ui.mesh_format_stl_binary": "STL (binário)", + "ui.mesh_format_stl_ascii": "STL (ASCII)", + "ui.network_folder_row": "Pasta de rede…", + "ui.network_folder_tip": "Adicionar uma pasta que um fatiador em outro computador lê, como um compartilhamento SMB ou NFS montado", + "ui.network_folder_delete_tip": "{folder}\nPressione Delete para removê-la da lista", + "ui.network_folder_title": "Adicionar pasta de rede", + "ui.network_folder_edit_title": "Editar pasta de rede", + "ui.network_folder_note": "Enviar ao fatiador copia o arquivo para esta pasta e não abre nenhum programa. Escolha uma pasta compartilhada montada neste computador, como um compartilhamento SMB ou NFS que um fatiador no seu servidor lê. Um arquivo que já está lá nunca é substituído.", + "ui.network_folder_name": "Nome", + "ui.network_folder_name_hint": "Orca no servidor", + "ui.network_folder_folder": "Pasta", + "ui.network_folder_folder_hint": "/mnt/printer-share", + "ui.network_folder_browse": "Procurar…", + "ui.network_folder_test": "Testar", + "ui.network_folder_testing": "Gravando um arquivo de teste…", + "ui.network_folder_test_ok": "Dá para gravar arquivos ali.", + "ui.network_folder_test_stopped": "O teste parou inesperadamente.", + "ui.network_folder_name_taken": "Já existe uma pasta de rede com esse nome.", + "ui.network_folder_add": "Adicionar", + "ui.network_folder_save": "Salvar", + "ui.network_folder_added": "Pasta de rede {name} salva: {folder}", + "ui.network_folder_sending": "Copiando para {target}…", + "ui.network_folder_still_sending": "Ainda copiando para {target}. Nada mais foi enviado.", + "ui.sent_to_network_folder": "Enviado para {target}: {path}", + "ui.network_folder_send_failed": "Não foi possível enviar para {target}: {error}. O arquivo está salvo em {path}", + "ui.network_folders": "Pastas de rede", + "ui.network_folders_none": "Nenhuma ainda. Adicione uma pasta que um fatiador em outro computador lê; ela aparece no topo da lista de Enviar ao fatiador.", + "ui.network_folder_edit": "Editar", + "ui.network_folder_remove": "Remover", + "ui.network_folder_add_button": "Adicionar pasta de rede…" }, "vi": { "cmd.file_slicers_add_remote": "Thêm thư mục mạng", "cmd.file_slicers_remove_remote": "Xóa thư mục mạng", - "cmd.file_slicers_test": "Kiểm tra thư mục mạng" + "cmd.file_slicers_test": "Kiểm tra thư mục mạng", + "ui.mesh_format_stl_binary": "STL (nhị phân)", + "ui.mesh_format_stl_ascii": "STL (ASCII)", + "ui.network_folder_row": "Thư mục mạng…", + "ui.network_folder_tip": "Thêm một thư mục mà phần mềm cắt lớp trên máy tính khác đọc, chẳng hạn thư mục chia sẻ SMB hoặc NFS đã gắn kết", + "ui.network_folder_delete_tip": "{folder}\nNhấn Delete để xóa khỏi danh sách", + "ui.network_folder_title": "Thêm thư mục mạng", + "ui.network_folder_edit_title": "Sửa thư mục mạng", + "ui.network_folder_note": "Gửi sang phần mềm cắt lớp sẽ sao chép tệp vào thư mục này và không khởi động chương trình nào. Hãy chọn một thư mục chia sẻ đã gắn kết trên máy tính này, chẳng hạn thư mục chia sẻ SMB hoặc NFS mà phần mềm cắt lớp trên máy chủ của bạn đọc. Tệp đã có ở đó sẽ không bao giờ bị thay thế.", + "ui.network_folder_name": "Tên", + "ui.network_folder_name_hint": "Orca trên máy chủ", + "ui.network_folder_folder": "Thư mục", + "ui.network_folder_folder_hint": "/mnt/printer-share", + "ui.network_folder_browse": "Duyệt…", + "ui.network_folder_test": "Kiểm tra", + "ui.network_folder_testing": "Đang ghi tệp kiểm tra…", + "ui.network_folder_test_ok": "Có thể ghi tệp vào đó.", + "ui.network_folder_test_stopped": "Quá trình kiểm tra dừng đột ngột.", + "ui.network_folder_name_taken": "Đã có thư mục mạng mang tên này.", + "ui.network_folder_add": "Thêm", + "ui.network_folder_save": "Lưu", + "ui.network_folder_added": "Đã lưu thư mục mạng {name}: {folder}", + "ui.network_folder_sending": "Đang sao chép sang {target}…", + "ui.network_folder_still_sending": "Vẫn đang sao chép sang {target}. Chưa có dữ liệu nào khác được gửi.", + "ui.sent_to_network_folder": "Đã gửi sang {target}: {path}", + "ui.network_folder_send_failed": "Không thể gửi sang {target}: {error}. Tệp đã được lưu tại {path}", + "ui.network_folders": "Thư mục mạng", + "ui.network_folders_none": "Chưa có thư mục nào. Hãy thêm một thư mục mà phần mềm cắt lớp trên máy tính khác đọc; thư mục đó sẽ xuất hiện ở đầu danh sách Gửi sang phần mềm cắt lớp.", + "ui.network_folder_edit": "Sửa", + "ui.network_folder_remove": "Xóa", + "ui.network_folder_add_button": "Thêm thư mục mạng…" }, "zh": { "cmd.file_slicers_add_remote": "添加网络文件夹", "cmd.file_slicers_remove_remote": "移除网络文件夹", - "cmd.file_slicers_test": "测试网络文件夹" + "cmd.file_slicers_test": "测试网络文件夹", + "ui.mesh_format_stl_binary": "STL(二进制)", + "ui.mesh_format_stl_ascii": "STL(ASCII)", + "ui.network_folder_row": "网络文件夹…", + "ui.network_folder_tip": "添加另一台计算机上的切片软件读取的文件夹,例如已挂载的 SMB 或 NFS 共享", + "ui.network_folder_delete_tip": "{folder}\n按 Delete 键从列表中移除", + "ui.network_folder_title": "添加网络文件夹", + "ui.network_folder_edit_title": "编辑网络文件夹", + "ui.network_folder_note": "“发送到切片软件”会将文件复制到此文件夹,不会启动任何程序。请选择已挂载到本机的共享文件夹,例如服务器上的切片软件读取的 SMB 或 NFS 共享。已有的文件永远不会被替换。", + "ui.network_folder_name": "名称", + "ui.network_folder_name_hint": "服务器上的 Orca", + "ui.network_folder_folder": "文件夹", + "ui.network_folder_folder_hint": "/mnt/printer-share", + "ui.network_folder_browse": "浏览…", + "ui.network_folder_test": "测试", + "ui.network_folder_testing": "正在写入测试文件…", + "ui.network_folder_test_ok": "可以在此处写入文件。", + "ui.network_folder_test_stopped": "测试意外停止。", + "ui.network_folder_name_taken": "已有同名的网络文件夹。", + "ui.network_folder_add": "添加", + "ui.network_folder_save": "保存", + "ui.network_folder_added": "已保存网络文件夹 {name}:{folder}", + "ui.network_folder_sending": "正在复制到 {target}…", + "ui.network_folder_still_sending": "仍在复制到 {target}。未发送其他内容。", + "ui.sent_to_network_folder": "已发送到 {target}:{path}", + "ui.network_folder_send_failed": "无法发送到 {target}:{error}。文件已保存在 {path}", + "ui.network_folders": "网络文件夹", + "ui.network_folders_none": "暂无。添加另一台计算机上的切片软件读取的文件夹后,它会显示在“发送到切片软件”列表的顶部。", + "ui.network_folder_edit": "编辑", + "ui.network_folder_remove": "移除", + "ui.network_folder_add_button": "添加网络文件夹…" } } diff --git a/crates/ui-egui/src/control_job.rs b/crates/ui-egui/src/control_job.rs index a34fe2e4884..0de700e0569 100644 --- a/crates/ui-egui/src/control_job.rs +++ b/crates/ui-egui/src/control_job.rs @@ -87,6 +87,8 @@ const READ_ON_A_COPY: &[&str] = &[ /// Exports and readings computing at once; more run here. const MAX_ANSWERING: usize = 4; +/// At most this many sends to network folders wait for a worker; more are refused in words. +const MAX_SENDS_WAITING: usize = 64; /// How often a design change is computed again because the design changed under it before it /// runs here anyway. @@ -131,6 +133,22 @@ fn reading(req: &ControlRequest) -> Option<(&'static str, Value)> { } } +/// Commands that can send to a network folder (#2304). +const SEND_TO_A_FOLDER: &[&str] = &["file.save_mesh", "file.send_to_slicer"]; + +/// A request that sends to one of the user's network folders: the command and its parameters. A +/// copy to a slow share takes seconds, and the window would answer nothing meanwhile. +fn sending_to_a_network_folder(app: &crate::SolveApp, req: &ControlRequest) -> Option<(&'static str, Value)> { + if !matches!(req.method.as_str(), "engine.execute" | "command") { + return None; + } + let (command, params) = executed(&req.params)?; + let id = spec_id(command).filter(|id| SEND_TO_A_FOLDER.contains(id))?; + let slicer = params.get("slicer").and_then(Value::as_str)?; + solidcraft_engine::remote_slicers::resolve(&app.preferences.network_folders, slicer)?; + Some((id, params)) +} + /// Requests that change the design: they wait while one computes. pub(crate) fn changes_the_design(method: &str) -> bool { matches!(method, "engine.execute" | "command" | "engine.script" | "engine.batch" | "document.import" | "document.saved") @@ -182,6 +200,19 @@ impl ControlJob { } } +/// A command to run on a copy of the session, taken when it was asked for. A send to a network +/// folder that waits for a worker is one: it sends the design as it was then. +pub(crate) struct OnACopy { + req: ControlRequest, + /// The command, as the toolbar names it. + label: String, + /// When it was asked for (ms). + asked: f64, + scope: Option, + /// The command on the copy, and its reply. + run: Box Option + Send>, +} + fn label(app: &SolveApp, command: &str) -> String { let language = solidcraft_ui_text::Locale::for_language(&app.preferences.language); language.label(solidcraft_engine::find_command(command).map_or(command, |c| c.label)).to_string() @@ -399,6 +430,27 @@ impl SolveApp { { return self.answer_on_a_copy(req, id, params); } + // Sending to a network folder: on a copy too, whatever the preference, so the window + // keeps answering while the file is copied (#2304). With every worker busy it waits for + // one, never running here: a slow share would hold the window up. + if let Some((id, params)) = sending_to_a_network_folder(self, &req) { + let now = self.control_answering.len() < MAX_ANSWERING && self.control_sends_waiting.is_empty(); + if !now && self.control_sends_waiting.len() >= MAX_SENDS_WAITING { + let _ = req.reply.send(json!({"ok": false, "error": "too many sends to network folders are waiting; try again"})); + return None; + } + // The copy is taken now: a send that waits still sends the design as it is now, not + // an edit made meanwhile or another tab's design. + let work = match self.send_on_a_copy(req, id, params) { + Ok(work) => work, + Err(req) => return Some(req), + }; + if now { + return self.start_on_a_copy(work).err(); + } + self.control_sends_waiting.push_back(work); + return None; + } if !self.preferences.agent_off_thread { return Some(req); } @@ -428,10 +480,19 @@ impl SolveApp { /// there: at once when it is done within the app's wait, otherwise once it is in. `None`: it /// is taken care of; `Some`: it runs here (no threads). fn answer_on_a_copy(&mut self, req: ControlRequest, id: &'static str, params: Value) -> Option { - let Ok(scope) = crate::control::request_scope(self, &req.params) else { return Some(req) }; + match self.on_a_copy(req, id, params) { + Ok(work) => self.start_on_a_copy(work).err(), + Err(req) => Some(req), + } + } + + /// Command `id` on a copy of the session as it is now, with the request's folder scope and + /// level; the request back when it can't run on a copy. + fn on_a_copy(&self, req: ControlRequest, id: &'static str, params: Value) -> Result { + let Ok(scope) = crate::control::request_scope(self, &req.params) else { return Err(req) }; // The request's own level (#9184) checks it on the copy, and the reply says so, as // `control::handle` does; a word that is no level is refused there. - let Ok(level) = crate::control::request_param_check(&req.method, &req.params) else { return Some(req) }; + let Ok(level) = crate::control::request_param_check(&req.method, &req.params) else { return Err(req) }; let mut copy = self.session.scratch(); if let Some(level) = level { copy.param_check = level; @@ -439,7 +500,7 @@ impl SolveApp { // The copy has no history and no file (#9624): an inspection reports the design's own. let s = &self.session; let own = (id == "document.inspect").then(|| (s.undo.len(), s.redo.len(), s.path.clone())); - let rx = spawn(scope, move || { + let run = Box::new(move || { let mut reply = match copy.execute(id, ¶ms) { Ok(mut v) => { if let (Some((undo, redo, path)), Some(o)) = (own, v.as_object_mut()) { @@ -456,13 +517,26 @@ impl SolveApp { } Some(reply) }); - let Some(rx) = rx else { return Some(req) }; - let job = ControlJob { label: label(self, id), req, work: Work::Answer, done: rx, started: crate::now_ms(), steps: None }; + Ok(OnACopy { label: label(self, id), asked: crate::now_ms(), req, scope, run }) + } + + /// Start `work` on a worker; the request back when no worker could start. + fn start_on_a_copy(&mut self, work: OnACopy) -> Result<(), ControlRequest> { + let OnACopy { req, label, asked, scope, run } = work; + let Some(rx) = spawn(scope, run) else { return Err(req) }; + let job = ControlJob { label, req, work: Work::Answer, done: rx, started: asked, steps: None }; match within_wait(self, &job.done) { Some(reply) => self.answered(job, reply), None => self.control_answering.push(job), } - None + Ok(()) + } + + /// A send to a network folder, on a copy that takes the user's folders as they are now; the + /// request back when it can't run there. + fn send_on_a_copy(&mut self, req: ControlRequest, id: &'static str, params: Value) -> Result { + self.session.network_folders = solidcraft_engine::remote_slicers::sanitized(&self.preferences.network_folders); + self.on_a_copy(req, id, params) } /// An export's or a reading's reply, from its copy, with the echo an export leaves when it @@ -472,7 +546,9 @@ impl SolveApp { return; } let reply = reply.unwrap_or_else(|| json!({"ok": false, "error": format!("`{}` ended without a reply", job.label)})); - let export = executed(&job.req.params).and_then(|(command, _)| spec_id(command)).is_some_and(|id| ANSWERED_ON_A_COPY.contains(&id)); + let export = executed(&job.req.params) + .and_then(|(command, _)| spec_id(command)) + .is_some_and(|id| ANSWERED_ON_A_COPY.contains(&id) || SEND_TO_A_FOLDER.contains(&id)); if reply["ok"] == true && export { let language = solidcraft_ui_text::Locale::for_language(&self.preferences.language); self.session.echo(language.format("ui.command_done", &[("command", job.label.as_str())])); @@ -499,6 +575,18 @@ impl SolveApp { } ctx.request_repaint_after(std::time::Duration::from_millis(100)); } + // Sends that waited for a worker, in order, as workers come free, each on the copy taken + // when it was asked for; never here, where a slow share would hold the window up. + while self.control_answering.len() < MAX_ANSWERING + && let Some(work) = self.control_sends_waiting.pop_front() + { + if work.req.refuse_cancelled_chat() { + continue; + } + if let Err(req) = self.start_on_a_copy(work) { + let _ = req.reply.send(json!({"ok": false, "error": "no worker could start the send to the network folder; try again"})); + } + } let Some(job) = &self.control_job else { return }; if job.req.refuse_cancelled_chat() { self.control_job = None; diff --git a/crates/ui-egui/src/dialogs_save_mesh.rs b/crates/ui-egui/src/dialogs_save_mesh.rs index cf92729131b..ea38be70c18 100644 --- a/crates/ui-egui/src/dialogs_save_mesh.rs +++ b/crates/ui-egui/src/dialogs_save_mesh.rs @@ -9,10 +9,14 @@ //! once, so it undoes like any other. //! //! Every place that saves a mesh opens this dialog: File › Export STL / Export 3MF, the Mesh tab, and the -//! Save As Mesh item of the body menus. The slicer list (Send to Slicer only) holds the programs the user added (kept -//! between runs, newest first), then the slicers found on this machine, then "Custom…", which asks -//! for a program and adds it at the top; "Custom…" itself is never the selection. Pressing Delete -//! over a program the user added removes it. +//! Save As Mesh item of the body menus. The slicer list (Send to Slicer only) holds the network +//! folders the user added (#2304), the programs the user added (kept between runs, newest first), +//! then the slicers found on this machine, then "Custom…", which asks for a program and adds it at +//! the top, and "Network folder…", which asks for a folder and a name; neither is ever the +//! selection. Pressing Delete over a network folder or a program the user added removes it. +//! +//! Send to Slicer has Format and Quality rows of its own (3MF, binary or ASCII STL; standard, fine +//! or finest), remembered apart from Save as Mesh's. Their first choices are what it always sent. use crate::selection::SelectionExt as _; use crate::ui_kit::BackingTooltipExt as _; @@ -34,6 +38,10 @@ use solidcraft_theme::Tokens; const FORMATS: [(&str, &str, &str); 3] = [("STL", "stl", "stl"), ("3MF", "3mf", "3mf"), ("3MF with face tags", "3mf-tagged", "3mf")]; /// The list key of the EasyPrint row (no slicer has it: ids are words, programs are paths). const EASYPRINT: &str = "easyprint"; +/// Send to Slicer's formats: the label, `file.send_to_slicer`'s `format` and `ascii`, and the name +/// the preference keeps. 3MF first: what Send to Slicer always sent. +const SEND_FORMATS: [(&str, &str, bool, &str); 3] = + [("3MF", "3mf", false, "3mf"), ("ui.mesh_format_stl_binary", "stl", false, "stl"), ("ui.mesh_format_stl_ascii", "stl", true, "stl-ascii")]; /// How closely the mesh follows curved faces (#4747): the label and `file.save_mesh`'s `quality`. const QUALITIES: [(&str, &str); 3] = [("Standard", "standard"), ("Fine", "fine"), ("Finest", "finest")]; /// Edge of a slicer's icon in the list. @@ -45,9 +53,11 @@ const MAX_CUSTOM: usize = 24; #[derive(Clone, Debug, PartialEq)] pub struct SaveMesh { format: usize, + /// Send to Slicer's format: an index into [`SEND_FORMATS`]. + send_format: usize, /// Send to Slicer: only the bodies and the slicer are asked. open: bool, - /// Index into [`QUALITIES`] (Save As Mesh; Send to Slicer has no quality row). + /// Index into [`QUALITIES`]; each of the two dialogs remembers its own. quality: usize, /// The chosen slicer: an installed one's id, or the path of one the user added. slicer: String, @@ -136,8 +146,10 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { _ if open => p.send_slicer.clone(), _ => String::new(), }; - let quality = QUALITIES.iter().position(|q| q.1 == p.save_mesh_quality).unwrap_or(0); - let kind = Kind::SaveMesh(SaveMesh { format, quality, open, slicer, stale: true, shown: None }); + let remembered = if open { &p.send_quality } else { &p.save_mesh_quality }; + let quality = QUALITIES.iter().position(|q| q.1 == *remembered).unwrap_or(0); + let send_format = SEND_FORMATS.iter().position(|f| f.3 == p.send_format).unwrap_or(0); + let kind = Kind::SaveMesh(SaveMesh { format, send_format, quality, open, slicer, stale: true, shown: None }); let mut inputs = vec![SelInput::new("Bodies", BODIES, true)]; // The design's only body is the one to export (#13098); with more, nothing says which. let only = body_picks(app, false); @@ -193,10 +205,19 @@ fn send_to_slicer(app: &mut SolveApp, params: Value) { app.set_status(line, false); return; } + if let Some(target) = crate::network_folder_ui::sending(app) { + let line = solidcraft_ui_text::format("ui.network_folder_still_sending", &[("target", target)]); + app.set_status(line, false); + return; + } let mut params = params; params["single_instance"] = json!(app.preferences.slicer_single_instance); params["wait"] = json!("return"); let Ok(result) = app.run("file.send_to_slicer", params.clone()) else { return }; + // A network folder: the copy goes on in the background, and the status line follows it. + if crate::network_folder_ui::follow(app, &result) { + return; + } if result.get("starting").is_none() { return report(app, &result); } @@ -225,6 +246,7 @@ fn begin_wait(app: &mut SolveApp, params: Value, result: &Value) { /// Per frame: when the slicer being waited for is ready, send the file; when the wait ran out, say so. pub fn tick_wait(app: &mut SolveApp, ctx: &egui::Context) { use std::sync::mpsc::TryRecvError; + crate::network_folder_ui::tick(app, ctx); let Some(wait) = app.slicer_wait.as_ref() else { return }; let ready = match wait.done.try_recv() { Err(TryRecvError::Empty) => return ctx.request_repaint_after(std::time::Duration::from_millis(200)), @@ -398,11 +420,15 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh, inputs: &mu app.slicer_menu.refresh(&app.preferences.custom_slicers); let entries = app.slicer_menu.entries(); let easyprint = crate::easyprint_ui::available(app); + let remotes = network_folders(app); k.slicer = if easyprint && k.slicer == EASYPRINT { EASYPRINT.into() + } else if remotes.iter().any(|t| t.id() == k.slicer) { + k.slicer.clone() } else { app.slicer_menu .key_for(&k.slicer) + .or_else(|| remotes.first().map(|t| t.id())) .or_else(|| entries.first().map(|e| e.key.clone())) .or_else(|| easyprint.then(|| EASYPRINT.to_string())) .unwrap_or_default() @@ -419,31 +445,81 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh, inputs: &mu let choosing = app.file_picker_busy(); ui.add_enabled_ui(!choosing, |ui| slicer_combo(app, ui, k)); }); + // EasyPrint takes its own file; the slicers and network folders take these. + if k.slicer != EASYPRINT { + choice_row(ui, "Format", "sm_send_format", &mut k.send_format, &SEND_FORMATS.map(|f| f.0)); + choice_row(ui, "Quality", "sm_send_quality", &mut k.quality, &QUALITIES.map(|q| q.0)); + } false } +/// The network folders the list offers: the user's, where the host can reach folders. +fn network_folders(app: &SolveApp) -> Vec { + if crate::network_folder_ui::available(app) { app.preferences.network_folders.clone() } else { Vec::new() } +} + +/// Make `key` the dialog's slicer; with `instead`, only when that one is chosen now. +pub(crate) fn choose(k: &mut SaveMesh, key: &str, instead: Option<&str>) { + if instead.is_none_or(|old| k.slicer == old) { + k.slicer = key.to_string(); + } +} + +/// A network folder row, or the selected one's icon in the closed list. +fn paint_network_icon(ui: &egui::Ui, rect: egui::Rect) { + crate::icons::paint_icon(ui.painter(), rect, "network_folder", 1.0); +} + fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) { let entries = app.slicer_menu.entries(); let ctx = ui.ctx().clone(); let current = entries.iter().find(|e| e.key == k.slicer); + let remotes = network_folders(app); + let current_remote = remotes.iter().find(|t| t.id() == k.slicer); let pad = "\u{2003}\u{2003}"; let easyprint = crate::easyprint_ui::available(app); let easyprint_label = solidcraft_ui_text::tr("ui.easyprint_row"); - let text = match current { - Some(e) => format!("{pad}{}", e.slicer.name), - None if easyprint && k.slicer == EASYPRINT => format!("{pad}{easyprint_label}"), - None => solidcraft_ui_text::tr_label("No slicer found").to_string(), + let text = match (current_remote, current) { + (Some(t), _) => format!("{pad}{}", t.name), + (None, Some(e)) => format!("{pad}{}", e.slicer.name), + (None, None) if easyprint && k.slicer == EASYPRINT => format!("{pad}{easyprint_label}"), + (None, None) => solidcraft_ui_text::tr_label("No slicer found").to_string(), }; + let (programs, network) = (app.services.pick_program.is_some(), crate::network_folder_ui::available(app)); let mut pick_custom = false; + let mut pick_network = false; let mut delete: Option = None; + let mut delete_remote: Option = None; let mut chosen: Option = None; - let name = current.map(|e| e.slicer.name.clone()); + let name = current_remote.map(|t| t.name.clone()).or_else(|| current.map(|e| e.slicer.name.clone())); // A long name ends in … instead of wrapping onto a second line; the full one is in the tooltip. let wrap = ui.style().wrap_mode; ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); let r = crate::ui_kit::dropdown_menu(ui, "sm_slicer", &text, |ui| { let frame = ctx.cumulative_frame_nr(); ctx.data_mut(|d| d.insert_temp(egui::Id::unique("sc_slicer_popup"), frame)); + // The network folders first, as the programs the user added come before the ones found. + for t in &remotes { + let key = t.id(); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + if resp.hovered() || key == k.slicer { + let fill = if resp.hovered() { Tokens::get().hover } else { Tokens::get().selected_bg }; + ui.painter().rect_filled(rect, Tokens::get().radius_sm / 2, fill); + } + paint_network_icon(ui, egui::Rect::from_min_size(rect.left_center() + vec2(3.0, -ICON / 2.0), vec2(ICON, ICON))); + let text = fitted(ui, &t.name, rect.width() - (ICON + 9.0) - 6.0, Tokens::get().text); + ui.painter().galley(rect.left_center() + vec2(ICON + 9.0, -text.size().y / 2.0), text, Tokens::get().text); + crate::scenario::publish_handle(&format!("dialog:Slicer:{}", t.name), rect.center()); + let hint = solidcraft_ui_text::format("ui.network_folder_delete_tip", &[("folder", t.folder())]); + resp.clone().backing_on_hover_text(format!("{}\n{hint}", t.name)); + if resp.hovered() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete)) { + delete_remote = Some(t.name.clone()); + } + if resp.clicked() { + chosen = Some(key); + ui.close(); + } + } for e in &entries { let tex = icon(&mut app.slicer_menu, &ctx, e); let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); @@ -485,43 +561,67 @@ fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) { ui.close(); } } - if !entries.is_empty() || easyprint { + if !entries.is_empty() || !remotes.is_empty() || easyprint { ui.separator(); } - // A browser has no program to add. - if app.services.pick_program.is_none() { - return; - } - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); - if resp.hovered() { - ui.painter().rect_filled(rect, Tokens::get().radius_sm / 2, Tokens::get().hover); + // A browser has no program to add, nor a folder. + let add_row = |ui: &mut egui::Ui, label: &str, tip: &str, handle: &str| { + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, Tokens::get().radius_sm / 2, Tokens::get().hover); + } + ui.painter().text( + rect.left_center() + vec2(ICON + 9.0, 0.0), + egui::Align2::LEFT_CENTER, + label, + egui::FontId::proportional(solidcraft_theme::Tokens::get().font_button), + Tokens::get().text, + ); + crate::scenario::publish_handle(handle, rect.center()); + let clicked = resp.backing_on_hover_text(tip).clicked(); + if clicked { + ui.close(); + } + clicked + }; + if programs { + pick_custom = + add_row(ui, solidcraft_ui_text::tr_label("Custom…"), solidcraft_ui_text::tr("ui.custom_program_tip"), "dialog:Slicer:Custom"); } - ui.painter().text( - rect.left_center() + vec2(ICON + 9.0, 0.0), - egui::Align2::LEFT_CENTER, - solidcraft_ui_text::tr_label("Custom…"), - egui::FontId::proportional(solidcraft_theme::Tokens::get().font_button), - Tokens::get().text, - ); - crate::scenario::publish_handle("dialog:Slicer:Custom", rect.center()); - if resp.backing_on_hover_text(solidcraft_ui_text::tr("ui.custom_program_tip")).clicked() { - pick_custom = true; - ui.close(); + if network { + pick_network = add_row( + ui, + solidcraft_ui_text::tr("ui.network_folder_row"), + solidcraft_ui_text::tr("ui.network_folder_tip"), + "dialog:Slicer:NetworkFolder", + ); } }); ui.style_mut().wrap_mode = wrap; if let Some(name) = name { r.clone().backing_on_hover_text(name); } - if let Some(e) = current { + let at = egui::Rect::from_min_size(r.rect.left_center() + vec2(ui.spacing().button_padding.x + 1.0, -ICON / 2.0), vec2(ICON, ICON)); + if current_remote.is_some() { + paint_network_icon(ui, at); + } else if let Some(e) = current { let tex = icon(&mut app.slicer_menu, &ctx, e); - let rect = r.rect; - let at = egui::Rect::from_min_size(rect.left_center() + vec2(ui.spacing().button_padding.x + 1.0, -ICON / 2.0), vec2(ICON, ICON)); paint_icon(ui, at, tex, &e.slicer.name); } if let Some(key) = chosen { k.slicer = key; } + if let Some(name) = delete_remote { + let key = format!("{}{name}", solidcraft_engine::remote_slicers::ID_PREFIX); + crate::network_folder_ui::remove(app, &name); + if k.slicer == key { + let first = network_folders(app).first().map(|t| t.id()); + k.slicer = first.or_else(|| app.slicer_menu.entries().first().map(|e| e.key.clone())).unwrap_or_default(); + } + } + if pick_network { + crate::network_folder_ui::open_new(app, true); + } if let Some(key) = delete { app.preferences.custom_slicers.retain(|p| *p != key); app.slicer_menu.set_custom(&app.preferences.custom_slicers); @@ -553,7 +653,7 @@ fn add_custom(app: &mut SolveApp, path: &str) -> Result<(), String> { pub fn commands(k: &SaveMesh, inputs: &[SelInput]) -> Result, String> { let format = FORMATS.get(k.format).map_or("stl", |f| f.1); let mut p = json!({ "format": format }); - // Standard is the command's own default, so it is left out. Sending has no quality row. + // Standard is the command's own default, so it is left out. Sending sets its own below. if let Some((_, quality)) = QUALITIES.get(k.quality).filter(|_| k.quality > 0 && !k.open) { p["quality"] = json!(quality); } @@ -570,6 +670,15 @@ pub fn commands(k: &SaveMesh, inputs: &[SelInput]) -> Result 0) { + p["quality"] = json!(quality); + } p["slicer"] = json!(k.slicer); return Ok(vec![("file.send_to_slicer".into(), p)]); } @@ -600,6 +709,8 @@ pub fn run(app: &mut SolveApp, k: &SaveMesh, inputs: &[SelInput]) -> Result<(), if k.slicer == EASYPRINT { crate::easyprint_ui::request(app, params); } else { + app.preferences.send_format = SEND_FORMATS.get(k.send_format).map_or("3mf", |f| f.3).into(); + app.preferences.send_quality = QUALITIES.get(k.quality).map_or("standard", |q| q.1).into(); send_to_slicer(app, params); } return Ok(()); @@ -629,6 +740,16 @@ fn save(app: &mut SolveApp, mut params: Value, path: &str) { /// The status line after a save or a send. fn report(app: &mut SolveApp, result: &Value) { let path = result.get("path").and_then(Value::as_str).unwrap_or_default(); + // A network folder: where the copy went (no program was started, nothing is replaced). + if result.get("remote").and_then(Value::as_bool) == Some(true) { + let target = result.get("target").and_then(Value::as_str).unwrap_or_default(); + match (result.get("slicer_error").and_then(Value::as_str), result.get("sent_to").and_then(Value::as_str)) { + (Some(e), _) => app.set_status(e.to_string(), true), + (None, Some(to)) => app.set_status(solidcraft_ui_text::format("ui.sent_to_network_folder", &[("target", target), ("path", to)]), false), + (None, None) => app.set_status(solidcraft_ui_text::format("ui.saved_to", &[("path", path)]), false), + } + return; + } match result.get("slicer_error").and_then(Value::as_str) { Some(e) => app.set_status(e.to_string(), true), None => match result.get("slicer").and_then(Value::as_str) { @@ -944,8 +1065,8 @@ mod tests { } #[test] - fn send_to_slicer_asks_for_bodies_and_a_slicer_but_not_a_format() { - let k = SaveMesh { format: 0, quality: 0, open: true, slicer: "prusa".into(), stale: false, shown: None }; + fn send_to_slicer_asks_for_bodies_a_slicer_a_format_and_a_quality() { + let k = SaveMesh { format: 0, send_format: 0, quality: 0, open: true, slicer: "prusa".into(), stale: false, shown: None }; let mut input = SelInput::new("Bodies", BODIES, true); assert!(commands(&k, std::slice::from_ref(&input)).is_err()); input.items = vec![Sel::Body { name: "Part".into() }]; @@ -957,18 +1078,249 @@ mod tests { assert_eq!((id.as_str(), p["format"].as_str(), p.get("slicer")), ("file.save_mesh", Some("3mf-tagged"), None)); assert_eq!(button(&save), "Save"); assert_eq!(button(&k), "Send"); + // The Format and Quality rows (#2304): ASCII STL at Fine is said; 3MF and Standard are the defaults. + let ascii_fine = SaveMesh { send_format: 2, quality: 1, ..k.clone() }; + let (_, p) = commands(&ascii_fine, std::slice::from_ref(&input)).unwrap().remove(0); + assert_eq!(p, json!({"slicer": "prusa", "bodies": ["Part"], "format": "stl", "ascii": true, "quality": "fine"})); + let (_, p) = commands(&SaveMesh { send_format: 1, ..k.clone() }, std::slice::from_ref(&input)).unwrap().remove(0); + assert_eq!((p["format"].as_str(), p.get("ascii")), (Some("stl"), None), "binary STL"); + // EasyPrint takes its own 3MF whatever the rows say. + let (id, p) = commands(&SaveMesh { slicer: EASYPRINT.into(), ..ascii_fine }, std::slice::from_ref(&input)).unwrap().remove(0); + assert_eq!((id.as_str(), p["format"].as_str(), p.get("quality"), p.get("ascii")), ("file.open_in_easyprint", Some("3mf"), None, None)); assert!(commands(&SaveMesh { slicer: String::new(), ..k }, &[input]).is_err()); } #[test] - fn a_remembered_quality_goes_to_save_but_not_to_send() { + fn send_to_slicer_starts_as_it_always_sent_and_each_dialog_remembers_its_own_choices() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let opened = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) { + Some(Kind::SaveMesh(k)) => k.clone(), + _ => panic!("no dialog"), + }; + app.services.pick_program = Some(Box::new(|| Box::pin(async { None }))); + app.start("file.send_to_slicer"); + let k = opened(&app); + // Changes a default: no. A new user sends a Standard 3MF, as before the rows existed. + assert_eq!((SEND_FORMATS[k.send_format].3, QUALITIES[k.quality].1), ("3mf", "standard")); + app.dialog = None; + app.preferences.send_format = "stl-ascii".into(); + app.preferences.send_quality = "fine".into(); + app.preferences.save_mesh_quality = "finest".into(); + app.start("file.send_to_slicer"); + let k = opened(&app); + assert_eq!((SEND_FORMATS[k.send_format].3, QUALITIES[k.quality].1), ("stl-ascii", "fine")); + app.dialog = None; + app.start("file.save_mesh"); + assert_eq!(QUALITIES[opened(&app).quality].1, "finest", "Save as Mesh keeps its own quality"); + // Something unreadable in the settings file starts from the defaults. + app.dialog = None; + app.preferences.send_format = "obj".into(); + app.preferences.send_quality = "ultra".into(); + app.start("file.send_to_slicer"); + let k = opened(&app); + assert_eq!((k.send_format, k.quality), (0, 0)); + } + + /// A share folder for a test, removed when it ends. + struct Share(std::path::PathBuf); + + impl Share { + fn new(tag: &str) -> Share { + let dir = std::env::temp_dir().join(format!("solidcraft-ui-network-folder-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Share(dir) + } + fn path(&self) -> String { + self.0.to_string_lossy().into_owned() + } + } + + impl Drop for Share { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + /// Frames until the status line holds `text`. + fn until_status(h: &mut crate::scenario::Harness, text: &str) -> String { + for _ in 0..300 { + if let Some((line, _, _)) = &h.app.status + && line.contains(text) + { + return line.clone(); + } + h.frame(); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the status line never said {text:?}: {:?}", h.app.status); + } + + #[test] + fn a_network_folder_is_added_in_its_window_listed_first_and_sent_to_without_a_program() { + let share = Share::new("window"); + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Part"})).unwrap(); + h.app.services.pick_program = Some(Box::new(|| Box::pin(async { None }))); + let folder = share.path(); + h.app.services.pick_folder = Some(Box::new(move || { + let folder = folder.clone(); + Box::pin(async move { Some(folder) }) + })); + h.app.preferences.send_format = "stl".into(); + h.app.start("file.send_to_slicer"); + h.app.dialog.as_mut().unwrap().inputs[0].items = vec![Sel::Body { name: "Part".into() }]; + h.settle(); + // "Network folder…" in the list opens the window; Browse fills the folder, Test writes there. + h.step(&json!({"widget": "Slicer", "near": "Slicer"})).unwrap(); + h.settle(); + h.step(&json!({"click": {"handle": "dialog:Slicer:NetworkFolder"}})).unwrap(); + h.settle(); + assert!(h.widget("Add Network Folder").is_some(), "the window opened from the list"); + h.step(&json!({"click": {"handle": "dialog:NetworkFolder:Browse"}})).unwrap(); + h.settle(); + h.step(&json!({"widget": "Name", "near": "Name"})).unwrap(); + h.step(&json!({"text": "Orca on homelab"})).unwrap(); + h.settle(); + h.step(&json!({"widget": "Test"})).unwrap(); + for _ in 0..100 { + h.frame(); + if h.widget("A file can be written there.").is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(h.widget("A file can be written there.").is_some(), "the test result is shown"); + assert_eq!(std::fs::read_dir(&share.0).unwrap().count(), 0, "the test file is deleted"); + h.step(&json!({"widget": "Add"})).unwrap(); + h.settle(); + assert_eq!(h.app.preferences.network_folders.len(), 1, "kept in the preferences"); + assert_eq!( + (h.app.preferences.network_folders[0].name.as_str(), h.app.preferences.network_folders[0].folder()), + ("Orca on homelab", share.path().as_str()) + ); + let Some(Kind::SaveMesh(k)) = h.app.dialog.as_ref().map(|d| d.kind.clone()) else { panic!("Send to Slicer closed") }; + assert_eq!(k.slicer, "remote:Orca on homelab", "the folder just added is the choice"); + assert_eq!(network_folders(&h.app).first().map(|t| t.id()), Some(k.slicer.clone()), "listed first"); + // Send: a binary STL under the design and body's name; no program, the path in the status line. + let inputs = h.app.dialog.as_ref().unwrap().inputs.clone(); + run(&mut h.app, &k, &inputs).unwrap(); + let line = until_status(&mut h, "Sent to Orca on homelab"); + let sent = share.0.join("Untitled - Part.stl"); + assert!(line.contains(&sent.to_string_lossy().into_owned()), "{line}"); + assert!(!std::fs::read(&sent).unwrap().starts_with(b"PK")); + assert_eq!(h.app.preferences.send_slicer, "remote:Orca on homelab", "remembered"); + // Again: a number is added rather than replacing the file. + run(&mut h.app, &k, &inputs).unwrap(); + until_status(&mut h, "Untitled - Part (2).stl"); + // Delete over its row takes it out (the files sent there stay). + crate::network_folder_ui::remove(&mut h.app, "Orca on homelab"); + assert!(h.app.preferences.network_folders.is_empty() && sent.exists()); + } + + #[test] + fn a_network_folder_that_is_not_mounted_is_reported_and_nothing_is_made() { + let share = Share::new("gone"); + let gone = share.0.join("not-mounted"); + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Part"})).unwrap(); + h.app.services.pick_folder = Some(Box::new(|| Box::pin(async { None }))); + h.app.preferences.network_folders = vec![solidcraft_engine::remote_slicers::RemoteTarget::folder_target("NAS", &gone.to_string_lossy())]; + let k = SaveMesh { format: 0, send_format: 0, quality: 0, open: true, slicer: "remote:NAS".into(), stale: false, shown: None }; let mut input = SelInput::new("Bodies", BODIES, true); input.items = vec![Sel::Body { name: "Part".into() }]; - let k = SaveMesh { format: 0, quality: 2, open: true, slicer: "prusa".into(), stale: false, shown: None }; - let (_, sent) = commands(&k, std::slice::from_ref(&input)).unwrap().remove(0); - assert_eq!(sent.get("quality"), None, "sending has no quality row: the default applies"); - let (_, saved) = commands(&SaveMesh { open: false, ..k }, &[input]).unwrap().remove(0); - assert_eq!(saved["quality"], "finest"); + run(&mut h.app, &k, &[input]).unwrap(); + let line = until_status(&mut h, "mounted"); + assert!(matches!(&h.app.status, Some((_, _, true))), "an error: {line}"); + assert!(line.contains("NAS"), "{line}"); + assert!(!gone.exists(), "a missing folder is never made"); + } + + #[test] + fn network_folders_added_by_a_script_are_kept_in_the_preferences_and_across_restarts() { + let share = Share::new("script"); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.services.pick_folder = Some(Box::new(|| Box::pin(async { None }))); + app.run("file.slicers.add_remote", json!({"name": "Printer share", "folder": share.path()})).unwrap(); + assert!(app.dialog.is_none(), "no window for a script"); + assert_eq!(app.preferences.network_folders.len(), 1); + let listed = app.run("file.slicers", json!({})).unwrap(); + assert_eq!((listed["slicers"][0]["id"].as_str(), listed["slicers"][0]["remote"].as_bool()), (Some("remote:Printer share"), Some(true))); + let tested = app.run("file.slicers.test", json!({"name": "Printer share"})).unwrap(); + assert_eq!(tested["ok"], true); + // The next start reads them back from the settings file; the design never holds them. + let saved = app.prefs(); + assert!(!app.session.doc.to_json().contains(&share.path())); + let mut next = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + next.load_prefs(&saved); + assert_eq!(next.preferences.network_folders, app.preferences.network_folders); + assert_eq!(next.session.network_folders, app.preferences.network_folders); + next.run("file.slicers.remove_remote", json!({"name": "remote:printer share"})).unwrap(); + assert!(next.preferences.network_folders.is_empty()); + // A hand-edited settings file with a bad entry: it is left out, not a crash. + next.preferences.network_folders = vec![solidcraft_engine::remote_slicers::RemoteTarget::folder_target("", "relative")]; + let listed = next.run("file.slicers", json!({})).unwrap(); + assert!(listed["slicers"].as_array().unwrap().iter().all(|t| t["remote"].is_null())); + } + + /// Each step of `engine.script` runs through `SolveApp::run` (#12629), and a command id matches + /// in any case: a network folder added or removed either way is kept in the preferences, also + /// when a later step of the script failed. + #[test] + fn network_folders_added_by_engine_script_or_in_capitals_are_kept_in_the_preferences() { + let (first, second) = (Share::new("engine-script"), Share::new("capitals")); + let mut h = crate::scenario::Harness::new(); + h.app.services.pick_folder = Some(Box::new(|| Box::pin(async { None }))); + let add = json!({"command": "file.slicers.add_remote", "params": {"name": "Script share", "folder": first.path()}}); + let r = h.call("engine.script", json!({"commands": [add, {"command": "no.such_command"}]})); + assert_eq!(r["ok"], false, "the second step fails: {r}"); + assert_eq!(h.app.preferences.network_folders.len(), 1, "the first step's folder is kept"); + h.app.run("FILE.SLICERS.ADD_REMOTE", json!({"name": "Capitals", "folder": second.path()})).unwrap(); + let listed = h.app.run("file.slicers", json!({})).unwrap(); + let ids: Vec<_> = listed["slicers"].as_array().unwrap().iter().filter_map(|t| t["id"].as_str()).collect(); + assert!(ids.contains(&"remote:Script share") && ids.contains(&"remote:Capitals"), "{listed}"); + let r = h.call("engine.script", json!([{"command": "file.slicers.remove_remote", "params": {"name": "Script share"}}])); + assert_eq!(r["ok"], true, "{r}"); + let names: Vec<_> = h.app.preferences.network_folders.iter().map(|t| t.name.as_str()).collect(); + assert_eq!(names, ["Capitals"]); + } + + #[test] + fn network_folders_are_found_by_the_preferences_search() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.preferences.language = "en".into(); + h.app.services.pick_folder = Some(Box::new(|| Box::pin(async { None }))); + h.app.preferences.network_folders = vec![solidcraft_engine::remote_slicers::RemoteTarget::folder_target("Orca on homelab", "/mnt/prints")]; + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_GENERAL); + let row = "Orca on homelab \u{2014} /mnt/prints"; + // The rows have no labelled control: the block's label, a name or a folder finds them. + for query in ["network folder", "homelab", "/mnt/prints"] { + h.app.prefs_window.shell.filter = query.into(); + h.frames(4); + let body = crate::scenario::rect_of("prefs:page_body").unwrap(); + let at = h.widget(row).unwrap_or_else(|| panic!("{query} finds the network folder")); + assert!(body.contains(egui::pos2(at[0] as f32, at[1] as f32)), "{query}: the row is drawn in the results"); + assert!(h.widget(h.app.tr("prefs.search_empty")).is_none(), "{query} has a result"); + assert!(h.widget("Add network folder\u{2026}").is_some(), "{query}: the rows keep their buttons"); + // The section's heading goes above the block, never into its control column. + let label = h.widgets("Network folders").into_iter().find(|p| (p[1] - at[1]).abs() < 6.0 && p[0] < at[0]); + let label = label.unwrap_or_else(|| panic!("{query}: the block's label is on its first row")); + let heading = h.widget("FILES").unwrap_or_else(|| panic!("{query}: the section heading is shown")); + assert!(heading[1] < at[1] && heading[0] < label[0], "{query}: the heading is above the block: {heading:?} {label:?} {at:?}"); + } + h.app.prefs_window.shell.filter = "zebra stripes".into(); + h.frames(4); + assert!(h.widget(row).is_none(), "an unrelated search leaves the rows out"); + } + + #[test] + fn the_browser_offers_no_network_folder() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.preferences.network_folders = vec![solidcraft_engine::remote_slicers::RemoteTarget::folder_target("NAS", "/mnt/nas")]; + assert!(app.services.pick_folder.is_none()); + assert!(!crate::network_folder_ui::available(&app)); + assert!(network_folders(&app).is_empty(), "no folders where none can be written"); } #[test] diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs index 982f869a458..9162f6d3eb5 100644 --- a/crates/ui-egui/src/file_picker.rs +++ b/crates/ui-egui/src/file_picker.rs @@ -79,6 +79,15 @@ impl SolveApp { self.begin_picker(future, Box::new(complete)); } + /// Ask the host for a folder (Send to Slicer's network folder); none when it can't ask. + pub(crate) fn pick_folder(&mut self, complete: impl FnOnce(&mut SolveApp, Option) + 'static) { + if self.file_picker_busy() { + return; + } + let future = self.services.pick_folder.as_ref().map(|pick| pick()); + self.begin_picker(future, Box::new(complete)); + } + fn begin_picker(&mut self, future: Option, complete: Completion) { let Some(future) = future else { complete(self, None); diff --git a/crates/ui-egui/src/history_off_thread_tests.rs b/crates/ui-egui/src/history_off_thread_tests.rs index 0994c1b197a..a55c554a3ac 100644 --- a/crates/ui-egui/src/history_off_thread_tests.rs +++ b/crates/ui-egui/src/history_off_thread_tests.rs @@ -860,6 +860,87 @@ fn a_measure_reads_a_copy_off_the_window_thread_preference_or_not() { assert_eq!(h.app.session.log.len(), log, "a reading leaves no echo: {:?}", h.app.session.log); } +/// #2304: sending to a network folder over the control channel copies the file on a copy of the +/// design, preference or not: a copy to a slow share took seconds on the window thread, which +/// answered nothing meanwhile. The window answers `ui.*` while it sends, and the file arrives. +#[test] +fn a_send_to_a_network_folder_runs_off_the_window_thread_preference_or_not() { + let (mut h, tx) = agent_harness(); + h.app.preferences.agent_off_thread = false; + let share = std::env::temp_dir().join(format!("solidcraft-control-share-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&share); + std::fs::create_dir_all(&share).unwrap(); + let folder = solidcraft_engine::remote_slicers::RemoteTarget::folder_target("Share", &share.to_string_lossy()); + h.app.preferences.network_folders = vec![folder]; + let send = + ask(&tx, "engine.execute", json!({"command": "file.send_to_slicer", "params": {"slicer": "Share", "bodies": ["Body1"], "wait": "block"}})); + let view = ask(&tx, "ui.inspect", json!({})); + h.frames(1); + assert!(view.try_recv().is_ok_and(|v| v["ok"] == true), "ui.* answered meanwhile"); + let r = reply_to(&mut h, &send); + assert_eq!(r["ok"], true, "{r}"); + let sent = r["result"]["sent_to"].as_str().unwrap_or_default().to_string(); + assert!(std::path::Path::new(&sent).starts_with(&share) && std::fs::metadata(&sent).is_ok_and(|m| m.len() > 0), "{r}"); + assert!(h.app.control_answering.is_empty()); + let _ = std::fs::remove_dir_all(&share); +} + +/// #2304: with every worker busy, more sends to a network folder wait for one instead of running +/// on the window thread, and each still arrives, in order. +#[test] +fn sends_to_a_network_folder_wait_for_a_worker_when_all_are_busy() { + let (mut h, tx) = agent_harness(); + let share = std::env::temp_dir().join(format!("solidcraft-control-busy-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&share); + std::fs::create_dir_all(&share).unwrap(); + let folder = solidcraft_engine::remote_slicers::RemoteTarget::folder_target("Share", &share.to_string_lossy()); + h.app.preferences.network_folders = vec![folder]; + let sends: Vec<_> = (0..7) + .map(|_| ask(&tx, "engine.execute", json!({"command": "file.send_to_slicer", "params": {"slicer": "Share", "bodies": ["Body1"]}}))) + .collect(); + let view = ask(&tx, "ui.inspect", json!({})); + h.frames(1); + assert!(view.try_recv().is_ok_and(|v| v["ok"] == true), "ui.* answered meanwhile"); + assert!(h.app.control_answering.len() <= 4, "at most four workers: {}", h.app.control_answering.len()); + assert!(!h.app.control_sends_waiting.is_empty(), "the rest wait for a worker"); + for send in &sends { + let r = reply_to(&mut h, send); + assert_eq!(r["ok"], true, "{r}"); + } + assert_eq!(std::fs::read_dir(&share).unwrap().count(), 7, "every send arrived, none replaced"); + assert!(h.app.control_answering.is_empty() && h.app.control_sends_waiting.is_empty()); + let _ = std::fs::remove_dir_all(&share); +} + +/// #2304: a send to a network folder that waits for a worker sends the design as it was when it +/// was asked for. It took the design only once a worker came free, so an edit made meanwhile +/// (here, renaming the body it sends) changed what it sent, or made it fail. +#[test] +fn a_send_that_waits_for_a_worker_sends_the_design_as_it_was_asked_for() { + let (mut h, tx) = agent_harness(); + // The rename runs at once, behind the sends, while some of them still wait. + h.app.preferences.agent_off_thread = false; + let share = std::env::temp_dir().join(format!("solidcraft-control-asked-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&share); + std::fs::create_dir_all(&share).unwrap(); + let folder = solidcraft_engine::remote_slicers::RemoteTarget::folder_target("Share", &share.to_string_lossy()); + h.app.preferences.network_folders = vec![folder]; + let sends: Vec<_> = (0..7) + .map(|_| ask(&tx, "engine.execute", json!({"command": "file.send_to_slicer", "params": {"slicer": "Share", "bodies": ["Body1"]}}))) + .collect(); + let rename = ask(&tx, "engine.execute", json!({"command": "body.rename", "params": {"body": "Body1", "name": "Renamed"}})); + h.frames(1); + assert!(!h.app.control_sends_waiting.is_empty(), "some sends wait for a worker"); + assert_eq!(reply_to(&mut h, &rename)["ok"], true); + for send in &sends { + let r = reply_to(&mut h, send); + assert_eq!(r["ok"], true, "{r}"); + assert!(r["result"]["sent_to"].as_str().is_some_and(|sent| sent.contains("Body1")), "the body as it was named: {r}"); + } + assert_eq!(std::fs::read_dir(&share).unwrap().count(), 7); + let _ = std::fs::remove_dir_all(&share); +} + /// #9624: an inspection read on a copy reports the design's undo and redo counts and its file, /// as one run here does; the copy has no history and no file, and it said undo 0, redo 0, path /// none, so an agent could not tell how far to roll back a failed batch. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3a4b501cd87..8727c0a8de6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -209,6 +209,7 @@ mod navigation_bar_tests; mod navigation_bar_view; pub mod navigation_slots; pub use navigation::WebWheelGestures; +mod network_folder_ui; pub mod network_prompt; pub mod op_auto; pub mod open_elsewhere; @@ -480,6 +481,9 @@ pub struct Services { pub pick_file: Option FilePickerFuture>>, /// Open a dialog asking for a program (a slicer); `None` when the host has no such dialog. pub pick_program: Option FilePickerFuture>>, + /// Open a dialog asking for a folder (a network folder for Send to Slicer); `None` when the + /// host has no such dialog (the browser), and then no network folder is offered. + pub pick_folder: Option FilePickerFuture>>, pub show_in_folder: Option>, /// Where the host reads the anti-aliasing preference at start (a small JSON file). pub graphics_path: Option, @@ -603,6 +607,8 @@ pub struct SolveApp { file_picker: Option, /// A slicer started alone and waited for before the file is sent (Send to Slicer). pub(crate) slicer_wait: Option, + /// Send to Slicer's network folders: the window that adds one and a copy going on (#2304). + pub(crate) network_folder: network_folder_ui::State, /// Open with EasyPrint: the upload in flight and the question before the first one. pub(crate) easyprint: easyprint_ui::State, /// A Save or Save As being written on a worker (see [`save_job`]). @@ -804,6 +810,9 @@ pub struct SolveApp { control_job: Option, /// Agent exports computing on copies of the design. control_answering: Vec, + /// Sends to a network folder waiting for a free worker, each on the copy of the design taken + /// when it was asked for: they never run on the window thread. + control_sends_waiting: std::collections::VecDeque, /// The agent cursor acting out control requests. pub agent: agent_cursor::AgentCursor, /// The agent chat panel (docs/design/in-app-agent-chat.md). @@ -905,6 +914,7 @@ impl SolveApp { services, file_picker: None, slicer_wait: None, + network_folder: Default::default(), easyprint: Default::default(), saving: None, viewport: viewport::ViewportState::default(), @@ -1007,6 +1017,7 @@ impl SolveApp { control_held: Default::default(), control_job: None, control_answering: Vec::new(), + control_sends_waiting: Default::default(), agent: Default::default(), shots: solidcraft_control_egui::screenshot::Shots::new("no frame was presented (window hidden?); use ui.render"), styled: false, @@ -1291,6 +1302,8 @@ impl SolveApp { self.ui.layout = p.layout; self.preferences = p; } + // Send to Slicer's network folders live in the preferences; the session's commands use them. + self.session.network_folders = solidcraft_engine::remote_slicers::sanitized(&self.preferences.network_folders); // Before a design given at start opens: its paths follow the network preferences. prefs::sync_surface_analysis(self); prefs::apply_network(&self.preferences); @@ -1338,6 +1351,12 @@ impl SolveApp { solidcraft_engine::slicers::set_chosen_programs(&self.preferences.custom_slicers); } self.session.set_validation(self.preferences.validation); + // The network folders are the preferences'. A command matches its id in any case, and so + // do these checks. + let command_id = solidcraft_engine::find_command(id).map_or(id, |spec| spec.id); + if network_folder_ui::read_by(command_id) { + self.session.network_folders = solidcraft_engine::remote_slicers::sanitized(&self.preferences.network_folders); + } if id == "timeline.play" { let reply = self.session.execute(id, ¶ms).map_err(|e| e.to_string())?; let action = serde_json::from_value(reply["action"].clone()).map_err(|e| e.to_string())?; @@ -1421,7 +1440,8 @@ impl SolveApp { /// Host effects shared by directly executed and already evaluated commands. pub(crate) fn command_completed(&mut self, id: &str, r: Result) -> Result { // The engine has no edit in place to start or finish; the window does, and says when it can't. - let r = match solidcraft_engine::find_command(id).map(|spec| spec.id) { + let spec_id = solidcraft_engine::find_command(id).map(|spec| spec.id); + let r = match spec_id { // `queued`: it waits for the end of the agent's turn. Some("component.edit_in_place") => r.and_then(|v| edit_in_place::command_ran(self, &v).map(|queued| with_queued(v, queued))), Some("component.finish_edit") => r.and_then(|v| edit_in_place::finish_command(self).map(|queued| with_queued(v, queued))), @@ -1627,6 +1647,10 @@ impl SolveApp { // Curves drawn in construction (or centerline) mode take that line type. sketch_palette::apply_mode(self, id, v); } + // A network folder added or removed by a command is kept in the preferences. + if r.is_ok() && spec_id.is_some_and(network_folder_ui::changed_by) { + self.preferences.network_folders = self.session.network_folders.clone(); + } // Settings profiles live in the app: the engine only checked the parameters. let r = match r { Ok(v) if id.starts_with("settings.profile.") => settings_profiles::command(self, id, &v), @@ -3551,6 +3575,7 @@ impl SolveApp { // Preferences and Keyboard Shortcuts open from Home too (its links, the gear, Ctrl+,). prefs::show(self, ui.ctx()); browser::editors(self, ui); + network_folder_ui::show(self, ui.ctx()); return; } } @@ -3705,6 +3730,8 @@ impl SolveApp { joint_handles::show_warning(self, ui.ctx()); shortcut_box::show(self, ui.ctx()); prefs::show(self, ui.ctx()); + // Over Send to Slicer and Preferences, which both open it. + network_folder_ui::show(self, ui.ctx()); toolbar_custom::window(self, ui.ctx()); // All persistent producers have now registered this pass's actual // visible paint. Place independent controls and finish result navigation diff --git a/crates/ui-egui/src/network_folder_ui.rs b/crates/ui-egui/src/network_folder_ui.rs new file mode 100644 index 00000000000..c3692b792ab --- /dev/null +++ b/crates/ui-egui/src/network_folder_ui.rs @@ -0,0 +1,348 @@ +//! Send to Slicer's network folders (#2304): the window that adds or edits one (a name, a folder +//! and a Test button), the copy a send to one goes on with in the background, and their rows in +//! Preferences › General. The commands do the work (`file.slicers.add_remote` and +//! `file.slicers.remove_remote`, kept in the preferences by `SolveApp::run`, +//! see [`changed_by`]). The Test button and the copy run off the window thread: a share whose +//! server has gone can keep a file call waiting. +//! +//! The browser has no folder dialog, and offers no network folder. + +use serde_json::{Value, json}; +use solidcraft_engine::remote_slicers; + +use crate::SolveApp; +use crate::dialogs::Kind; +use crate::ui_kit; + +/// Edge of a network folder's icon in a list. +pub(crate) const ICON: f32 = 16.0; + +/// The window, and a copy going on. +#[derive(Default)] +pub struct State { + form: Option
, + /// A folder chosen in the folder dialog, waiting for the window to take it. + picked: Option, + /// A send whose copy goes on in the background: its ticket, the network folder's name and the + /// file that is being copied. + sending: Option<(u64, String, String)>, +} + +/// The values of the window. +struct Form { + name: String, + folder: String, + /// The name of the network folder being edited; none for a new one. + editing: Option, + /// Opened from Send to Slicer: the network folder it adds becomes the dialog's choice. + from_dialog: bool, + test: Test, + /// Why adding it was refused. + error: Option, +} + +#[derive(Default)] +enum Test { + #[default] + NotRun, + Running(std::sync::mpsc::Receiver>), + Done(Result<(), String>), +} + +/// Network folders can be offered: the host can ask for a folder (not the browser). +pub fn available(app: &SolveApp) -> bool { + app.services.pick_folder.is_some() +} + +/// Whether the command `id` (its registered id) reads the network folders: the session takes the +/// preferences' before it runs (Cancel in Preferences may have put back others). +pub(crate) fn read_by(id: &str) -> bool { + matches!(id, "file.save_mesh" | "file.send_to_slicer") || id.starts_with("file.slicers") +} + +/// Whether the command `id` (its registered id) adds or removes a network folder: the +/// preferences keep the session's once it ran. +pub(crate) fn changed_by(id: &str) -> bool { + matches!(id, "file.slicers.add_remote" | "file.slicers.remove_remote") +} + +/// The window for a new network folder. +pub fn open_new(app: &mut SolveApp, from_dialog: bool) { + app.network_folder.picked = None; + app.network_folder.form = Some(Form { name: String::new(), folder: String::new(), editing: None, from_dialog, test: Test::NotRun, error: None }); +} + +/// The window for the network folder named `name`. +pub fn open_edit(app: &mut SolveApp, name: &str) { + let Some(t) = app.preferences.network_folders.iter().find(|t| t.name == name) else { return }; + let form = Form { + name: t.name.clone(), + folder: t.folder().to_string(), + editing: Some(t.name.clone()), + from_dialog: false, + test: Test::NotRun, + error: None, + }; + app.network_folder.picked = None; + app.network_folder.form = Some(form); +} + +/// Take a network folder out of the list; the files sent there stay. +pub fn remove(app: &mut SolveApp, name: &str) { + if let Err(e) = app.run("file.slicers.remove_remote", json!({ "name": name })) { + app.set_status(e, true); + } +} + +fn same_name(a: &str, b: &str) -> bool { + a.trim().to_lowercase() == b.trim().to_lowercase() +} + +/// The window, when it is open. +pub fn show(app: &mut SolveApp, ctx: &egui::Context) { + if let Some(path) = app.network_folder.picked.take() + && let Some(form) = app.network_folder.form.as_mut() + { + form.folder = path; + form.test = Test::NotRun; + form.error = None; + } + let Some(mut form) = app.network_folder.form.take() else { return }; + let _language = solidcraft_ui_text::scope(&app.preferences.language); + if let Test::Running(rx) = &form.test { + use std::sync::mpsc::TryRecvError; + match rx.try_recv() { + Ok(answer) => form.test = Test::Done(answer), + Err(TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(200)), + Err(TryRecvError::Disconnected) => form.test = Test::Done(Err(solidcraft_ui_text::tr("ui.network_folder_test_stopped").to_string())), + } + } + let taken = app + .preferences + .network_folders + .iter() + .any(|t| same_name(&t.name, &form.name) && form.editing.as_deref().is_none_or(|old| !same_name(old, &t.name))); + let problem = remote_slicers::check_name(&form.name).err().filter(|_| !form.name.trim().is_empty()); + let problem = problem.or_else(|| taken.then(|| solidcraft_ui_text::tr("ui.network_folder_name_taken").to_string())); + let valid = problem.is_none() + && remote_slicers::check_name(&form.name).is_ok() + && remote_slicers::check_folder(&form.folder).is_ok() + && !matches!(form.test, Test::Running(_)); + let tr = |id: &str| solidcraft_ui_text::tr(id).to_string(); + let title = tr(if form.editing.is_some() { "ui.network_folder_edit_title" } else { "ui.network_folder_title" }); + let ok = tr(if form.editing.is_some() { "ui.network_folder_save" } else { "ui.network_folder_add" }); + let (test, note) = (tr("ui.network_folder_test"), tr("ui.network_folder_note")); + let (name_label, name_hint) = (tr("ui.network_folder_name"), tr("ui.network_folder_name_hint")); + let (folder_label, folder_hint, browse_label) = + (tr("ui.network_folder_folder"), tr("ui.network_folder_folder_hint"), tr("ui.network_folder_browse")); + let before = (form.name.clone(), form.folder.clone()); + let mut browse = false; + let picking = app.file_picker_busy(); + let (closed, action) = ui_kit::Confirm::new(egui::Id::unique("sc_network_folder"), "network_folder", &title) + .actions(&ok, "Cancel", Some(&test)) + .secondary_left() + .show(ctx, valid, |ui| { + ui_kit::text(ui, ¬e, ui_kit::Text::Note("network_folder_note")); + ui_kit::text_row(ui, &name_label, &mut form.name, &name_hint); + ui_kit::text_row(ui, &folder_label, &mut form.folder, &folder_hint); + crate::dialogs::form_row(ui, "", |ui| { + ui.add_enabled_ui(!picking, |ui| { + let r = ui_kit::button(ui, &browse_label, ui_kit::Button::Small); + crate::scenario::publish_handle("dialog:NetworkFolder:Browse", r.rect.center()); + browse = r.clicked(); + }); + }); + match &form.test { + Test::NotRun => {} + Test::Running(_) => { + ui_kit::text(ui, solidcraft_ui_text::tr("ui.network_folder_testing"), ui_kit::Text::Hint("network_folder_test")); + } + Test::Done(Ok(())) => { + ui_kit::text(ui, solidcraft_ui_text::tr("ui.network_folder_test_ok"), ui_kit::Text::Report("network_folder_test", false)); + } + Test::Done(Err(e)) => { + ui_kit::text(ui, e, ui_kit::Text::Error("network_folder_test")); + } + } + if let Some(e) = problem.as_ref().or(form.error.as_ref()) { + ui_kit::text(ui, e, ui_kit::Text::Error("network_folder_error")); + } + }); + if (form.name.as_str(), form.folder.as_str()) != (before.0.as_str(), before.1.as_str()) { + form.error = None; + if form.folder != before.1 { + form.test = Test::NotRun; + } + } + if browse { + app.pick_folder(|app, path| app.network_folder.picked = path); + } + match action { + ui_kit::Action::Apply => start_test(&mut form), + ui_kit::Action::Ok if valid => { + if !save(app, &mut form) { + app.network_folder.form = Some(form); + } + return; + } + ui_kit::Action::Cancel => return, + _ if closed => return, + _ => {} + } + app.network_folder.form = Some(form); +} + +/// Write and delete a small file in the folder, off the window thread. +fn start_test(form: &mut Form) { + if matches!(form.test, Test::Running(_)) { + return; + } + let folder = match remote_slicers::check_folder(&form.folder) { + Ok(folder) => folder.to_string(), + Err(e) => { + form.test = Test::Done(Err(e)); + return; + } + }; + let (tx, rx) = std::sync::mpsc::channel(); + let started = std::thread::Builder::new().name("network-folder-test".into()).spawn(move || { + let _ = tx.send(remote_slicers::probe(&folder)); + }); + form.test = match started { + Ok(_) => Test::Running(rx), + Err(e) => Test::Done(Err(e.to_string())), + }; +} + +/// Add (or change) the network folder; true when it was. +fn save(app: &mut SolveApp, form: &mut Form) -> bool { + let (name, folder) = (form.name.trim().to_string(), form.folder.trim().to_string()); + let added = match app.run("file.slicers.add_remote", json!({ "name": name, "folder": folder })) { + Ok(v) => v, + Err(e) => { + form.error = Some(e); + return false; + } + }; + let id = added.get("id").and_then(Value::as_str).unwrap_or_default().to_string(); + // Renamed: the old entry goes, and what chose it now chooses the new one. + if let Some(old) = form.editing.as_deref().filter(|old| !same_name(old, &name)) { + let old_id = format!("{}{old}", remote_slicers::ID_PREFIX); + let _ = app.run("file.slicers.remove_remote", json!({ "name": old })); + if app.preferences.send_slicer == old_id { + app.preferences.send_slicer = id.clone(); + } + choose_in_dialog(app, &id, Some(&old_id)); + } + if form.from_dialog { + choose_in_dialog(app, &id, None); + } + app.set_status(solidcraft_ui_text::format("ui.network_folder_added", &[("name", &name), ("folder", &folder)]), false); + true +} + +/// Make `id` the choice of the open Send to Slicer dialog (only in place of `instead`, when given). +fn choose_in_dialog(app: &mut SolveApp, id: &str, instead: Option<&str>) { + if let Some(Kind::SaveMesh(k)) = app.dialog.as_mut().map(|d| &mut d.kind) { + crate::dialogs_save_mesh::choose(k, id, instead); + } +} + +/// After `file.send_to_slicer` answered: a copy to a network folder that goes on in the background +/// is followed until it ends. True when one was. +pub fn follow(app: &mut SolveApp, result: &Value) -> bool { + let Some(ticket) = result.get("sending").and_then(Value::as_u64) else { return false }; + let name = result.get("target").and_then(Value::as_str).unwrap_or_default().to_string(); + let path = result.get("path").and_then(Value::as_str).unwrap_or_default().to_string(); + app.set_status(solidcraft_ui_text::format("ui.network_folder_sending", &[("target", &name)]), false); + app.network_folder.sending = Some((ticket, name, path)); + true +} + +/// A copy to a network folder is going on (a second send waits for it). +pub fn sending(app: &SolveApp) -> Option<&str> { + app.network_folder.sending.as_ref().map(|(_, name, _)| name.as_str()) +} + +/// Per frame: say where the copy went, or why it didn't, once it has ended. +pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { + let Some(ticket) = app.network_folder.sending.as_ref().map(|s| s.0) else { return }; + let Some(answer) = remote_slicers::poll(ticket) else { + ctx.request_repaint_after(std::time::Duration::from_millis(200)); + return; + }; + let Some((_, name, path)) = app.network_folder.sending.take() else { return }; + let _language = solidcraft_ui_text::scope(&app.preferences.language); + match answer { + Ok(sent) => { + let to = sent.path.to_string_lossy(); + app.set_status(solidcraft_ui_text::format("ui.sent_to_network_folder", &[("target", &name), ("path", &to)]), false); + } + Err(e) => { + let line = solidcraft_ui_text::format("ui.network_folder_send_failed", &[("target", &name), ("error", &e), ("path", &path)]); + app.set_status(line, true); + } + } +} + +/// Preferences › General: the Network folders block, the folders to change or remove and a button +/// to add one. +pub fn prefs_block(app: &mut SolveApp, ui: &mut egui::Ui, label_width: f32) { + let label = solidcraft_ui_text::tr("ui.network_folders").to_string(); + if !crate::ui_kit::settings_search::querying(ui) { + ui_kit::settings_block(ui, &label, label_width, |ui| listed_rows(app, ui)); + return; + } + // A search finds the block by its label, a folder's name or where it sends (#2304). The rows have + // no labelled control, so the hit is taken here, before the block: the page and section headings + // then go above it, not into its control column, and the block is shown whole. + crate::ui_kit::settings_search::set_control(ui, &label); + let mut texts = vec![label.clone(), solidcraft_ui_text::tr("ui.network_folder_add_button").to_string()]; + for t in &app.preferences.network_folders { + texts.extend([t.name.clone(), t.folder().to_string()]); + } + let texts: Vec<&str> = texts.iter().map(String::as_str).collect(); + if !crate::ui_kit::settings_search::visible(ui, &texts) { + return; + } + crate::ui_kit::settings_search::push_force(ui); + ui_kit::settings_block(ui, &label, label_width, |ui| listed_rows(app, ui)); + crate::ui_kit::settings_search::pop_force(ui); +} + +fn listed_rows(app: &mut SolveApp, ui: &mut egui::Ui) { + let mut edit = None; + let mut gone = None; + if app.preferences.network_folders.is_empty() { + ui_kit::text(ui, solidcraft_ui_text::tr("ui.network_folders_none"), ui_kit::Text::Hint("network_folders_none")); + } + for t in &app.preferences.network_folders { + ui.horizontal(|ui| { + let (rect, _) = ui.allocate_exact_size(egui::vec2(ICON, ICON), egui::Sense::hover()); + crate::icons::paint_icon(ui.painter(), rect, "network_folder", 1.0); + // The actions sit at the right edge; the name and folder take what is left and truncate. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui_kit::button(ui, solidcraft_ui_text::tr("ui.network_folder_remove"), ui_kit::Button::Small).clicked() { + gone = Some(t.name.clone()); + } + if ui_kit::button(ui, solidcraft_ui_text::tr("ui.network_folder_edit"), ui_kit::Button::Small).clicked() { + edit = Some(t.name.clone()); + } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui_kit::text(ui, &format!("{} — {}", t.name, t.folder()), ui_kit::Text::Inline); + }); + }); + }); + } + let add = ui_kit::button(ui, solidcraft_ui_text::tr("ui.network_folder_add_button"), ui_kit::Button::Small); + crate::scenario::publish_handle("prefs:network_folder_add", add.rect.center()); + if add.clicked() { + open_new(app, false); + } + if let Some(name) = edit { + open_edit(app, &name); + } + if let Some(name) = gone { + remove(app, &name); + } +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 9c723aeaaa2..fe9a13b2255 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1466,6 +1466,18 @@ preference_settings! { save_mesh_quality: String = "standard".into(); /// The programs the user added to the slicer list, newest first. custom_slicers: Vec = Vec::new(); + /// The network folders the user added to Send to Slicer (#2304), in the order added: a folder, + /// usually a mounted share, that a slicer on another computer reads. No page reset discards + /// this user-made list; the engine gets it before each slicer command. An entry that doesn't + /// read is dropped on its own, not the whole list. + #[serde(deserialize_with = "network_folders_that_read")] + network_folders: Vec = Vec::new(); + /// Send to Slicer: the last format (`3mf`, `stl` or `stl-ascii`). 3MF, as before the + /// dialog had a Format row. + send_format: String = "3mf".into(); + /// Send to Slicer: the last quality (`standard`, `fine` or `finest`). Standard, as before the + /// dialog had a Quality row. + send_quality: String = "standard".into(); /// AI features (docs/agent-chat.md): the master switch. Off: no AI button, shortcut, menu /// entry or panel, and nothing is looked for or started. ai_features: bool = true, PAGE_ASSISTANT; @@ -3242,6 +3254,23 @@ fn devices_that_read<'de, D: serde::Deserializer<'de>>(saved: D) -> Result>(saved: D) -> Result, D::Error> { + let saved = Vec::::deserialize(saved)?; + Ok(saved + .into_iter() + .enumerate() + .filter_map(|(i, folder)| match serde_json::from_value(folder) { + Ok(folder) => Some(folder), + Err(error) => { + log::warn!("preferences: network folder {} can't be read ({error}); leaving it out", i + 1); + None + } + }) + .collect()) +} + /// The saved button jobs that still read. A job this version doesn't know (from a newer release) /// drops that button only, with a log line, not its device's other buttons or the other devices. fn button_jobs_that_read<'de, D: serde::Deserializer<'de>>( @@ -6712,6 +6741,23 @@ mod tests { assert!(other.session.doc.sheet.rules.is_empty(), "a personal rule is not a rule of the design"); } + /// A saved network folder this version can't read (a kind from a newer release, a hand edit) + /// is left out on its own: it emptied the whole list, and the next save wrote that back. + #[test] + fn a_network_folder_that_does_not_read_leaves_the_others() { + use serde_json::json; + let p = super::lenient(&json!({"length_decimals": 4, "network_folders": [ + {"name": "NAS", "kind": "folder", "folder": "/mnt/nas"}, + {"name": "Newer", "kind": "webdav", "url": "https://printer.local/prints"}, + {"name": "No folder", "kind": "folder"}, + null, + {"name": "Shop", "kind": "folder", "folder": "/mnt/shop"}, + ]})); + assert_eq!(p.length_decimals, 4); + let names: Vec<_> = p.network_folders.iter().map(|t| t.name.as_str()).collect(); + assert_eq!(names, ["NAS", "Shop"]); + } + /// The interface font (#1290): a font that can be read, or empty for the built-in one; saved /// with the others and reset by Restore Defaults. #[test] diff --git a/crates/ui-egui/src/prefs/general.rs b/crates/ui-egui/src/prefs/general.rs index 33711df5d6a..0b61a63f1a0 100644 --- a/crates/ui-egui/src/prefs/general.rs +++ b/crates/ui-egui/src/prefs/general.rs @@ -126,6 +126,10 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }); ui_kit::help_icon(ui, &tip); }); + // Send to Slicer's network folders (#2304); the browser has none. + if crate::network_folder_ui::available(app) { + crate::network_folder_ui::prefs_block(app, ui, labels); + } ui_kit::settings_form(ui, labels, |ui| { ui_kit::settings_row_help(ui, app.tr("prefs.print_face_highlight"), app.tr("prefs.print_face_highlight_tip"), |ui| { ui_kit::settings_control_width(ui, t.space_24 * 10.0, |ui| { From 734ad815c0f88f6d610ccc9e74222ac65e08c612 Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Sun, 1 Nov 2026 15:37:10 -0300 Subject: [PATCH 3/3] Docs: Send to Slicer's Format and Quality rows and network folders (#2304) --- docs/book/src/guide/files.md | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index 94bab022970..1dae2145404 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -63,9 +63,11 @@ Cura then load it as one object with a part per body, and each part can take its design's own bodies, and a component with a single body, stay objects of their own. **File → Send to Slicer** (also on the Insert tab's Files panel, and in the right-click menu of a -body) is the short way: it saves the selected bodies as a 3MF in millimetres, without face tags, +body) is the short way: it saves the selected bodies as a mesh in millimetres, without face tags, and sends it to a slicer. It always asks which one and pre-selects the slicer you used last time, -so the usual case is one click or Enter. The list shows the slicers found on the computer with their +so the usual case is one click or Enter. Its **Format** row picks 3MF (the default), binary STL or +ASCII STL, and its **Quality** row how closely the mesh follows curved faces (Standard, the +default, Fine or Finest, as in Save as Mesh); both are remembered for the next send. The list shows the slicers found on the computer with their icons; **Custom…** adds any other program to the top of the list (kept between runs; hover an entry you added and press Delete to remove it). On Linux only, a program whose desktop entry says it opens 3MF or STL files is listed even if SolidCraft doesn't know it by name. Windows and macOS list the @@ -187,6 +189,32 @@ retain world coordinates. A lost cross-component association refreshed by an old need an explicit relink or refresh when its source returns. Loading never guesses a numerical correction. Association records, coordinate arrays and placements are bounded and checked. +## Network folders + +A slicer on another computer, such as OrcaSlicer in a container on a home server, can read the +files you send from a shared folder. Mount the share on this computer first (SMB or NFS, as your +system does it), then choose **Network folder…** at the bottom of the Send to Slicer list. Give it a +name, pick the folder with **Browse…**, and press **Test** to write a small file there and delete it +again. **Add** keeps it in your preferences, never in the design, and it is listed at the top of +the slicer list with a network icon, ready for the next send. + +Sending to a network folder starts no program. The file is written as for any slicer and copied +into the folder under the design's name, and the body's after it when one body is sent +(`Bracket - Arm.3mf`). A file that is already there is never replaced: the copy is numbered +instead (`Bracket - Arm (2).3mf`). It is copied under a hidden name first and then given its +name, so a slicer that watches the folder never reads half a file. The status line says where the +file went, or why it couldn't go: the folder is not there (is the share mounted?), there is no +permission to write, the disk is full, the file is larger than 1 GB, or the share did not answer +within 30 seconds. A missing folder is never created, so nothing lands on this computer by mistake +when a share is not mounted, and the file stays in your slicer folder either way. + +Hover a network folder in the list and press Delete to remove it, or change and remove them in +**Preferences → General**, under Files; the files already sent stay. The browser build has no network +folders. Scripts and the control channel use `file.slicers.add_remote` (`name`, `folder`), +`file.slicers.remove_remote` and `file.slicers.test` (`name` or `folder`); `file.slicers` lists the +network folders first, with `remote: true`, and `file.send_to_slicer` or `file.save_mesh` take a +network folder's name or id (`remote:`) as their `slicer`. None of them opens a window. + ## Large files SolidCraft opens STEP, IGES and the other CAD files it imports up to **512 MB**, and design files