SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Web: save to and open from files on your computer (#104) (#3681)
bherbruckb2168435baf7
diff --git a/apps/solidcraft-web/Cargo.toml b/apps/solidcraft-web/Cargo.tomlindex 668fe0860e..6bfebbb565 100644--- a/apps/solidcraft-web/Cargo.toml+++ b/apps/solidcraft-web/Cargo.toml@@ -29,5 +29,6 @@ web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "Location", "Navigator", "StorageManager","FileSystemHandle", "FileSystemDirectoryHandle", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemWritableFileStream","WritableStream", "File", "FileList", "Blob", "BlobPropertyBag", "Url", "HtmlAnchorElement", "HtmlInputElement", "Storage",+ "IdbFactory", "IdbDatabase", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode","BeforeUnloadEvent", "Event", "EventTarget", "Response", "MediaQueryList", "Gamepad", "Performance",] }diff --git a/apps/solidcraft-web/src/disk.rs b/apps/solidcraft-web/src/disk.rsnew file mode 100644index 0000000000..0b6b839ab5--- /dev/null+++ b/apps/solidcraft-web/src/disk.rs@@ -0,0 +1,418 @@+//! Designs on the computer's own disk, through the File System Access API (Chrome, Edge, Opera):+//! Save As and Open show the browser's file dialogs, and the chosen file's handle is kept (in+//! memory, and in IndexedDB so Save still reaches the file after a reload) so Save writes back to+//! it. To the engine such a design is the file `/disk/<id>/<name>`: it saves there like anywhere,+//! and [`flush`](crate::files::flush) forwards what it wrote to the handle. Browsers without the+//! API (Firefox, Safari) keep designs in the origin private file system (`files.rs`).+//!+//! The path logic is plain Rust and tested natively; the browser calls are wasm-only.+#![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]++/// Where a design on the computer's disk appears to the engine.+pub const PREFIX: &str = "/disk/";++/// The engine path of the design `name` kept under handle `id`.+pub fn path(id: &str, name: &str) -> String {+ format!("{PREFIX}{id}/{name}")+}++/// The handle id and file name of an engine path made by [`path`].+pub fn parse(path: &str) -> Option<(&str, &str)> {+ let (id, name) = path.strip_prefix(PREFIX)?.split_once('/')?;+ (!id.is_empty() && !name.is_empty() && !name.contains('/')).then_some((id, name))+}++/// A handle id from the time and a random number.+pub fn make_id(ms: u64, random: u64) -> String {+ format!("{ms:x}-{random:x}")+}++/// Where a design saved with Save As goes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum SaveTarget {+ /// A file the user picks on their computer.+ Disk,+ /// The browser's private storage (OPFS): what browsers without the API have always done.+ Browser,+ /// Not a design (an export): handed over as a download.+ Download,+}++/// Choose where a Save As goes: designs to the disk when the browser can pick a file, else into+/// the browser's storage; anything else is a download.+pub fn save_target(api: bool, design: bool) -> SaveTarget {+ match (design, api) {+ (false, _) => SaveTarget::Download,+ (true, true) => SaveTarget::Disk,+ (true, false) => SaveTarget::Browser,+ }+}++/// Does a picker for `extensions` (what the command reads; `&[]`: anything) belong to a design?+/// Only those go through the disk dialog; inserting a STEP or mesh keeps using the file window.+pub fn opens_design(extensions: &[&str]) -> bool {+ extensions.is_empty() || extensions.iter().any(|e| solidcraft_engine::io::DESIGN_EXTS.contains(e))+}++/// The file type a Save As dialog offers for `name`: (description, MIME type, extension).+pub fn save_type(name: &str) -> (&'static str, &'static str, &'static str) {+ let json = std::path::Path::new(name).extension().is_some_and(|e| e.eq_ignore_ascii_case("json"));+ if json { ("Plain JSON design", "application/json", ".json") } else { ("SolidCraft design", "application/octet-stream", ".solidcraft") }+}++/// Is this a cancelled dialog (the browser's `AbortError`)? Not an error to show.+pub fn is_abort(error_name: &str) -> bool {+ error_name == "AbortError"+}++#[cfg(target_arch = "wasm32")]+pub use web::*;++#[cfg(target_arch = "wasm32")]+mod web {+ use std::cell::{Cell, RefCell};+ use std::collections::{HashMap, VecDeque};+ use std::rc::Rc;++ use js_sys::{Array, Function, Object, Promise, Reflect};+ use solidcraft_engine::io::vfs;+ use wasm_bindgen::{JsCast as _, JsValue, closure::Closure};+ use wasm_bindgen_futures::{JsFuture, spawn_local};+ use web_sys::{FileSystemFileHandle, IdbDatabase, IdbObjectStore, IdbOpenDbRequest, IdbRequest, IdbTransactionMode};++ use super::{is_abort, make_id, opens_design, parse, path, save_type};+ use crate::files::{Files, err, read_handle};++ const DB: &str = "solidcraft-disk-handles";+ const STORE: &str = "handles";++ thread_local! {+ /// Handles picked or looked up in this session, by id.+ static HANDLES: RefCell<HashMap<String, FileSystemFileHandle>> = RefCell::new(HashMap::new());+ /// Writes waiting for their turn (a file takes one writer at a time), latest per id.+ static QUEUE: RefCell<VecDeque<(String, Vec<u8>)>> = const { RefCell::new(VecDeque::new()) };+ static BUSY: Cell<bool> = const { Cell::new(false) };+ }++ /// Why a dialog gave no file.+ enum Pick {+ Cancelled,+ Failed(String),+ }++ fn failed(e: JsValue) -> Pick {+ let name = Reflect::get(&e, &"name".into()).ok().and_then(|n| n.as_string()).unwrap_or_default();+ if is_abort(&name) { Pick::Cancelled } else { Pick::Failed(err(e)) }+ }++ /// Can this page show the browser's file dialogs and write to the files they pick?+ pub fn supported() -> bool {+ let Some(window) = web_sys::window() else { return false };+ let has = |name: &str| Reflect::get(&window, &name.into()).is_ok_and(|f| f.is_function());+ window.is_secure_context() && has("showSaveFilePicker") && has("showOpenFilePicker")+ }++ /// Is `path` a design on the disk?+ pub fn is_disk(path: &str) -> bool {+ parse(path).is_some()+ }++ fn types(description: &str, mime: &str, extension: &str) -> Array {+ let accept = Object::new();+ let _ = Reflect::set(&accept, &mime.into(), &Array::of1(&extension.into()));+ let entry = Object::new();+ let _ = Reflect::set(&entry, &"description".into(), &description.into());+ let _ = Reflect::set(&entry, &"accept".into(), &accept);+ Array::of1(&entry)+ }++ /// Start a dialog. This must run in the click that asked for it (the browser wants a user+ /// gesture), so it is called before anything is awaited.+ fn start_picker(function: &str, options: &Object) -> Result<Promise, Pick> {+ let window = web_sys::window().ok_or_else(|| Pick::Failed("no window".into()))?;+ let f: Function = Reflect::get(&window, &function.into())+ .map_err(failed)?+ .dyn_into()+ .map_err(|_| Pick::Failed("this browser can't open file dialogs".into()))?;+ f.call1(&window, options).map_err(failed)?.dyn_into().map_err(|_| Pick::Failed("no answer from the file dialog".into()))+ }++ /// Remember a picked file: in memory now, in IndexedDB for the next session.+ fn register(handle: &FileSystemFileHandle) -> String {+ let id = make_id(js_sys::Date::now() as u64, (js_sys::Math::random() * 1e15) as u64);+ HANDLES.with(|h| h.borrow_mut().insert(id.clone(), handle.clone()));+ let (key, kept, name) = (id.clone(), handle.clone(), handle.name());+ spawn_local(async move {+ if let Err(e) = remember(&key, &kept).await {+ log::warn!("the file's handle isn't kept for the next session: {e}");+ }+ });+ path(&id, &name)+ }++ /// Save As, step one: show the browser's save dialog (call in the click). The answer is the+ /// engine path the design is saved to, `None` when the dialog was closed.+ pub fn pick_save(files: &Rc<Files>, name: &str) -> impl std::future::Future<Output = Option<String>> + use<> {+ let options = Object::new();+ let _ = Reflect::set(&options, &"suggestedName".into(), &name.into());+ let (description, mime, extension) = save_type(name);+ let _ = Reflect::set(&options, &"types".into(), &types(description, mime, extension));+ let promise = start_picker("showSaveFilePicker", &options);+ let files = files.clone();+ async move {+ let handle = match promise {+ Ok(p) => JsFuture::from(p)+ .await+ .map_err(failed)+ .and_then(|h| h.dyn_into::<FileSystemFileHandle>().map_err(|_| Pick::Failed("not a file".into()))),+ Err(e) => Err(e),+ };+ match handle {+ Ok(h) => Some(register(&h)),+ Err(Pick::Cancelled) => None,+ Err(Pick::Failed(e)) => {+ files.say(format!("save: {e}"), true);+ None+ }+ }+ }+ }++ /// Open, step one: show the browser's open dialog for a design (call in the click). The+ /// answer is the engine path of the file, read into the engine's files; a design keeps its+ /// handle, so Save writes back to the file. `None`: closed, or it could not be read.+ pub fn pick_open(files: &Rc<Files>) -> impl std::future::Future<Output = Option<String>> + use<> {+ let promise = start_picker("showOpenFilePicker", &open_options());+ let files = files.clone();+ async move {+ let r = async {+ let p = promise?;+ let handles: Array = JsFuture::from(p).await.map_err(failed)?.dyn_into().map_err(|_| Pick::Failed("no file".into()))?;+ let h: FileSystemFileHandle = handles.get(0).dyn_into().map_err(|_| Pick::Cancelled)?;+ let bytes = read_handle(&h).await.map_err(Pick::Failed)?;+ Ok((h, bytes))+ };+ match r.await {+ Ok((h, bytes)) => Some(arrive(&h, bytes)),+ Err(Pick::Cancelled) => None,+ Err(Pick::Failed(e)) => {+ files.say(format!("open: {e}"), true);+ None+ }+ }+ }+ }++ /// The options of the open dialog: a single file, designs and CAD files listed first.+ pub fn open_options() -> Object {+ let options = Object::new();+ let _ = Reflect::set(&options, &"multiple".into(), &JsValue::FALSE);+ let extensions = Array::new();+ for e in [".solidcraft", ".solvecraft", ".json", ".step", ".stp", ".3mf", ".stl", ".obj", ".glb", ".gltf"] {+ extensions.push(&e.into());+ }+ let accept = Object::new();+ let _ = Reflect::set(&accept, &"application/octet-stream".into(), &extensions);+ let entry = Object::new();+ let _ = Reflect::set(&entry, &"description".into(), &"Designs and CAD files".into());+ let _ = Reflect::set(&entry, &"accept".into(), &accept);+ let _ = Reflect::set(&options, &"types".into(), &Array::of1(&entry));+ options+ }++ /// A file read from a dialog's handle: a design lives at its disk path from now on (and+ /// keeps the handle); anything else is an upload to open or insert.+ pub fn arrive(handle: &FileSystemFileHandle, bytes: Vec<u8>) -> String {+ let name = handle.name();+ let p = if solidcraft_engine::io::is_design_path(&name) { register(handle) } else { format!("{}{name}", crate::files::UPLOAD) };+ vfs::insert(&p, bytes);+ p+ }++ /// Does an Open for `extensions` use the browser's open dialog?+ pub fn handles_open(extensions: &[&str]) -> bool {+ supported() && opens_design(extensions)+ }++ // ---- writing ------------------------------------------------------------------------++ /// Queue what a command wrote to a disk path. Writes go one at a time; a newer write of the+ /// same file replaces one still waiting.+ pub fn enqueue(files: &Rc<Files>, path: &str, bytes: Vec<u8>) {+ QUEUE.with(|q| {+ let mut q = q.borrow_mut();+ q.retain(|(p, _)| p != path);+ q.push_back((path.to_string(), bytes));+ });+ if BUSY.with(|b| b.replace(true)) {+ return;+ }+ let files = files.clone();+ spawn_local(async move {+ while let Some((path, bytes)) = QUEUE.with(|q| q.borrow_mut().pop_front()) {+ if let Err(e) = write(&path, &bytes).await {+ files.failed_disk(&path, &e);+ }+ }+ BUSY.with(|b| b.set(false));+ });+ }++ async fn write(path: &str, bytes: &[u8]) -> Result<(), String> {+ let (id, name) = parse(path).ok_or("not a file on the computer")?;+ let handle = handle_for(id).await.map_err(|e| format!("{name}: {e}"))?;+ ensure_readwrite(&handle).await.map_err(|e| format!("{name}: {e}"))?;+ let w: web_sys::FileSystemWritableFileStream =+ JsFuture::from(handle.create_writable()).await.map_err(err)?.dyn_into().map_err(|_| "no writable stream".to_string())?;+ JsFuture::from(w.write_with_u8_array(bytes).map_err(err)?).await.map_err(err)?;+ JsFuture::from(w.close()).await.map_err(err)?;+ Ok(())+ }++ async fn handle_for(id: &str) -> Result<FileSystemFileHandle, String> {+ if let Some(h) = HANDLES.with(|h| h.borrow().get(id).cloned()) {+ return Ok(h);+ }+ let h: FileSystemFileHandle = recall(id)+ .await?+ .and_then(|v| v.dyn_into().ok())+ .ok_or("the browser no longer remembers where this design was saved: use Save As to choose the file again")?;+ HANDLES.with(|m| m.borrow_mut().insert(id.to_string(), h.clone()));+ Ok(h)+ }++ /// Ask for write access if the browser doesn't hold it any more (after a reload): one prompt,+ /// from the click that asked for the save.+ async fn ensure_readwrite(handle: &FileSystemFileHandle) -> Result<(), String> {+ let options = Object::new();+ let _ = Reflect::set(&options, &"mode".into(), &"readwrite".into());+ for method in ["queryPermission", "requestPermission"] {+ let Some(f) = Reflect::get(handle, &method.into()).ok().and_then(|f| f.dyn_into::<Function>().ok()) else {+ // A browser without the permission calls hands out writable handles as they are.+ return Ok(());+ };+ let answer = f.call1(handle, &options).map_err(err)?;+ let state = JsFuture::from(Promise::resolve(&answer)).await.map_err(err)?;+ if state.as_string().as_deref() == Some("granted") {+ return Ok(());+ }+ }+ Err("the browser wasn't given permission to write the file: use Save As to choose it again".into())+ }++ // ---- IndexedDB: the handles, by id --------------------------------------------------++ /// The result of an IndexedDB request.+ async fn result(req: &IdbRequest) -> Result<JsValue, String> {+ let promise = Promise::new(&mut |resolve, reject| {+ let r = req.clone();+ let ok = Closure::once_into_js(move || {+ let _ = resolve.call1(&JsValue::NULL, &r.result().unwrap_or(JsValue::UNDEFINED));+ });+ let bad = Closure::once_into_js(move || {+ let _ = reject.call1(&JsValue::NULL, &"IndexedDB failed".into());+ });+ req.set_onsuccess(Some(ok.unchecked_ref()));+ req.set_onerror(Some(bad.unchecked_ref()));+ });+ JsFuture::from(promise).await.map_err(err)+ }++ async fn open_db() -> Result<IdbDatabase, String> {+ let factory = web_sys::window().ok_or("no window")?.indexed_db().map_err(err)?.ok_or("this browser has no IndexedDB")?;+ let request: IdbOpenDbRequest = factory.open_with_u32(DB, 1).map_err(err)?;+ let target = request.clone();+ let upgrade = Closure::once_into_js(move || {+ if let Ok(db) = target.result().and_then(|r| r.dyn_into::<IdbDatabase>()) {+ let _ = db.create_object_store(STORE);+ }+ });+ request.set_onupgradeneeded(Some(upgrade.unchecked_ref()));+ result(&request).await?.dyn_into().map_err(|_| "no database".to_string())+ }++ fn store(db: &IdbDatabase, mode: IdbTransactionMode) -> Result<IdbObjectStore, String> {+ db.transaction_with_str_and_mode(STORE, mode).map_err(err)?.object_store(STORE).map_err(err)+ }++ async fn remember(id: &str, handle: &FileSystemFileHandle) -> Result<(), String> {+ let db = open_db().await?;+ let req = store(&db, IdbTransactionMode::Readwrite)?.put_with_key(handle, &id.into()).map_err(err)?;+ result(&req).await.map(|_| ())+ }++ async fn recall(id: &str) -> Result<Option<JsValue>, String> {+ let db = open_db().await?;+ let req = store(&db, IdbTransactionMode::Readonly)?.get(&id.into()).map_err(err)?;+ Ok(Some(result(&req).await?).filter(|v| !v.is_undefined()))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_disk_path_round_trips_its_handle_id_and_name() {+ let p = path("18f-2a", "Bracket v2.solidcraft");+ assert_eq!(p, "/disk/18f-2a/Bracket v2.solidcraft");+ assert_eq!(parse(&p), Some(("18f-2a", "Bracket v2.solidcraft")));+ }++ #[test]+ fn only_disk_paths_parse() {+ for not in [+ "/opfs/a.solidcraft",+ "/downloads/a.step",+ "/upload/a.step",+ "/disk/",+ "/disk/id",+ "/disk/id/",+ "/disk//a",+ "/disk/id/x/y",+ "a.solidcraft",+ ] {+ assert_eq!(parse(not), None, "{not}");+ }+ }++ #[test]+ fn handle_ids_differ_by_time_and_by_chance() {+ assert_ne!(make_id(1, 5), make_id(2, 5));+ assert_ne!(make_id(1, 5), make_id(1, 6));+ assert!(!make_id(0, 0).contains('/'));+ }++ /// Save As: a design goes to the disk where the browser can pick files and to the browser's+ /// storage where it cannot (today's behaviour); an export is a download either way.+ #[test]+ fn save_as_chooses_between_the_disk_the_browsers_storage_and_a_download() {+ assert_eq!(save_target(true, true), SaveTarget::Disk);+ assert_eq!(save_target(false, true), SaveTarget::Browser);+ assert_eq!(save_target(true, false), SaveTarget::Download);+ assert_eq!(save_target(false, false), SaveTarget::Download);+ }++ #[test]+ fn only_design_opens_use_the_disk_dialog() {+ assert!(opens_design(&[]));+ assert!(opens_design(&["solidcraft"]));+ assert!(opens_design(&["solvecraft"]));+ assert!(!opens_design(&["step", "stp"]));+ assert!(!opens_design(&["json"]));+ }++ #[test]+ fn the_save_dialog_offers_the_type_of_the_name() {+ assert_eq!(save_type("Plate.solidcraft").2, ".solidcraft");+ assert_eq!(save_type("Plate.JSON").2, ".json");+ assert_eq!(save_type("Plate").2, ".solidcraft");+ }++ #[test]+ fn closing_a_dialog_is_not_an_error() {+ assert!(is_abort("AbortError"));+ assert!(!is_abort("NotAllowedError"));+ assert!(!is_abort("SecurityError"));+ }+}diff --git a/apps/solidcraft-web/src/files.rs b/apps/solidcraft-web/src/files.rsindex 126bede0cc..42be96deee 100644--- a/apps/solidcraft-web/src/files.rs+++ b/apps/solidcraft-web/src/files.rs@@ -2,14 +2,18 @@//! the engine's in-memory files (`solidcraft_engine::io::vfs`) at start, written back whenever a//! command writes one. Files come in from the computer through a file picker (the File System//! Access API where the browser has it, an `<input type=file>` otherwise) or a drop on the page,-//! and go out as downloads (exports, and "Download design"). An autosave of unsaved work is kept-//! in OPFS too and offered again after a reload or a crash.+//! and go out as downloads (exports, and "Download design"). Where the File System Access API+//! exists a design also lives on the computer's disk, saved and opened through the browser's file+//! dialogs (`disk.rs`). An autosave of unsaved work is kept in OPFS and offered again after a+//! reload or a crash.use std::cell::{Cell, RefCell};use std::rc::Rc;use js_sys::{Array, Function, Object, Reflect, Uint8Array};use solidcraft_engine::io::vfs;++use crate::disk;use wasm_bindgen::{JsCast as _, JsValue, closure::Closure};use wasm_bindgen_futures::{JsFuture, spawn_local};use web_sys::{FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetFileOptions, FileSystemWritableFileStream};@@ -51,6 +55,10 @@ pub struct Files {pub entries: RefCell<Vec<Entry>>,/// Files read from the computer: (name, bytes, what to do).pub incoming: RefCell<Vec<(String, Vec<u8>, Intent)>>,+ /// Designs opened from the computer's disk: their paths in the engine's files.+ pub opened: RefCell<Vec<String>>,+ /// Disk designs whose last write failed: they are not saved.+ pub unsaved: RefCell<Vec<String>>,/// Messages for the status line (errors and confirmations).pub messages: RefCell<Vec<(String, bool)>>,/// The stored designs are loaded (the app may open them).@@ -64,11 +72,17 @@ pub struct Files {}impl Files {- fn say(&self, text: impl Into<String>, error: bool) {+ pub fn say(&self, text: impl Into<String>, error: bool) {self.messages.borrow_mut().push((text.into(), error));self.wake();}+ /// Writing the design at disk `path` failed: say so, and take its "saved" back.+ pub fn failed_disk(&self, path: &str, error: &str) {+ self.unsaved.borrow_mut().push(path.to_string());+ self.say(format!("Not saved to your computer: {error}"), true);+ }+/// A file arrived from the computer.fn arrive(&self, name: String, bytes: Vec<u8>, intent: Intent) {self.incoming.borrow_mut().push((name, bytes, intent));@@ -127,7 +141,7 @@ pub fn local_only() -> bool {LOCAL.with(Cell::get)}-fn err(e: JsValue) -> String {+pub(crate) fn err(e: JsValue) -> String {e.as_string().or_else(|| Reflect::get(&e, &"message".into()).ok().and_then(|m| m.as_string())).unwrap_or_else(|| format!("{e:?}"))}@@ -150,7 +164,7 @@ async fn root() -> Result<FileSystemDirectoryHandle, String> {dir.dyn_into::<FileSystemDirectoryHandle>().map_err(|_| "this browser has no private file storage (OPFS)".to_string())}-async fn read_handle(h: &FileSystemFileHandle) -> Result<Vec<u8>, String> {+pub(crate) async fn read_handle(h: &FileSystemFileHandle) -> Result<Vec<u8>, String> {let file: web_sys::File = JsFuture::from(h.get_file()).await.map_err(err)?.dyn_into().map_err(|_| "not a file".to_string())?;blob_bytes(&file).await}@@ -311,6 +325,8 @@ pub fn flush(files: &Rc<Files>) {files.say(format!("{name}: {e}"), true);}});+ } else if crate::disk::is_disk(&path) {+ disk::enqueue(files, &path, bytes);} else if let Some(name) = path.strip_prefix(DOWNLOADS)&& let Err(e) = download(name, &bytes){@@ -427,8 +443,15 @@ pub fn pick_from_disk(files: &Rc<Files>, intent: Intent) {let picker = Reflect::get(&window, &"showOpenFilePicker".into()).ok().and_then(|f| f.dyn_into::<Function>().ok());match picker {Some(f) => {- let opts = Object::new();- let _ = Reflect::set(&opts, &"multiple".into(), &JsValue::FALSE);+ // A design from the computer's disk keeps its file, so Save writes back to it.+ let on_disk = intent == Intent::Open && disk::supported();+ let opts = if on_disk {+ disk::open_options()+ } else {+ let opts = Object::new();+ let _ = Reflect::set(&opts, &"multiple".into(), &JsValue::FALSE);+ opts+ };let promise = f.call1(&window, &opts);let files = files.clone();spawn_local(async move {@@ -438,7 +461,13 @@ pub fn pick_from_disk(files: &Rc<Files>, intent: Intent) {for h in handles.iter() {let h: FileSystemFileHandle = h.dyn_into().map_err(|_| "not a file".to_string())?;let bytes = read_handle(&h).await?;- files.arrive(h.name(), bytes, intent);+ if on_disk && solidcraft_engine::io::is_design_path(&h.name()) {+ let path = disk::arrive(&h, bytes);+ files.opened.borrow_mut().push(path);+ files.wake();+ } else {+ files.arrive(h.name(), bytes, intent);+ }}Ok::<(), String>(())};diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rsindex 4b4819f654..72de50bb34 100644--- a/apps/solidcraft-web/src/main.rs+++ b/apps/solidcraft-web/src/main.rs@@ -8,6 +8,8 @@#[cfg(target_arch = "wasm32")]mod api;+#[cfg(any(target_arch = "wasm32", test))]+mod disk;#[cfg(target_arch = "wasm32")]mod files;#[cfg(target_arch = "wasm32")]@@ -25,6 +27,7 @@ mod web {use wasm_bindgen::JsCast as _;use crate::api::Api;+ use crate::disk::{self, SaveTarget};use crate::files::{self, Files, Intent};use crate::space_mouse::SpaceMouse;@@ -121,6 +124,18 @@ mod web {return;}files::flush(&self.files);+ // A write to the computer's disk that failed: the design is not saved after all.+ for path in self.files.unsaved.borrow_mut().drain(..) {+ if self.app.session.path.as_deref() == Some(path.as_str()) {+ self.app.session.mark_unsaved();+ }+ }+ // Designs opened from the computer's disk (the files window): open them.+ let opened: Vec<_> = self.files.opened.borrow_mut().drain(..).collect();+ for path in opened {+ self.app.open_path(&path);+ self.files.panel.set(false);+ }for (text, error) in self.files.messages.borrow_mut().drain(..) {self.app.set_status(text, error);}@@ -224,6 +239,9 @@ mod web {act = Some(("download_open", String::new()));}});+ if !disk::supported() {+ ui.weak("This browser can't save to a folder: designs stay in this browser. Download design saves a file.");+ }ui.separator();if !self.files.ready.get() {ui.horizontal(|ui| {@@ -533,18 +551,33 @@ mod web {solidcraft_ui_egui::fonts::setup_fonts(&cc.egui_ctx);let files = Rc::new(Files::default());files::start(&files);- let panel = files.clone();+ let (panel, opener, saver, shown) = (files.clone(), files.clone(), files.clone(), files.clone());let services = Services {- // Open shows the browser's files (and the computer's, from there).- pick_open: Some(Box::new(move |_: &[&str]| {+ // Open shows the browser's open dialog for a design where it has one+ // (the file keeps its handle, so Save writes back to it); otherwise,+ // and for inserting STEP or meshes, the browser's files window.+ pick_open: Some(Box::new(move |exts: &[&str]| {+ if disk::handles_open(exts) {+ return Box::pin(disk::pick_open(&opener));+ }panel.panel.set(true);Box::pin(std::future::ready(None))})),- // Designs are kept in the browser; everything else is downloaded.- pick_save: Some(Box::new(|name: &str, exts: &[&str]| {+ // A design is saved to a file the user picks, or kept in the browser+ // where the browser can't pick one; everything else is downloaded.+ pick_save: Some(Box::new(move |name: &str, exts: &[&str]| {let design = exts.contains(&solidcraft_engine::io::DESIGN_EXT);- Box::pin(std::future::ready(Some(format!("{}{name}", if design { files::OPFS } else { files::DOWNLOADS }))))+ match disk::save_target(disk::supported(), design) {+ SaveTarget::Disk => Box::pin(disk::pick_save(&saver, name)),+ SaveTarget::Browser => {+ saver.say("This browser can't save to a folder: the design is kept in this browser. File > Download design saves a file.", false);+ Box::pin(std::future::ready(Some(format!("{}{name}", files::OPFS))))+ }+ SaveTarget::Download => Box::pin(std::future::ready(Some(format!("{}{name}", files::DOWNLOADS)))),+ }})),+ download_design: Some(Box::new(files::download)),+ browser_files: Some(Box::new(move || shown.panel.set(true))),install_app: Some(crate::install::service(&cc.egui_ctx)),..Default::default()};diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rsindex c4489c6fb1..d80917d73e 100644--- a/apps/solidcraft/src/main.rs+++ b/apps/solidcraft/src/main.rs@@ -210,6 +210,8 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services {http_download: Some(std::sync::Arc::new(http_download)),// Already an installed app: only the browser build offers to install.install_app: None,+ download_design: None,+ browser_files: None,agent_http: Some(std::sync::Arc::new(agent_http)),secrets: Some(std::sync::Arc::new(Keychain)),show_in_folder: Some(Box::new(|path| {diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 514331e985..5d3be9ce3b 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -304,6 +304,11 @@ pub struct Services {pub http_download: Option<update::install::HttpDownload>,/// The browser's offer to install the web app (`install`); None: no Install button (desktop).pub install_app: Option<install::InstallApp>,+ /// Hand a design's bytes to the user as a downloaded file (name, bytes); the browser build's+ /// File > Download design. None: the host saves real files, so there is nothing to offer.+ pub download_design: Option<Box<dyn Fn(&str, &[u8]) -> Result<(), String>>>,+ /// Show the designs the browser keeps for itself; None: the host has no such store.+ pub browser_files: Option<Box<dyn Fn()>>,/// HTTP for the agent chat's API agents (OpenAI-compatible endpoints); None: no API agents.pub agent_http: Option<agent_chat::backend::HttpFn>,/// The system keychain, for API agents' keys; None: keys can't be stored.diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rsindex e9650a9443..be868569ce 100644--- a/crates/ui-egui/src/toolbar.rs+++ b/crates/ui-egui/src/toolbar.rs@@ -522,6 +522,17 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) {save_as_with_extension(app, "json");close = true;}+ // The browser build: a copy as a downloaded file, whatever Save does.+ if app.services.download_design.is_some() && item_if(ui, "Download design", "", shown) {+ download_design(app);+ close = true;+ }+ if app.services.browser_files.is_some() && item(ui, "Files in this browser…", "") {+ if let Some(show) = &app.services.browser_files {+ show();+ }+ close = true;+ }ui.separator();if item_if(ui, "Save as mesh…", "", shown) {app.start("file.save_mesh");@@ -619,6 +630,20 @@ fn save_as_with_extension(app: &mut SolveApp, extension: &str) {});}+/// File > Download design (browser build): the open design as a `.solidcraft` file download.+fn download_design(app: &mut SolveApp) {+ let name = format!("{}.{}", app.session.doc.name, solidcraft_engine::io::DESIGN_EXT);+ let result = app+ .session+ .design_container(solidcraft_engine::io::DesignCompression::Fast, false, false)+ .map_err(|e| e.to_string())+ .and_then(|bytes| app.services.download_design.as_ref().map_or(Ok(()), |download| download(&name, &bytes)));+ match result {+ Ok(()) => app.set_status(format!("Downloaded {name}"), false),+ Err(e) => app.set_status(format!("Download design: {e}"), true),+ }+}+fn export(app: &mut SolveApp, ext: &str) {export_as(app, ext, None);}@@ -1486,6 +1511,29 @@ mod header_report_tests {assert!(!solidcraft_engine::io::is_design_container(&std::fs::read(saved).unwrap()), "subsequent Save keeps a .json choice");}+ /// The browser build's File > Download design hands the open design to the host as a+ /// `.solidcraft` container named after it; a host that saves real files shows no such item.+ #[test]+ fn file_menu_download_design_hands_the_container_to_the_host() {+ let mut h = crate::scenario::Harness::new();+ h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap();+ h.app.session.doc_mut().name = "Plate".into();+ let got = std::rc::Rc::new(std::cell::RefCell::new(Vec::<(String, Vec<u8>)>::new()));+ let sink = got.clone();+ h.app.services.download_design = Some(Box::new(move |name, bytes| {+ sink.borrow_mut().push((name.to_string(), bytes.to_vec()));+ Ok(())+ }));+ h.frames(3);+ h.step(&json!({"click":{"handle":"appbar:folder"}})).unwrap();+ h.step(&json!({"widget":"Download design"})).unwrap();+ let got = got.borrow();+ assert_eq!(got.len(), 1);+ assert_eq!(got[0].0, "Plate.solidcraft");+ assert!(solidcraft_engine::io::is_design_container(&got[0].1));+ assert!(h.app.session.path.is_none(), "a download is no save: the design keeps no file");+ }+fn sizes(buttons: &[usize]) -> Vec<PanelSize> {buttons.iter().map(|&b| PanelSize { buttons: b, labelled: false }).collect()}diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.mdindex ee253e6fa1..7a05dd98cf 100644--- a/docs/book/src/guide/files.md+++ b/docs/book/src/guide/files.md@@ -164,18 +164,25 @@ copy its properties; Save As keeps them. A command script of the design## Saving in the web app-In the web app, **Save** and **Save As** keep designs in this browser's private storage;-they do not open a dialog for choosing a folder on your computer. Clearing the site's data+In Chrome, Edge and Opera, **Save As** opens your browser's save dialog and writes the+`.solidcraft` file to the folder you choose, and **Open** opens the browser's open dialog.+**Save** then writes back to that same file. The browser remembers the file, so after you+reload the page the first **Save** asks once for permission to write to it, and carries on.+A design you open from your computer saves back to the file you opened.++In Firefox and Safari, which can't write to a folder, **Save** and **Save As** keep designs in+this browser's private storage instead, and the app says so. Clearing the site's datacan remove those designs. Download a copy to keep it outside the browser or move it toanother device.-1. Open the File menu and choose **Open** to show **Files in this browser**.-2. Choose **Download open design** for the current design, including its unsaved changes,- or **Download** beside a stored file for its last saved contents.-3. Find the `.solidcraft` file in your browser's downloads. Whether a folder chooser appears- depends on your browser's download settings.--Use **Open from computer…** in the same panel to reopen a downloaded design. The web app-works on a browser-stored copy; later saves do not update the original downloaded file.-Use **Rename** beside a stored file to change its name. Exports such as STEP and STL are-also downloaded.+To get a copy as a download in any browser, choose **File → Download design**. It holds the+current design, including its unsaved changes. In **File → Files in this browser…** (and in+Firefox and Safari, **File → Open**), **Download open design** does the same, and **Download**+beside a stored file gives its last saved contents. Whether a folder chooser appears depends+on your browser's download settings.++Use **Open from computer…** in the same window to open a design from your computer; where the+browser can write to a folder it saves back to that file, otherwise it works on a copy kept+in the browser. Use **Rename** beside a stored file to change its name. Autosave and recovery+stay in the browser's private storage in every browser. Exports such as STEP and STL are+downloaded.