From 857fb1e3d08aa8e4f8fdd21697809693e662cbb3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 22 Nov 2026 17:15:46 +0100 Subject: [PATCH] Save projects in the background and show progress --- crates/engine/src/bake/mesh_map_command.rs | 24 +-- crates/engine/src/file_cmds.rs | 165 +++++++++++++----- crates/engine/src/painting.rs | 3 +- crates/engine/src/path_tool.rs | 3 +- crates/engine/src/session.rs | 37 +++- crates/formats/src/project_file/mod.rs | 14 +- .../src/project_file/ram_reservation.rs | 12 +- .../formats/src/project_file/save_progress.rs | 69 ++++++++ crates/ui-egui/src/control.rs | 4 + crates/ui-egui/src/display_settings.rs | 3 +- crates/ui-egui/src/lib.rs | 29 ++- crates/ui-egui/src/manual_save.rs | 88 ++++++++++ crates/ui-egui/src/menus.rs | 4 + crates/ui-egui/src/shader_settings.rs | 3 +- crates/ui-egui/src/toolbar.rs | 5 + crates/ui-egui/src/windows.rs | 59 ++++--- crates/ui-egui/tests/it/file_dialogs.rs | 77 ++++++-- 17 files changed, 468 insertions(+), 131 deletions(-) create mode 100644 crates/formats/src/project_file/save_progress.rs create mode 100644 crates/ui-egui/src/manual_save.rs diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index fef27ea3..4e219bd1 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -56,7 +56,7 @@ pub(super) fn specs() -> Vec { cmd!("bake.cage.set", "Load cage mesh", [], None, "{path} — a mesh with the low poly's triangles", always, cage_set), cmd!("bake.cage.clear", "Remove cage mesh", [], None, "{}", always, |s, _| { s.bake_meshes.cage = None; - s.modified = true; + s.mark_modified(); Ok(meshes_json(s)) }), ] @@ -274,7 +274,7 @@ impl Session { for set in &mut self.doc.project.texture_sets { set.bake.high_poly.use_low_as_high = false; } - self.modified = true; + self.mark_modified(); Ok(name) } @@ -285,7 +285,7 @@ impl Session { } let removed = self.bake_meshes.high.remove(index); self.bake_meshes.rebuild(); - self.modified = true; + self.mark_modified(); Ok(removed) } @@ -303,7 +303,7 @@ impl Session { m.base_color.clear(); let name = m.name.clone(); self.bake_meshes.cage = Some(m); - self.modified = true; + self.mark_modified(); Ok(name) } @@ -347,20 +347,6 @@ impl Session { } } } - - pub(crate) fn saved_bake_paint(&self) -> BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData> { - self.doc - .bake_paint - .iter() - .map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() })) - .collect() - } - - /// The bake meshes for a project file: (high polys, cage). - pub(crate) fn saved_bake_meshes(&self) -> (Vec, Option) { - let entry = |m: &BakeMesh| (m.name.clone(), m.bytes.as_ref().clone()); - (self.bake_meshes.high.iter().map(entry).collect(), self.bake_meshes.cage.as_ref().map(entry)) - } } /// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`). @@ -392,7 +378,7 @@ fn high_remove(s: &mut Session, p: &Value) -> Result { if boolp(p, "all") == Some(true) { s.bake_meshes.high.clear(); s.bake_meshes.rebuild(); - s.modified = true; + s.mark_modified(); return Ok(meshes_json(s)); } let index = match (u64p(p, "index"), strp(p, "name")) { diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f493093b..fdc29bf1 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -16,6 +16,47 @@ use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p} use crate::session::{Document, Session}; use crate::{EngineError, Result, cmd}; +fn project_with_resources( + doc: &Document, + mesh: Option<&(String, Arc>)>, + bake_meshes: &crate::BakeMeshes, + resources: BTreeMap, +) -> ProjectFile { + let mut pixels = doc.pixels.clone(); + + // Drop pixel images whose size no longer matches their texture set + let size_of = |id: texturecraft_core::LayerId| { + doc.project.locate(id).and_then(|(ts, _, _)| doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| { + doc.project + .effect(id) + .and_then(|(owner, _)| doc.project.locate(owner)) + .and_then(|(ts, _, _)| doc.project.texture_sets.get(ts)) + .map(TextureSet::size) + }) + }; + pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height()))); + pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height()))); + + let bake_mesh = |mesh: &crate::BakeMesh| (mesh.name.clone(), mesh.bytes.as_ref().clone()); + let bake_paint = doc + .bake_paint + .iter() + .map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() })) + .collect(); + ProjectFile { + project: doc.project.clone(), + pixels, + baked: doc.baked.clone(), + mesh: mesh.map(|(extension, bytes)| (extension.clone(), bytes.as_ref().clone())), + high_poly: bake_meshes.high.iter().map(bake_mesh).collect(), + cage: bake_meshes.cage.as_ref().map(bake_mesh), + bake_paint, + thumbnail: None, + resources, + warnings: Vec::new(), + } +} + pub fn specs() -> Vec { vec![ cmd!( @@ -171,7 +212,7 @@ impl Session { // Packed mesh files can have spare capacity that the project would otherwise retain let mut source = bytes.into_owned(); source.shrink_to_fit(); - session.mesh_source = Some((extension, source)); + session.mesh_source = Some((extension, Arc::new(source))); session.doc.project.mesh_file = leaf_of(file_name); session.doc.project.cameras = imported.cameras; @@ -204,7 +245,7 @@ impl Session { }; check_materials(&pf.project, &mesh)?; - let source = pf.mesh.clone(); + let source = pf.mesh; let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect(); let mut s = Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?; @@ -220,44 +261,12 @@ impl Session { /// The project with independently owned resource bytes. pub fn project_file(&self) -> ProjectFile { let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect(); - self.project_with_resources(resources) + project_with_resources(&self.doc, self.mesh_source.as_ref(), &self.bake_meshes, resources) } /// A save snapshot that shares immutable resource payloads with the document. pub fn project_snapshot(&self) -> ProjectFile>> { - self.project_with_resources(self.doc.resources.clone()) - } - - fn project_with_resources(&self, resources: BTreeMap) -> ProjectFile { - let mut pixels = self.doc.pixels.clone(); - - // Drop pixel images whose size no longer matches their texture set - let size_of = |id: texturecraft_core::LayerId| { - self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| { - self.doc - .project - .effect(id) - .and_then(|(owner, _)| self.doc.project.locate(owner)) - .and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)) - .map(TextureSet::size) - }) - }; - pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height()))); - pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height()))); - - let (high_poly, cage) = self.saved_bake_meshes(); - ProjectFile { - project: self.doc.project.clone(), - pixels, - baked: self.doc.baked.clone(), - mesh: self.mesh_source.clone(), - high_poly, - cage, - bake_paint: self.saved_bake_paint(), - thumbnail: None, - resources, - warnings: Vec::new(), - } + project_with_resources(&self.doc, self.mesh_source.as_ref(), &self.bake_meshes, self.doc.resources.clone()) } pub fn to_project_bytes(&self) -> Result> { @@ -449,6 +458,7 @@ fn plan(session: &mut Session, params: &Value) -> Result { mod native { use super::*; use std::path::Path; + use texturecraft_formats::project_file::SaveProgress; pub fn path_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> { strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required"))) @@ -484,21 +494,82 @@ mod native { } pub fn save_to(s: &mut Session, path: &str, adopt: bool) -> Result { - let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") }; - let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?; - reservation.save(Path::new(&path), &s.project_snapshot()).map_err(fe)?; + let output = s.save_task(path, adopt).run(None)?; + output.apply(s); + Ok(json!({ "path": output.path })) + } - if adopt { - s.path = Some(path.clone()); - s.modified = false; + struct SaveTarget { + project_id: u64, + revision: u64, + adopt: bool, + path: String, + } + + /// A manual save of the document at the moment it was requested. Large payloads are shared + /// until the worker assembles the archive. + pub struct SaveTask { + target: SaveTarget, + doc: Document, + mesh: Option<(String, Arc>)>, + bake_meshes: crate::BakeMeshes, + } + + impl Session { + pub fn save_task(&self, path: &str, adopt: bool) -> SaveTask { + let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") }; + SaveTask { + target: SaveTarget { project_id: self.project_id, revision: self.save_revision, adopt, path }, + doc: self.doc.clone(), + mesh: self.mesh_source.clone(), + bake_meshes: self.bake_meshes.clone(), + } + } + } + + impl SaveTask { + /// Complete the atomic write on the worker. Waiting for a previous save to release the + /// RAM allowance also happens here. + pub fn run(self, progress: Option<&SaveProgress>) -> Result { + let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?; + let snapshot = project_with_resources(&self.doc, self.mesh.as_ref(), &self.bake_meshes, self.doc.resources.clone()); + let path = Path::new(&self.target.path); + match progress { + Some(progress) => reservation.save_with_progress(path, &snapshot, progress), + None => reservation.save(path, &snapshot), + } + .map_err(fe)?; + Ok(SaveOutput { path: self.target.path, project_id: self.target.project_id, revision: self.target.revision, adopt: self.target.adopt }) + } + } + + /// An archive that was written successfully. Only the same project can adopt its path. + pub struct SaveOutput { + pub path: String, + project_id: u64, + revision: u64, + adopt: bool, + } + + impl SaveOutput { + /// Apply the saved path without clearing edits made since the snapshot. + pub fn apply(&self, session: &mut Session) { + if session.project_id != self.project_id { + return; + } + if self.adopt { + session.path = Some(self.path.clone()); + if session.save_revision == self.revision && !session.stroke_active() { + session.modified = false; + } + } + session.log.info("Project", format!("Saved {}", self.path)); } - s.log.info("Project", format!("Saved {path}")); - Ok(json!({ "path": path })) } } #[cfg(not(target_arch = "wasm32"))] -pub use native::{absolute, open_path, read_mesh}; +pub use native::{SaveOutput, SaveTask, absolute, open_path, read_mesh}; /// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the /// mesh file `mesh`, remembering its path for Reimport mesh. @@ -597,7 +668,7 @@ impl Session { let (mesh, source, warnings, mesh_file) = match file { Some(f) => { let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh; - (m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name)) + (m, Some((ext_of(&f.name), Arc::new(f.bytes))), f.warnings, leaf_of(&f.name)) } None => match &self.mesh_source { Some((ext, bytes)) => { @@ -612,7 +683,7 @@ impl Session { doc.project.mesh = format!("mesh.{ext}"); doc.project.mesh_file = mesh_file; } - let mut next = Session::new(doc, mesh, source)?; + let mut next = Session::new_with_source(doc, mesh, source)?; next.log.warnings("Importer", warnings); next.path = self.path.clone(); next.sync_images(); diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 62010b50..9ca5836a 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -576,8 +576,7 @@ impl Session { self.undo.remove(0); } self.redo.clear(); - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); // The live preview already shows the committed result: the stroke's tiles recomposite // from the committed pixels at low priority, without holding up this frame. self.mark_settle(st.ts, st.target, st.canvas.dirty.iter().copied()); diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 5398501f..63d047b2 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -922,8 +922,7 @@ impl Session { } else { self.invalidate_changed(&before); } - self.revision = self.revision.wrapping_add(1); - self.modified = true; + self.mark_modified(); Ok((painted, before)) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index b493a8b6..4f2c8b77 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -418,7 +418,7 @@ pub struct Session { pub(crate) source: Arc, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. - pub mesh_source: Option<(String, Vec)>, + pub mesh_source: Option<(String, Arc>)>, /// High-definition meshes and cage for baking (saved inside the project). pub bake_meshes: crate::BakeMeshes, pub caches: Vec, @@ -467,6 +467,9 @@ pub struct Session { /// (see [`crate::commands::check_enabled`]). pub project_open: bool, pub modified: bool, + /// Edits to saved data, independent of viewport and tool changes. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) save_revision: u64, /// Bumps on every document change. pub revision: u64, /// Messages for the UI (status bar / toasts). @@ -492,6 +495,10 @@ pub struct Session { impl Session { /// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`]) pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec)>) -> Result { + Self::new_with_source(doc, mesh, mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes)))) + } + + pub(crate) fn new_with_source(doc: Document, mesh: Mesh, mesh_source: Option<(String, Arc>)>) -> Result { mesh.validate().map_err(|error| EngineError::Other(error.to_string()))?; let source = Arc::new(mesh); @@ -539,6 +546,8 @@ impl Session { path: None, project_open: true, modified: false, + #[cfg(not(target_arch = "wasm32"))] + save_revision: 0, revision: 1, log: crate::log::SessionLog::new(), log_id: next_mesh_id(), @@ -567,6 +576,10 @@ impl Session { pub fn switch_to(&mut self, mut next: Session) { // Invalidate caches even when both projects were loaded with the same revision next.revision = self.revision.wrapping_add(1); + #[cfg(not(target_arch = "wasm32"))] + { + next.save_revision = self.save_revision.wrapping_add(1); + } next.viewport = self.viewport; next.export_presets = std::mem::take(&mut self.export_presets); @@ -711,8 +724,7 @@ impl Session { self.path_steps = Default::default(); } - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) { self.undo.push((label.to_string(), before)); } @@ -723,8 +735,7 @@ impl Session { /// A change from `other` to the current document that is not an undo step (a path preview) pub(crate) fn changed_without_history(&mut self, other: &Document) { - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); self.invalidate_changed(other); } @@ -835,14 +846,23 @@ impl Session { /// Mark the document changed and every texture set dirty. pub fn touched(&mut self) { - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); self.sync_caches(); for c in &mut self.caches { c.invalidate_all(); } } + /// Mark saved data changed without invalidating the texture sets. + pub fn mark_modified(&mut self) { + self.modified = true; + self.revision = self.revision.wrapping_add(1); + #[cfg(not(target_arch = "wasm32"))] + { + self.save_revision = self.save_revision.wrapping_add(1); + } + } + /// Make caches agree with the project's texture sets (resolution or channel changes). pub fn sync_caches(&mut self) { let sets = self.doc.project.texture_sets.clone(); @@ -953,11 +973,10 @@ impl Session { fn after_history(&mut self, other: &Document) { // Pending operations may still hold layer IDs from the discarded snapshot self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id); - self.modified = true; + self.mark_modified(); // Layers picked together belong to the stack they were picked in self.multi.clear(); - self.revision = self.revision.wrapping_add(1); self.invalidate_changed(other); // An undone add or duplicate takes the selected effect away diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index c5bf3bdb..06a504ca 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -38,10 +38,12 @@ mod load_budget; mod project_open_limit; mod ram_operation; mod ram_reservation; +mod save_progress; #[cfg(not(target_arch = "wasm32"))] pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, configured_ram_budget, save_ram_budget, set_save_resources}; pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; pub use ram_reservation::RamReservation; +pub use save_progress::SaveProgress; const KIND: &str = "project file"; #[cfg(test)] @@ -109,11 +111,11 @@ pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Resul } #[cfg(not(target_arch = "wasm32"))] -fn write_project_atomic(path: &std::path::Path, project_file: &ProjectFile>>) -> Result<()> { +fn write_project_atomic(path: &std::path::Path, project_file: &ProjectFile>>, progress: Option<&SaveProgress>) -> Result<()> { let (temporary_path, file) = crate::create_temp(path)?; let result = (|| -> Result<()> { let mut file = std::io::BufWriter::new(file); - write_project(&mut file, project_file)?; + write_project(&mut file, project_file, progress)?; file.into_inner().map_err(|error| error.into_error())?.sync_all()?; std::fs::rename(&temporary_path, path)?; Ok(()) @@ -276,9 +278,13 @@ fn entries(pf: &ProjectFile>>) -> Result>> { Ok(out) } -fn write_project(out: W, pf: &ProjectFile>>) -> Result<()> { +fn write_project(out: W, pf: &ProjectFile>>, progress: Option<&SaveProgress>) -> Result<()> { let mut zip = ZipWriter::new(out); - entries::write_entries(&mut zip, entries(pf)?)?; + let mut entries = entries(pf)?; + if let Some(progress) = progress { + progress.track(&mut entries); + } + entries::write_entries(&mut zip, entries)?; zip.finish().map_err(zip_err)?; Ok(()) } diff --git a/crates/formats/src/project_file/ram_reservation.rs b/crates/formats/src/project_file/ram_reservation.rs index 72857c15..caff4af1 100644 --- a/crates/formats/src/project_file/ram_reservation.rs +++ b/crates/formats/src/project_file/ram_reservation.rs @@ -2,6 +2,8 @@ use std::borrow::Borrow; use std::io::Cursor; use std::sync::{Condvar, Mutex}; +#[cfg(not(target_arch = "wasm32"))] +use super::SaveProgress; use super::{ProjectFile, ram_operation::RamOperation, write_project}; use crate::{FormatError, Result}; @@ -57,14 +59,20 @@ impl RamReservation { pub fn save_bytes(&mut self, project_file: &ProjectFile>>) -> Result> { self.check_save()?; let mut out = Cursor::new(Vec::new()); - write_project(&mut out, project_file)?; + write_project(&mut out, project_file, None)?; Ok(out.into_inner()) } #[cfg(not(target_arch = "wasm32"))] pub fn save(&mut self, path: &std::path::Path, project_file: &ProjectFile>>) -> Result<()> { self.check_save()?; - super::write_project_atomic(path, project_file) + super::write_project_atomic(path, project_file, None) + } + + #[cfg(not(target_arch = "wasm32"))] + pub fn save_with_progress(&mut self, path: &std::path::Path, project_file: &ProjectFile>>, progress: &SaveProgress) -> Result<()> { + self.check_save()?; + super::write_project_atomic(path, project_file, Some(progress)) } fn check_save(&self) -> Result<()> { diff --git a/crates/formats/src/project_file/save_progress.rs b/crates/formats/src/project_file/save_progress.rs new file mode 100644 index 00000000..4e7c1810 --- /dev/null +++ b/crates/formats/src/project_file/save_progress.rs @@ -0,0 +1,69 @@ +use std::io::{self, Write}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::entries::Entry; + +/// Estimated archive progress, based on the payload processed by the entry writers. +/// Completing the archive, syncing it to disk, and replacing the destination can take longer. +#[derive(Default)] +pub struct SaveProgress { + total: AtomicU64, + processed: AtomicU64, +} + +impl SaveProgress { + pub fn fraction(&self) -> f32 { + let total = self.total.load(Ordering::Relaxed); + if total == 0 { + return 0.0; + } + let processed = self.processed.load(Ordering::Relaxed).min(total); + // Leave room for the final write and atomic replacement. + 0.95 * (processed as f64 / total as f64) as f32 + } + + pub(super) fn track<'a>(&'a self, entries: &mut [Entry<'a>]) { + self.processed.store(0, Ordering::Relaxed); + self.total.store(entries.iter().fold(0u64, |sum, entry| sum.saturating_add(entry.weight)), Ordering::Relaxed); + for entry in entries { + let body = std::mem::replace(&mut entry.body, Box::new(|_| Ok(()))); + let remaining = entry.weight; + entry.body = Box::new(move |target| { + let mut writer = ProgressWriter { target, progress: self, remaining, pending: 0 }; + body(&mut writer)?; + writer.report(); + Ok(()) + }); + } + } +} + +struct ProgressWriter<'a> { + target: &'a mut dyn Write, + progress: &'a SaveProgress, + remaining: u64, + pending: u64, +} + +impl ProgressWriter<'_> { + fn report(&mut self) { + self.progress.processed.fetch_add(std::mem::take(&mut self.pending), Ordering::Relaxed); + } +} + +impl Write for ProgressWriter<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + let written = self.target.write(bytes)?; + let counted = (written as u64).min(self.remaining); + self.remaining -= counted; + self.pending += counted; + if self.pending >= 64 << 10 { + self.report(); + } + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + self.target.flush() + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6b471ff5..6e999d7d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -141,6 +141,10 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para }, "command.run" => { let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") }; + #[cfg(not(target_arch = "wasm32"))] + if app.save_job.is_some() && crate::manual_save::is_save(id) { + return err("A manual project save is already running"); + } let command_params = params.get("params").cloned().unwrap_or(Value::Null); let before = app.session.camera; match texturecraft_engine::execute(&mut app.session, id, &command_params) { diff --git a/crates/ui-egui/src/display_settings.rs b/crates/ui-egui/src/display_settings.rs index 7c0bc14d..6a8e56b2 100644 --- a/crates/ui-egui/src/display_settings.rs +++ b/crates/ui-egui/src/display_settings.rs @@ -57,8 +57,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } app.session.doc.project.display = display; - app.session.modified = true; - app.session.revision = app.session.revision.wrapping_add(1); + app.session.mark_modified(); } if import_hdr { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1a8508eb..f6b25860 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -50,6 +50,8 @@ mod levels_properties; mod line_snap; mod list_action; pub mod log_panel; +#[cfg(not(target_arch = "wasm32"))] +mod manual_save; mod mask_preview_image; mod material_preview_image; pub mod menus; @@ -189,6 +191,7 @@ pub struct Toast { pub error: bool, pub until: f64, pub show_log: bool, + announce: bool, } pub struct TextureCraftApp { @@ -267,10 +270,13 @@ pub struct TextureCraftApp { /// Native file dialogs and their continuations (desktop only). #[cfg(not(target_arch = "wasm32"))] pub file_dialogs: file_dialogs::FileDialogs, - /// The unsaved-changes dialog's Save is waiting on the Save dialog's answer. + /// A manual save running on the desktop archive writer. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) save_job: Option, + /// The unsaved-changes dialog's Save is waiting for a path or a save result. #[cfg(not(target_arch = "wasm32"))] pub(crate) saving_for_prompt: bool, - /// That Save dialog saved the project; the prompt goes on at its next frame. + /// The requested save completed; the prompt goes on at its next frame. #[cfg(not(target_arch = "wasm32"))] pub(crate) prompt_saved: bool, /// The resolved keymap and its key dispatcher. @@ -364,6 +370,8 @@ impl TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), #[cfg(not(target_arch = "wasm32"))] + save_job: None, + #[cfg(not(target_arch = "wasm32"))] saving_for_prompt: false, #[cfg(not(target_arch = "wasm32"))] prompt_saved: false, @@ -504,13 +512,13 @@ impl TextureCraftApp { } pub fn toast(&mut self, text: impl Into, error: bool) { - self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false }); + self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, announce: false }); } /// An error toast that stays until the user dismisses it (for a problem that persists and /// is reported once, like a texture set the GPU could not hold). pub fn toast_sticky(&mut self, text: impl Into) { - self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false }); + self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, announce: false }); } /// Start baking texture sets in the background, one after another. Invalid set indices @@ -871,6 +879,9 @@ impl TextureCraftApp { /// and written on a worker thread; the project data is shared copy-on-write). #[cfg(not(target_arch = "wasm32"))] fn autosave(&mut self, now: f64) { + if self.save_job.is_some() { + return; + } let period = autosave_period_seconds(self.ui.prefs.autosave_minutes); // The clock starts at the first unsaved change @@ -1023,7 +1034,10 @@ impl eframe::App for TextureCraftApp { ctx.set_zoom_factor(scale); } #[cfg(not(target_arch = "wasm32"))] - self.autosave(now); + { + self.poll_save(ctx); + self.autosave(now); + } i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] { @@ -1198,7 +1212,10 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| { ui.set_max_width(width); - ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap()); + let label = ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap()); + if t.announce { + ui.ctx().accesskit_node_builder(label.id, |node| node.set_live(egui::accesskit::Live::Polite)); + } }); if t.show_log && ui.link(i18n::tr("Open Log")).clicked() { show_log = true; diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs new file mode 100644 index 00000000..c2481678 --- /dev/null +++ b/crates/ui-egui/src/manual_save.rs @@ -0,0 +1,88 @@ +//! Manual desktop saves share the atomic archive writer with autosave and headless saves. + +use std::sync::{Arc, mpsc}; +use std::time::Duration; + +use texturecraft_engine::{Result, file_cmds::SaveOutput, formats::project_file::SaveProgress}; + +use crate::{ + TextureCraftApp, + i18n::{tr, trf}, +}; + +pub(crate) struct SaveJob { + progress: Arc, + output: mpsc::Receiver>, + project_id: u64, + for_prompt: bool, + remember: bool, + pub(crate) quit_after_save: bool, +} + +pub(crate) fn is_save(id: &str) -> bool { + matches!(id, "file.save" | "file.saveAs" | "file.saveCopy") +} + +impl TextureCraftApp { + pub(crate) fn start_save(&mut self, path: &str, adopt: bool, for_prompt: bool, remember: bool) -> bool { + if self.save_job.is_some() { + self.toast(tr("A project save is already running"), true); + return false; + } + if let Err(error) = self.session.end_stroke() { + self.toast(error.to_string(), true); + return false; + } + + let task = self.session.save_task(path, adopt); + let progress = Arc::new(SaveProgress::default()); + let worker_progress = progress.clone(); + let output = crate::spawn_worker("texturecraft-save", move || task.run(Some(&worker_progress))); + self.save_job = Some(SaveJob { progress, output, project_id: self.session.project_id, for_prompt, remember, quit_after_save: false }); + true + } + + pub(crate) fn save_progress(&self) -> Option { + self.save_job.as_ref().map(|job| job.progress.fraction()) + } + + pub(crate) fn poll_save(&mut self, ctx: &egui::Context) { + let Some(job) = &self.save_job else { return }; + let result = match job.output.try_recv() { + Ok(result) => result.map_err(|error| error.to_string()), + Err(mpsc::TryRecvError::Empty) => { + ctx.request_repaint_after(Duration::from_millis(80)); + return; + } + Err(mpsc::TryRecvError::Disconnected) => Err(tr("The project save worker stopped").into()), + }; + let Some(job) = self.save_job.take() else { return }; + let same_project = job.project_id == self.session.project_id; + let continue_prompt = job.for_prompt && self.saving_for_prompt; + if job.for_prompt { + self.saving_for_prompt = false; + } + + match result { + Ok(output) => { + output.apply(&mut self.session); + if job.remember { + crate::windows::remember(self, &output.path); + } + self.prompt_saved = continue_prompt && same_project && !self.session.modified && !self.session.stroke_active(); + self.toast(trf("Saved {path}", &[("path", &output.path)]), false); + if job.quit_after_save && same_project { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + Err(error) => { + let message = trf("Could not save project: {error}", &[("error", &error)]); + self.session.log.warn("Project", message.clone()); + self.toast(message, true); + } + } + if let Some(toast) = self.toasts.last_mut() { + toast.announce = true; + } + } +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 7ec42c75..8aea36c1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -175,6 +175,10 @@ fn tooltip_of(id: &str) -> Option<&'static str> { /// Whether an item can run now pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { + #[cfg(not(target_arch = "wasm32"))] + if app.save_job.is_some() && crate::manual_save::is_save(id) { + return false; + } if UNAVAILABLE.contains(&id) { return false; } diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs index ba00a046..88dd9ae4 100644 --- a/crates/ui-egui/src/shader_settings.rs +++ b/crates/ui-egui/src/shader_settings.rs @@ -77,8 +77,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if display != app.session.doc.project.display { app.session.doc.project.display = display; - app.session.modified = true; - app.session.revision = app.session.revision.wrapping_add(1); + app.session.mark_modified(); } } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index dc2f3453..a28a5360 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -536,6 +536,11 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { .frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(10, 0))) .show(ui, |ui| { ui.horizontal_centered(|ui| { + #[cfg(not(target_arch = "wasm32"))] + if let Some(progress) = app.save_progress() { + ui.add(egui::ProgressBar::new(progress).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Saving project")).size(10.0))); + ui.separator(); + } if let Some(p) = app.bake_progress() { ui.add(egui::ProgressBar::new(p).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Baking")).size(10.0))); if ui.small_button(tr("Cancel")).clicked() { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0624e1be..8473de9a 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -92,7 +92,19 @@ pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) { { app.toast(error.to_string(), true); } - if closing && ask_to_save(app, crate::state::Unsaved::Quit) { + #[cfg(not(target_arch = "wasm32"))] + let waiting_for_save = if closing + && !app.session.modified + && let Some(job) = &mut app.save_job + { + job.quit_after_save = true; + true + } else { + false + }; + #[cfg(target_arch = "wasm32")] + let waiting_for_save = false; + if closing && (waiting_for_save || ask_to_save(app, crate::state::Unsaved::Quit)) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); if ctx.input(|i| i.viewport().minimized == Some(true)) { ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); @@ -110,7 +122,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(pending) = app.ui.windows.unsaved.clone() else { return }; #[cfg(not(target_arch = "wasm32"))] - let (waiting_for_save, saved_by_dialog) = (app.saving_for_prompt, std::mem::take(&mut app.prompt_saved)); + let (waiting_for_save, saved_by_dialog) = (app.saving_for_prompt || app.save_job.is_some(), std::mem::take(&mut app.prompt_saved)); #[cfg(target_arch = "wasm32")] let (waiting_for_save, saved_by_dialog) = (false, false); @@ -129,7 +141,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { // One row keeps the window to its contents; a bare right-to-left layout fills the screen height ui.horizontal(|ui| { - // The answers wait while the Save dialog is open + // Wait for the path picker or an active save to finish. ui.add_enabled_ui(!waiting_for_save, |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add(primary_button(ui, tr("Save"))).clicked() { @@ -156,11 +168,13 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { let discard_after_create = matches!(pending, Unsaved::CreateProject(_)) && save_first == Some(false) && app.session.modified; match save_first { Some(true) => { - // An untitled project is saved from a dialog that answers on a later frame #[cfg(not(target_arch = "wasm32"))] { - app.saving_for_prompt = app.session.path.is_none(); + app.saving_for_prompt = true; + file_action(app, ctx, "file.save"); + return; } + #[cfg(target_arch = "wasm32")] file_action(app, ctx, "file.save"); } // Going ahead anyway: the changes are let go @@ -484,15 +498,16 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> }); true } - "file.save" if app.session.path.is_some() => { - if let Some(result) = app.run("file.save", json!({})) { - let saved_path = result["path"].as_str().unwrap_or_default(); - app.toast(trf("Saved {path}", &[("path", &saved_path)]), false); - } - true - } "file.save" | "file.saveAs" => { - ask_save_project(app, "file.saveAs"); + if id == "file.save" + && let Some(path) = app.session.path.clone() + { + if !app.start_save(&path, true, app.saving_for_prompt, false) { + app.saving_for_prompt = false; + } + } else { + ask_save_project(app, "file.saveAs"); + } true } "file.saveCopy" => { @@ -568,7 +583,7 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } } -/// Asks where to save the project and runs `cmd` with the answer. Each caller is its own dialog +/// Asks where to save the project and starts the worker with the answer. Each caller is its own dialog /// request, so Save As and Save a Copy queue separately. #[cfg(not(target_arch = "wasm32"))] #[track_caller] @@ -578,19 +593,11 @@ fn ask_save_project(app: &mut TextureCraftApp, cmd: &'static str) { // Save a Copy leaves the project unsaved, so it never answers the unsaved-changes prompt. let for_prompt = app.saving_for_prompt && cmd == "file.saveAs"; let asked = app.ask_file(dialog, Bound::Project, move |app, paths| { - let mut saved = false; - if let Some(p) = paths.first() { - let path = p.display().to_string(); - saved = app.run(cmd, json!({"path": path})).is_some(); - if saved { - remember(app, &path); - app.toast(trf("Saved {path}", &[("path", &path)]), false); - } - } - // The answer ends the wait. A canceled or failed save leaves the prompt open for an answer. - if for_prompt { + let for_prompt = for_prompt && app.saving_for_prompt; + let started = paths.first().is_some_and(|p| app.start_save(&p.display().to_string(), cmd != "file.saveCopy", for_prompt, true)); + // Canceled dialogs and failures leave the prompt open for another answer. + if for_prompt && !started { app.saving_for_prompt = false; - app.prompt_saved = saved && !app.session.modified; } }); // A Save As already on its way answers for itself: the prompt's buttons stay usable. diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index a8876e9e..d9ff167b 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -1,6 +1,7 @@ //! Native file dialogs answer on a later frame; the tests answer them without a window. use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; use egui::{ViewportCommand, ViewportEvent, ViewportId}; use egui_kittest::Harness; @@ -10,6 +11,8 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; use texturecraft_ui_egui::state::Unsaved; +use super::temp_dir::TempDir; + fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; @@ -198,7 +201,7 @@ fn a_mesh_change_keeps_the_answer_for_the_same_project() { answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); invoke(&mut h, "file.saveAs"); h.state_mut().session.mesh_id += 1; - h.run_steps(3); + wait_for(&mut h, |h| h.state().session.path.as_deref() == file.to_str()); assert!(file.exists(), "a reimport or a UV layout change is still the same project"); } @@ -217,6 +220,15 @@ fn sends(h: &mut Harness<'_, TextureCraftApp>, frames: usize, cmd: &ViewportComm }) } +fn wait_for(h: &mut Harness<'_, TextureCraftApp>, ready: impl Fn(&Harness<'_, TextureCraftApp>) -> bool) { + let deadline = Instant::now() + Duration::from_secs(10); + while !ready(h) { + assert!(Instant::now() < deadline, "save did not finish"); + h.step(); + std::thread::yield_now(); + } +} + fn untitled_with_prompt(h: &mut Harness<'_, TextureCraftApp>) { h.state_mut().session.path = None; request_close(h); @@ -236,16 +248,61 @@ fn closing_during_a_stroke_finishes_it_and_asks() { #[test] fn save_in_the_prompt_goes_on_once_the_dialog_has_saved() { - let file = temp_file("prompt-save", "saved.tcraft"); + let temp = TempDir::new("prompt-save"); + for untitled in [true, false] { + let file = temp.join(if untitled { "new.tcraft" } else { "existing.tcraft" }); + let mut h = harness(true); + h.state_mut().session.path = (!untitled).then(|| file.display().to_string()); + request_close(&mut h); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + h.get_by_label("Save").click(); + wait_for(&mut h, |h| h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close))); + assert!(file.exists()); + assert!(!h.state().session.modified); + assert!(h.state().ui.windows.unsaved.is_none()); + } +} + +#[test] +fn a_background_save_preserves_edits_made_while_the_file_is_written() { + let temp = TempDir::new("save-edits"); + let file = temp.join("project.tcraft"); let mut h = harness(true); - untitled_with_prompt(&mut h); - let path = file.clone(); - answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); - h.get_by_label("Save").click(); - assert!(sends(&mut h, 5, &ViewportCommand::Close), "the close goes on after the save"); - assert!(file.exists()); - assert!(!h.state().session.modified); - assert!(h.state().ui.windows.unsaved.is_none()); + h.state_mut().session.path = Some(file.display().to_string()); + let original = h.state().session.doc.project.texture_sets[0].name.clone(); + invoke(&mut h, "file.save"); + assert!(!texturecraft_ui_egui::menus::enabled(h.state(), "file.save"), "the save returns with a worker still to collect"); + let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"})); + assert!(rename.is_some(), "editing remains available"); + + wait_for(&mut h, |h| texturecraft_ui_egui::menus::enabled(h.state(), "file.save")); + let saved = texturecraft_engine::formats::load_project(&file).unwrap(); + assert_eq!(saved.project.texture_sets[0].name, original, "the first save writes the snapshot it started with"); + assert_eq!(h.state().session.doc.project.texture_sets[0].name, "Edited while saving"); + assert!(h.state().session.modified, "the later edit still needs to be saved"); + + invoke(&mut h, "file.save"); + h.state_mut().run("camera.view.front", serde_json::Value::Null); + wait_for(&mut h, |h| texturecraft_ui_egui::menus::enabled(h.state(), "file.save")); + let saved = texturecraft_engine::formats::load_project(&file).unwrap(); + assert_eq!(saved.project.texture_sets[0].name, "Edited while saving"); + assert!(!h.state().session.modified, "moving the camera alone does not create an unsaved edit"); +} + +#[test] +fn a_failed_background_save_keeps_the_project_and_its_path() { + let temp = TempDir::new("save-failure"); + let file = temp.join("current.tcraft"); + let missing_parent = temp.join("missing").join("as.tcraft"); + let mut h = harness(true); + h.state_mut().session.path = Some(file.display().to_string()); + answer(&mut h, move |_| Answer::Paths(vec![missing_parent.clone()])); + invoke(&mut h, "file.saveAs"); + wait_for(&mut h, |h| h.state().toasts.iter().any(|toast| toast.error)); + assert!(h.state().session.modified); + assert_eq!(h.state().session.path.as_deref(), file.to_str()); + assert!(texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs")); } #[test]