diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 9d2d9a4a33..f4cef9bec8 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -258,7 +258,17 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; // Never a half-written file: see [`write_atomic`]. - write_atomic(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e)) +} + +/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the +/// file was put in place ([`vectorcraft_format::write_atomic_with`]), otherwise the path and the reason. +#[cfg(not(target_arch = "wasm32"))] +fn write_error(path: &str, error: std::io::Error) -> EngineError { + if error.get_ref().is_some_and(|e| e.is::()) { + return EngineError::Cancelled; + } + EngineError::Other(format!("{path}: {error}")) } /// [`write_file`] with what `fill` writes into the file (a save streamed into it). @@ -266,7 +276,7 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e)) } /// The save commands' writer: preserves a filesystem location refusal as a typed error. Other @@ -285,8 +295,10 @@ pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::W #[cfg(not(target_arch = "wasm32"))] pub(super) fn save_write_error(path: &str, error: std::io::Error) -> EngineError { - let reason = format!("{path}: {error}"); - if vectorcraft_format::read_only_location(&error) { EngineError::ReadOnlyLocation(reason) } else { EngineError::Other(reason) } + if !vectorcraft_format::read_only_location(&error) { + return write_error(path, error); + } + EngineError::ReadOnlyLocation(format!("{path}: {error}")) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 09b7924442..b603859ef1 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -629,6 +629,24 @@ impl std::io::Write for Counted { } } +/// A writer that fails once the work running on this thread is canceled +/// ([`crate::cancel::is_cancelled`]), so a streamed save stops writing into its temporary file. +/// It sits under the stream's buffer: it is checked once per buffer written, not per write. +struct StopsWhenCancelled(W); + +impl std::io::Write for StopsWhenCancelled { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if crate::cancel::is_cancelled() { + return Err(std::io::Error::other(crate::cancel::Cancelled)); + } + self.0.write(buf) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.0.flush() + } +} + /// The artboards a native or `.ai` save also writes to files of their own: with /// `separateArtboards`, those `range` names (default all). fn separate_boards(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result> { @@ -1022,10 +1040,15 @@ impl SaveJob { } /// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in - /// order: when `stop` returns a value, nothing is written and that value is returned. + /// order: when `stop` returns a value, nothing is written and that value is returned. Work + /// canceled ([`crate::cancel`]) before the first file is written returns + /// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the + /// others are written too. pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let (plan, doc) = (&self.plan, &*self.doc); + crate::cancel::check()?; let enc = self.encode()?; + crate::cancel::check()?; let extra = json!({ "format": plan.format.id, "warnings": enc.notes() }); let Some(path) = &plan.path else { let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?; @@ -1042,8 +1065,13 @@ impl SaveJob { if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::>()) { return Ok(stopped); } - for (p, bytes) in &files { - write(p, bytes)?; + for (i, (p, bytes)) in files.iter().enumerate() { + if i == 0 { + write(p, bytes)?; + } else { + // Once a file is in place, a Cancel no longer stops the save: the set is written whole. + crate::cancel::scope(&crate::cancel::CancelToken::new(), None, || write(p, bytes))?; + } } let bytes = files.first().map_or(0, |f| f.1.len()); let mut out = super::merge(json!({ "path": path, "bytes": bytes }), extra); @@ -1066,11 +1094,15 @@ impl SaveJob { /// [`SaveJob::write`] through `stream`, which writes the file at a path with what the filler /// it is given writes (atomically, as [`vectorcraft_format::write_atomic_with`]). A native /// file goes into it as it is encoded ([`SaveJob::streams`]), never held whole in memory; - /// other files are encoded first, then written into it. + /// other files are encoded first, then written into it. Work canceled ([`crate::cancel`]) + /// while the native file is encoded, or before its filler returns, returns + /// [`crate::EngineError::Cancelled`]: the filler fails, so `stream` keeps the file as it was + /// (the atomic writer checks once more before it puts the file in place). pub fn write_streamed(&self, stream: StreamWrite) -> Result { let (Some(path), true) = (&self.plan.path, self.streams()) else { return self.write(|p, b| stream(p, &mut |w| w.write_all(b))); }; + crate::cancel::check()?; let (cmd, f) = (self.plan.mode.command(), self.plan.format); let doc = self.doc.without_edit_modes(); let doc = match f.id { @@ -1087,16 +1119,22 @@ impl SaveJob { let mut failed = None; let mut written = 0u64; let mut fill = |w: &mut dyn std::io::Write| { - let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, w), n: 0 }; + let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, StopsWhenCancelled(w)), n: 0 }; let r = super::native::encode_to(cmd, f, &doc, &self.params, &mut out); written = out.n; - match r { + let r = match r { Ok(()) => out.inner.flush(), Err(e) => { failed = Some(e); Err(std::io::Error::other("the file couldn't be encoded")) } + }; + // The last check before the file is replaced: a canceled save leaves it as it was. + if crate::cancel::is_cancelled() { + failed = Some(crate::EngineError::Cancelled); + return Err(std::io::Error::other(crate::cancel::Cancelled)); } + r }; let r = stream(path, &mut fill); r.map_err(|e| failed.take().unwrap_or(e))?; diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index bbf6883834..40a0159303 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -922,6 +922,109 @@ fn a_save_that_fails_while_streaming_leaves_the_file_as_it_was() { let _ = std::fs::remove_dir_all(&d); } +/// A save canceled (Background Save's Cancel) before it starts, while a native file streams into +/// its temporary file, or after the last byte went into it, fails with `Cancelled` and leaves the +/// file as it was, with no temporary file behind. A file encoded first is never written. +#[test] +fn a_canceled_save_leaves_the_file_as_it_was() { + /// Passes every write on, and cancels the save after the first one. + struct CancelAfterFirst<'a> { + inner: &'a mut dyn std::io::Write, + token: crate::cancel::CancelToken, + } + impl std::io::Write for CancelAfterFirst<'_> { + fn write(&mut self, b: &[u8]) -> std::io::Result { + let n = self.inner.write(b)?; + self.token.cancel(); + Ok(n) + } + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } + } + let d = tmp_dir("stream-cancel"); + // A small document's file goes in one piece; a large one's in several. + for count in [1, 1500] { + let mut s = session(2000.0, 2000.0, 1); + for i in 0..count { + s.execute("shape.rectangle", &json!({"x": i % 100 * 20, "y": i / 100 * 20, "width": 10, "height": 10})).unwrap(); + } + let path = d.join("a.vectorcraft").to_string_lossy().to_string(); + s.execute("file.saveCopy", &json!({"path": path})).unwrap(); + let before = std::fs::read(&path).unwrap(); + s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + assert!(job.streams()); + let token = crate::cancel::CancelToken::new(); + let r = crate::cancel::scope(&token, None, || { + job.write_streamed(&mut |p, fill| super::write_file_with(p, &mut |w| fill(&mut CancelAfterFirst { inner: w, token: token.clone() }))) + }); + assert!(matches!(r, Err(EngineError::Cancelled)), "{count}: {r:?}"); + assert_eq!(std::fs::read(&path).unwrap(), before, "{count} objects"); + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1, "no temporary file is left"); + // Canceled before it starts: the file isn't opened. + let mut opened = false; + let r = crate::cancel::scope(&token, None, || { + job.write_streamed(&mut |_, _| { + opened = true; + Ok(()) + }) + }); + assert!(matches!(r, Err(EngineError::Cancelled)) && !opened, "{r:?}"); + } + // A file encoded first (SVG): nothing reaches the writer. + let mut s = session(200.0, 100.0, 1); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": d.join("a.svg").to_string_lossy()})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let token = crate::cancel::CancelToken::new(); + token.cancel(); + let mut writes = 0; + let r = crate::cancel::scope(&token, None, || { + job.write_streamed(&mut |_, _| { + writes += 1; + Ok(()) + }) + }); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + let r = crate::cancel::scope(&token, None, || { + job.write(|_, _| { + writes += 1; + Ok(()) + }) + }); + assert!(matches!(r, Err(EngineError::Cancelled)) && writes == 0, "{r:?}"); + assert!(!d.join("a.svg").exists()); + let _ = std::fs::remove_dir_all(&d); +} + +/// A save that writes several files (EPS with Use Artboards) and is canceled once its first file is +/// in place writes the others too and succeeds: the set is never left half written. +#[test] +fn a_save_canceled_after_its_first_file_writes_them_all() { + let d = tmp_dir("cancel-files"); + let mut s = session(100.0, 100.0, 2); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let path = d.join("logo.eps").to_string_lossy().to_string(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let token = crate::cancel::CancelToken::new(); + let mut written = vec![]; + let r = crate::cancel::scope(&token, None, || { + job.write(|p, b| { + super::write_save_file(p, b)?; + written.push(p.to_string()); + token.cancel(); + Ok(()) + }) + }); + assert!(r.is_ok(), "{r:?}"); + assert_eq!(written.len(), 3, "{written:?}"); + assert!(written.iter().all(|p| std::path::Path::new(p).is_file()), "{written:?}"); + let _ = std::fs::remove_dir_all(&d); +} + /// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them. #[test] fn a_failed_save_does_not_stamp_the_documents_dates() { diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 8e7149cad2..e8f3c42b8e 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -9,6 +9,10 @@ //! are on disk, and the error names them. Where that copy of the old file can't be made, the file //! is left as it was and the save fails. //! +//! Work canceled ([`vectorcraft_doc::cancel`]) by the time the temporary file is written and flushed +//! puts nothing in place: the temporary file is removed, the file stays as it was (or absent), and +//! the error wraps [`vectorcraft_doc::cancel::Cancelled`]. +//! //! On macOS `File::sync_all` is a full flush (`F_FULLFSYNC`), which SMB shares refuse with //! `ENOTSUP` and virtiofs shares (folders shared into a macOS VM) with `ENOTTY`, while a plain //! `fsync` works: [`sync_file`] falls back to the plain one there (#1620). @@ -43,7 +47,8 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { } /// Write `path` atomically with `fill`, which writes the content into the temporary file. When -/// `fill` or flushing fails the temporary file is removed and `path` is left untouched. When the +/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the +/// temporary file is removed and `path` is left untouched. When the /// folder refuses the temporary file or the rename, the content is copied into `path` instead (see /// the module docs). pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { @@ -79,7 +84,7 @@ fn write_atomic_stepping( (tmp, f, Some(e)) } }; - let filled = fill(&mut f).and_then(|()| sync_file(&f)); + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); if let Err(e) = filled { // Best effort: the temporary file is all there is to clean up. @@ -176,7 +181,7 @@ fn write_new_linking( ) -> io::Result<()> { let tmp = temp_path(path)?; let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?; - let filled = fill(&mut f).and_then(|()| sync_file(&f)); + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); let placed = filled.and_then(|()| match link(&tmp, path) { Err(e) if e.kind() != io::ErrorKind::AlreadyExists => copy_new(&tmp, path), @@ -187,6 +192,12 @@ fn write_new_linking( placed } +/// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has +/// been canceled: the last check before a written temporary file is put in place. +fn not_cancelled() -> io::Result<()> { + vectorcraft_doc::cancel::check().map_err(io::Error::other) +} + /// Create `path` (never replacing anything) with the content of the file `from`; a failed copy /// removes it again. fn copy_new(from: &Path, path: &Path) -> io::Result<()> { @@ -408,6 +419,39 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// Work canceled by the time the temporary file is written and flushed puts nothing in place: + /// the old file stays as it was, also where the folder refuses the rename (no copy over it), a + /// new file is not created, and no temporary file is left. + #[test] + fn canceled_work_puts_nothing_in_place() { + use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope}; + fn cancelled(e: &io::Error) -> bool { + e.get_ref().is_some_and(|e| e.is::()) + } + let d = dir("cancel"); + let path = d.join("doc.vectorcraft"); + std::fs::write(&path, b"original").unwrap(); + let token = CancelToken::new(); + let r = scope(&token, None, || { + write_atomic_with(&path, |f| { + f.write_all(b"new")?; + token.cancel(); + Ok(()) + }) + }); + assert!(r.as_ref().is_err_and(cancelled), "{r:?}"); + let refused = |_: &Path, _: &Path| -> io::Result<()> { Err(io::Error::from(io::ErrorKind::PermissionDenied)) }; + let r = scope(&token, None, || write_atomic_stepping(&path, |f| f.write_all(b"new"), create_new, refused)); + assert!(r.as_ref().is_err_and(cancelled), "{r:?}"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + let new = d.join("new.vectorcraft"); + let r = scope(&token, None, || write_new_with(&new, |f| f.write_all(b"new"))); + assert!(r.as_ref().is_err_and(cancelled), "{r:?}"); + assert!(!new.exists()); + assert!(leftovers(&d, "doc.vectorcraft").is_empty(), "{:?}", leftovers(&d, "doc.vectorcraft")); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn the_original_file_survives_a_failed_write() { let d = dir("fail"); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 0e3d6df203..aa0493f1ba 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1455,6 +1455,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the export progress dialog; the exports go on, shown in the status bar → {hidden: n}", ), + ( + "file.cancelSave", + "Cancel Save", + "", + "{} stop every save running in the background (Background Save) before it replaces its file: the file stays as it was and the document keeps its file and stays modified; a save whose file was already being replaced finishes and is reported as saved → {cancelled: n}", + ), + ( + "file.saveInBackground", + "Continue in Background", + "", + "{} close the save progress window; the saves go on, shown in the status bar → {hidden: n}", + ), ( "file.cancelOpen", "Cancel Opening", diff --git a/crates/ui-egui/src/background.rs b/crates/ui-egui/src/background.rs index b0bdcc6287..34e1071813 100644 --- a/crates/ui-egui/src/background.rs +++ b/crates/ui-egui/src/background.rs @@ -1,7 +1,9 @@ //! Background Save and Background Export (Preferences → File Handling): a save or an export encodes //! and writes a snapshot of the document on a worker thread while editing goes on. The status bar //! shows what is in progress; the result is applied on the UI thread when it arrives (a save marks -//! the document saved as of its snapshot, so edits made meanwhile keep it modified). +//! the document saved as of its snapshot, so edits made meanwhile keep it modified). Exports and +//! saves show in the progress window ([`crate::export_progress`]) with Cancel and Continue in +//! Background. //! //! It needs a thread-safe writer from the host ([`crate::Services::write_shared`], desktop); //! without one (the web, which downloads) the work runs at once, as with the preference off. @@ -44,15 +46,27 @@ struct Task { scope: ScopeHandle, } +/// What a job that shows in the progress window does: its Cancel and Continue in Background act on +/// the jobs of its kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// An export (Background Export): `file.cancelExport`, `file.exportInBackground`. + Export, + /// A save (Background Save): `file.cancelSave`, `file.saveInBackground`. + Save, +} + /// A job in progress. pub struct Job { id: u64, + /// What the job does, for the progress window and its commands. + pub kind: Kind, /// What the status bar and `ui.inspect` show ("Saving Poster.vectorcraft"); empty for work they /// don't show. pub label: String, /// The document the job reads (`DocState::uid`), if any. pub doc: Option, - /// How far an export has got, and its Cancel ([`crate::export_progress`] shows it). + /// How far an export or a save has got, and its Cancel ([`crate::export_progress`] shows it). pub progress: Option>, /// Continue in Background: the progress dialog no longer shows this job. pub hidden: bool, @@ -119,18 +133,41 @@ impl Background { /// Cancel every export in progress → how many there were. pub fn cancel_exports(&mut self) -> usize { + self.cancel(Kind::Export) + } + + /// Hide the exports in progress from the progress dialog (they go on) → how many there were. + pub fn hide_exports(&mut self) -> usize { + self.hide(Kind::Export) + } + + /// Cancel every save in progress that the progress window can show → how many there were. + pub fn cancel_saves(&mut self) -> usize { + self.cancel(Kind::Save) + } + + /// Hide the saves in progress from the progress window (they go on) → how many there were. + pub fn hide_saves(&mut self) -> usize { + self.hide(Kind::Save) + } + + /// Is a job of `kind` in progress that can still be canceled? + pub fn running(&self, kind: Kind) -> bool { + self.jobs.iter().any(|j| j.kind == kind && j.progress.is_some() && !j.cancelled()) + } + + fn cancel(&mut self, kind: Kind) -> usize { let mut n = 0; - for p in self.jobs.iter().filter(|j| !j.cancelled()).filter_map(|j| j.progress.as_ref()) { + for p in self.jobs.iter().filter(|j| j.kind == kind && !j.cancelled()).filter_map(|j| j.progress.as_ref()) { p.cancel(); n += 1; } n } - /// Hide the exports in progress from the progress dialog (they go on) → how many there were. - pub fn hide_exports(&mut self) -> usize { + fn hide(&mut self, kind: Kind) -> usize { let mut n = 0; - for j in self.jobs.iter_mut().filter(|j| j.progress.is_some() && !j.hidden && !j.cancelled()) { + for j in self.jobs.iter_mut().filter(|j| j.kind == kind && j.progress.is_some() && !j.hidden && !j.cancelled()) { j.hidden = true; n += 1; } @@ -163,6 +200,34 @@ pub fn run_with_progress( progress: Option>, work: impl FnOnce(Writer) -> Result + Send + 'static, then: impl FnOnce(&mut VectorcraftApp, Result) -> Result + 'static, +) -> Result { + start(app, enabled, label, doc, progress, Kind::Export, work, then) +} + +/// [`run_with_progress`] for a save of document `doc`: the progress window shows it as a save, and +/// its Cancel is `file.cancelSave`. +pub fn run_saving( + app: &mut VectorcraftApp, + enabled: bool, + label: String, + doc: u64, + progress: Arc, + work: impl FnOnce(Writer) -> Result + Send + 'static, + then: impl FnOnce(&mut VectorcraftApp, Result) -> Result + 'static, +) -> Result { + start(app, enabled, label, Some(doc), Some(progress), Kind::Save, work, then) +} + +#[allow(clippy::too_many_arguments)] +fn start( + app: &mut VectorcraftApp, + enabled: bool, + label: String, + doc: Option, + progress: Option>, + kind: Kind, + work: impl FnOnce(Writer) -> Result + Send + 'static, + then: impl FnOnce(&mut VectorcraftApp, Result) -> Result + 'static, ) -> Result { let mut work: Work = Box::new(work); let shared = app.services.write_shared.clone().filter(|_| enabled && !app.background.foreground && app.services.download.is_none()); @@ -174,7 +239,8 @@ pub fn run_with_progress( let (sets, status) = (app.ui.status_sets, if label.is_empty() { String::new() } else { format!("{label}…") }); let bg = &mut app.background; bg.next_id += 1; - bg.jobs.push(Job { id, label: label.clone(), doc, progress, hidden: false, sets, line: status.clone(), then: Box::new(then) }); + let line = status.clone(); + bg.jobs.push(Job { id, kind, label: label.clone(), doc, progress, hidden: false, sets, line, then: Box::new(then) }); if label.is_empty() { return Ok(json!({ "background": true })); } diff --git a/crates/ui-egui/src/export_progress.rs b/crates/ui-egui/src/export_progress.rs index 3d392c3a35..ebde2f8be2 100644 --- a/crates/ui-egui/src/export_progress.rs +++ b/crates/ui-egui/src/export_progress.rs @@ -7,11 +7,17 @@ //! Cancel), Continue in Background (`file.exportInBackground`) closes the //! dialog and leaves the export to the status bar. //! +//! A save running in the background (Background Save) shows in the same window, with a moving bar +//! (a save counts no steps) and how many more saves wait: Cancel (`file.cancelSave`, also Esc) +//! stops it before it replaces its file, and Continue in Background (`file.saveInBackground`) +//! leaves it to the status bar. +//! //! It opens after [`DELAY`] so a quick export doesn't flash it, and waits while another dialog is //! open (the overwrite question, an options dialog): never two modals at once. use serde_json::json; +use crate::background::Kind; use crate::dialogs::modal; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -24,11 +30,12 @@ fn seen_id() -> egui::Id { egui::Id::unique("export-progress-seen") } -/// What the dialog shows: (label, steps done, steps in all, share done, exports after this one, -/// what the steps are). +/// What the dialog shows: (label, steps done, steps in all, share done, jobs of its kind after this +/// one, what the steps are). fn shown(app: &VectorcraftApp, now: f64, ctx: &egui::Context) -> Option<(String, u64, u64, f32, usize, Steps)> { let jobs: Vec<_> = app.background.jobs.iter().filter(|j| !j.hidden && !j.cancelled()).filter(|j| j.progress.is_some()).collect(); let first = jobs.first()?; + let more = jobs.iter().filter(|j| j.kind == first.kind).count() - 1; let since = ctx.data_mut(|m| { let seen = m.get_temp_mut_or_insert_with(seen_id(), || (first.id(), now)); if seen.0 != first.id() { @@ -42,11 +49,12 @@ fn shown(app: &VectorcraftApp, now: f64, ctx: &egui::Context) -> Option<(String, let (done, total) = first.progress.as_ref().map(|p| p.counts()).unwrap_or_default(); let frac = first.progress.as_ref().and_then(|p| p.fraction()).unwrap_or(0.0) as f32; let steps = match &first.progress { + _ if first.kind == Kind::Save => Steps::Save, Some(p) if p.counts_share() => Steps::Share, Some(p) if p.counts_files() => Steps::Files, _ => Steps::Artboards, }; - Some((first.label.clone(), done, total, frac, jobs.len() - 1, steps)) + Some((first.label.clone(), done, total, frac, more, steps)) } /// What an export's steps are. @@ -57,6 +65,8 @@ enum Steps { Files, /// An exporter plug-in's own steps, shown as a share of the work. Share, + /// A save, which counts no steps: a moving bar. + Save, } /// Draws the window for the first export running in the background that wasn't hidden or @@ -71,6 +81,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let t = Tokens::get(ctx); let heading = format!("{}…", crate::i18n::msg(&label)); let pressed = window(ctx, "export-progress", &heading, |ui| { + if steps == Steps::Save { + indeterminate(ui, tl!("Encoding and writing the file…")); + if more > 0 { + ui.add_space(6.0); + let queued = crate::i18n::tn(more as u64, "{n} more save waiting", "{n} more saves waiting"); + ui.label(egui::RichText::new(queued).size(11.5).color(t.text_dim)); + } + return; + } // One step says nothing a spinner doesn't: the bar would sit at 0 % until the file is written. if steps == Steps::Share && total > 0 { share(ui, tl!("Encoding and writing the file…"), frac); @@ -95,10 +114,12 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.label(egui::RichText::new(queued).size(11.5).color(t.text_dim)); } }); - let id = match pressed { - Some(Pressed::Cancel) => "file.cancelExport", - Some(Pressed::Hide) => "file.exportInBackground", - None => return, + let id = match (pressed, steps == Steps::Save) { + (Some(Pressed::Cancel), false) => "file.cancelExport", + (Some(Pressed::Hide), false) => "file.exportInBackground", + (Some(Pressed::Cancel), true) => "file.cancelSave", + (Some(Pressed::Hide), true) => "file.saveInBackground", + (None, _) => return, }; if let Err(e) = app.run(id, json!({})) { app.status(e); @@ -298,6 +319,45 @@ mod tests { assert!(app.background.jobs.is_empty()); } + /// A Background Save shows in the window after the delay, with a moving bar and how many more + /// saves wait, never over another dialog; Continue in Background hides it and the saves go on. + /// With Background Save off the save is written at once and no window shows. + #[test] + fn a_background_save_shows_in_the_window_and_continue_hides_it() { + let go = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let mut app = app(go.clone()); + for name in ["a", "b"] { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let r = app.run("file.save", json!({"path": format!("/docs/{name}.vectorcraft")})).unwrap(); + assert_eq!(r["background"], true, "{r}"); + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + assert!(!frame(&mut app, &ctx, 0.0).contains("Saving a.vectorcraft"), "not before the delay"); + // Another dialog is open: the window waits. + app.ui.dialog = Some(crate::state::Dialog::new("about", json!({}))); + frame(&mut app, &ctx, 1.0); + assert!(!frame(&mut app, &ctx, 1.1).contains("Saving a.vectorcraft"), "never over another dialog"); + app.ui.dialog = None; + frame(&mut app, &ctx, 1.2); + let shown = frame(&mut app, &ctx, 1.3); + assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("1 more save waiting"), "{shown}"); + assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}"); + assert_eq!(app.run("file.saveInBackground", json!({})).unwrap()["hidden"], 2); + assert!(!frame(&mut app, &ctx, 2.0).contains("Saving"), "hidden saves aren't shown"); + assert!(crate::menus::enabled(&app, "file.cancelSave"), "they can still be canceled"); + go.store(true, std::sync::atomic::Ordering::SeqCst); + background::wait_all(&mut app); + assert!(app.background.jobs.is_empty()); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/docs/b.vectorcraft")); + app.session.execute("prefs.set", &json!({"values": {"backgroundSave": false}})).unwrap(); + app.services.write = Some(Box::new(|_: &str, _: &[u8]| Ok(()))); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let r = app.run("file.save", json!({"path": "/docs/c.vectorcraft"})); + assert!(r.as_ref().is_ok_and(|r| r.get("background").is_none()), "{r:?}"); + assert!(app.background.jobs.is_empty() && !frame(&mut app, &ctx, 3.0).contains("Saving")); + } + #[test] fn an_export_of_files_counts_files() { let go = Arc::new(std::sync::atomic::AtomicBool::new(false)); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..65501cb6cc 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6063,6 +6063,9 @@ theme Appearance Външен вид Continue in Background Продължаване във фонов режим Cancel Export Отказ от експортирането @msg Export cancelled Експортирането е отказано + Cancel Save Отказ от записването +@plural {n} more save waiting|{n} more saves waiting Още {n} записване в изчакване|Още {n} записвания в изчакване +@msg Save canceled Записването е отказано # Paragraph panel menu › Justification… Desired Желано Word Spacing: Разстояние между думите: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..10931ec65c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6084,6 +6084,9 @@ mark-style Japanese Japanski Continue in Background Nastavi u pozadini Cancel Export Otkaži izvoz @msg Export cancelled Izvoz otkazan + Cancel Save Otkaži čuvanje +@plural {n} more save waiting|{n} more saves waiting Čeka još {n} čuvanje|Čekaju još {n} čuvanja|Čeka još {n} čuvanja +@msg Save canceled Čuvanje otkazano Desired Željeno Word Spacing: Razmak riječi: Letter Spacing: Razmak slova: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..6c0cad2469 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5887,6 +5887,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg Expand: no gradient fills Expandeix: no hi ha farciments de degradat @msg Expand: nothing to expand Expandeix: no hi ha res per expandir @msg Export cancelled Exportació cancel·lada + Cancel Save Cancel·la el desament +@plural {n} more save waiting|{n} more saves waiting {n} desament més en espera|{n} desaments més en espera +@msg Save canceled Desament cancel·lat @msg Exported {path} S’ha exportat {path} @msg Exported {what} S’ha exportat {what} @msg Exporting {_1} S’està exportant {_1} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..3d485958c9 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6512,6 +6512,9 @@ mark-style Japanese Japonské Continue in Background Pokračovat na pozadí Cancel Export Zrušit export @msg Export cancelled Export byl zrušen + Cancel Save Zrušit ukládání +@plural {n} more save waiting|{n} more saves waiting Čeká ještě {n} uložení|Čekají ještě {n} uložení|Čeká ještě {n} uložení +@msg Save canceled Ukládání bylo zrušeno # Paragraph panel menu › Justification… Desired Požadované Word Spacing: Mezery mezi slovy: diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..304fb63c29 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -8793,6 +8793,9 @@ swatch Bright Violet Kraftig violet Continue in Background Fortsæt i baggrunden Cancel Export Annullér eksport @msg Export cancelled Eksport annulleret + Cancel Save Annullér gemning +@plural {n} more save waiting|{n} more saves waiting {n} gemning mere venter|{n} gemninger mere venter +@msg Save canceled Gemning annulleret # Paragraph panel menu › Justification… Desired Ønsket Word Spacing: Ordafstand: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..fd47295aad 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6094,6 +6094,9 @@ effect Soft Weich Continue in Background Im Hintergrund fortsetzen Cancel Export Export abbrechen @msg Export cancelled Export abgebrochen + Cancel Save Speichern abbrechen +@plural {n} more save waiting|{n} more saves waiting {n} weiterer Speichervorgang wartet|{n} weitere Speichervorgänge warten +@msg Save canceled Speichern abgebrochen # Paragraph panel menu › Justification… Desired Optimal Word Spacing: Wortabstand: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..b9c540f597 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6492,6 +6492,9 @@ effect Points Σημεία Continue in Background Συνέχεια στο παρασκήνιο Cancel Export Ακύρωση εξαγωγής @msg Export cancelled Η εξαγωγή ακυρώθηκε + Cancel Save Ακύρωση αποθήκευσης +@plural {n} more save waiting|{n} more saves waiting {n} ακόμη αποθήκευση σε αναμονή|{n} ακόμη αποθηκεύσεις σε αναμονή +@msg Save canceled Η αποθήκευση ακυρώθηκε # Paragraph panel menu › Justification… Desired Επιθυμητό Word Spacing: Απόσταση λέξεων: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..90e0ff2c62 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6480,6 +6480,9 @@ mark-style Japanese Japonesas Continue in Background Continuar en segundo plano Cancel Export Cancelar exportación @msg Export cancelled Exportación cancelada + Cancel Save Cancelar guardado +@plural {n} more save waiting|{n} more saves waiting {n} guardado más en espera|{n} guardados más en espera +@msg Save canceled Guardado cancelado # Paragraph panel menu › Justification… Desired Deseado Word Spacing: Espaciado entre palabras: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..e553a223d0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6502,6 +6502,9 @@ mark-style Japanese Japanilainen Continue in Background Jatka taustalla Cancel Export Peruuta vienti @msg Export cancelled Vienti peruutettiin + Cancel Save Peruuta tallennus +@plural {n} more save waiting|{n} more saves waiting {n} tallennus odottaa|{n} tallennusta odottaa +@msg Save canceled Tallennus peruutettiin # Paragraph panel menu › Justification… Desired Haluttu Word Spacing: Sanaväli: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..33c646bb8b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6507,6 +6507,9 @@ theme Appearance Apparence Continue in Background Continuer en arrière-plan Cancel Export Annuler l’exportation @msg Export cancelled Exportation annulée + Cancel Save Annuler l’enregistrement +@plural {n} more save waiting|{n} more saves waiting {n} autre enregistrement en attente|{n} autres enregistrements en attente +@msg Save canceled Enregistrement annulé # Paragraph panel menu › Justification… Desired Optimal Word Spacing: Espacement des mots : diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..b6bf3c68c8 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -487,6 +487,7 @@ Can't save “{name}”. “{name}” સાચવી શકાતી નથી. Cancel રદ કરો Cancel Export નિકાસ રદ કરો + Cancel Save સાચવવાનું રદ કરો Cancel Image Trace ઇમેજ ટ્રેસ રદ કરો Cancel Key Object કી ઑબ્જેક્ટ રદ કરો Cancel Opening ખોલવાનું રદ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..9e9c146bdb 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7085,6 +7085,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg expected {{"objects": [...]}} अपेक्षित: {{"objects": [...]}} @msg export `{name}`: {e} निर्यात `{name}`: {e} @msg Export cancelled निर्यात रद्द + Cancel Save सेव रद्द करना +@plural {n} more save waiting|{n} more saves waiting {n} और सेव प्रतीक्षा में|{n} और सेव प्रतीक्षा में +@msg Save canceled सेव रद्द @msg Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft स्क्रीन के लिए एक्सपोर्ट png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai या vectorcraft लिखता है @msg export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes निर्यात प्रीसेट फ़ाइल {MAX_PRESET_FILE_BYTES} bytes से बड़ा है @msg Exported {path} {path} एक्सपोर्ट किया गया diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..1150f91b88 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6496,6 +6496,9 @@ liquify-list-end {0}, {1} {0} és {1} Continue in Background Folytatás a háttérben Cancel Export Exportálás megszakítása @msg Export cancelled Az exportálás megszakítva + Cancel Save Mentés megszakítása +@plural {n} more save waiting|{n} more saves waiting Még {n} mentés várakozik +@msg Save canceled A mentés megszakítva # Paragraph panel menu › Justification… Desired Kívánt Word Spacing: Szóköz: diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..7aebab75b7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6062,6 +6062,9 @@ swatch Bright Violet Violet cerah Continue in Background Lanjutkan di latar belakang Cancel Export Batalkan ekspor @msg Export cancelled Ekspor dibatalkan + Cancel Save Batalkan penyimpanan +@plural {n} more save waiting|{n} more saves waiting {n} penyimpanan lagi menunggu +@msg Save canceled Penyimpanan dibatalkan # Paragraph panel menu › Justification… Desired Diinginkan Word Spacing: Spasi Kata: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..f4af60963b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6130,6 +6130,9 @@ lighting Light Luce Continue in Background Continua in background Cancel Export Annulla esportazione @msg Export cancelled Esportazione annullata + Cancel Save Annulla salvataggio +@plural {n} more save waiting|{n} more saves waiting {n} altro salvataggio in attesa|{n} altri salvataggi in attesa +@msg Save canceled Salvataggio annullato # Paragraph panel menu › Justification… Desired Desiderato Word Spacing: Spaziatura parole: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..2a6a61a252 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6177,6 +6177,9 @@ lighting Light ライト Continue in Background バックグラウンドで続行 Cancel Export 書き出しをキャンセル @msg Export cancelled 書き出しをキャンセルしました + Cancel Save 保存をキャンセル +@plural {n} more save waiting|{n} more saves waiting 待機中の保存: あと {n} 件 +@msg Save canceled 保存をキャンセルしました # Paragraph panel menu › Justification… Desired 最適 Word Spacing: 単語間隔: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..e25c5778de 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8497,6 +8497,9 @@ liquify-list-end {0}, {1} {0} და {1} Cancel Export ექსპორტირების გაუქმება @plural {n} more export waiting|{n} more exports waiting რიგში მომლოდინე სხვა ექსპორტირება: {n} @msg Export cancelled ექსპორტირება გაუქმდა + Cancel Save შენახვის გაუქმება +@plural {n} more save waiting|{n} more saves waiting რიგში მომლოდინე სხვა შენახვა: {n} +@msg Save canceled შენახვა გაუქმდა Clear History ისტორიის გასუფთავება New Document from State ახალი დოკუმენტი მდგომარეობიდან Continue in Background ფონურ რეჟიმში გაგრძელება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..7a7c057b2e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6094,6 +6094,9 @@ lighting Light 광원 Continue in Background 백그라운드에서 계속 Cancel Export 내보내기 취소 @msg Export cancelled 내보내기를 취소했습니다 + Cancel Save 저장 취소 +@plural {n} more save waiting|{n} more saves waiting 대기 중인 저장 {n}개 더 +@msg Save canceled 저장을 취소했습니다 # Paragraph panel menu › Justification… Desired 희망 Word Spacing: 단어 간격: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..7b7bb07c33 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8618,6 +8618,9 @@ swatch Bright Violet Felviolet Continue in Background Doorgaan op achtergrond Cancel Export Export annuleren @msg Export cancelled Export geannuleerd + Cancel Save Opslaan annuleren +@plural {n} more save waiting|{n} more saves waiting Nog {n} opslagactie in de wachtrij|Nog {n} opslagacties in de wachtrij +@msg Save canceled Opslaan geannuleerd # Paragraph panel menu › Justification… Desired Gewenst Word Spacing: Woordafstand: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..b77f23725c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6366,6 +6366,9 @@ mark-style Japanese Japońskie Continue in Background Kontynuuj w tle Cancel Export Anuluj eksport @msg Export cancelled Eksport anulowany + Cancel Save Anuluj zapisywanie +@plural {n} more save waiting|{n} more saves waiting Czeka jeszcze {n} zapis|Czekają jeszcze {n} zapisy|Czeka jeszcze {n} zapisów +@msg Save canceled Zapisywanie anulowane # Paragraph panel menu › Justification… Desired Optymalne Word Spacing: Odstępy między wyrazami: diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..9eea52c773 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6424,6 +6424,9 @@ mark-style Japanese Japonesas Continue in Background Continuar em Segundo Plano Cancel Export Cancelar Exportação @msg Export cancelled Exportação cancelada + Cancel Save Cancelar Salvamento +@plural {n} more save waiting|{n} more saves waiting Mais {n} salvamento aguardando|Mais {n} salvamentos aguardando +@msg Save canceled Salvamento cancelado # Paragraph panel menu › Justification… Desired Desejado Word Spacing: Espaçamento entre Palavras: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..741bb5a641 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6130,6 +6130,9 @@ lighting Light Свет Continue in Background Продолжить в фоне Cancel Export Отменить экспорт @msg Export cancelled Экспорт отменён + Cancel Save Отменить сохранение +@plural {n} more save waiting|{n} more saves waiting Ещё {n} сохранение в очереди|Ещё {n} сохранения в очереди|Ещё {n} сохранений в очереди +@msg Save canceled Сохранение отменено # Paragraph panel menu › Justification… Desired Желательно Word Spacing: Интервал между словами: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..10c87e89d0 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6552,6 +6552,9 @@ swatch Yellow Green Gulgrön Continue in Background Fortsätt i bakgrunden Cancel Export Avbryt export @msg Export cancelled Exporten avbröts + Cancel Save Avbryt sparande +@plural {n} more save waiting|{n} more saves waiting {n} sparande till väntar|{n} sparanden till väntar +@msg Save canceled Sparandet avbröts # Paragraph panel menu › Justification… Desired Önskat Word Spacing: Ordavstånd: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..e84fc15f2f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6622,6 +6622,9 @@ theme Appearance Görünüm @msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. Düz Logo modu görüntüyü {_3} × {_4} boyutundan ortalama alarak küçültüp {_1} × {_2} pikselde izledi. @plural {n} more export waiting|{n} more exports waiting {n} dışa aktarma daha bekliyor|{n} dışa aktarma daha bekliyor @msg Export cancelled Dışa aktarma iptal edildi + Cancel Save Kaydetmeyi İptal Et +@plural {n} more save waiting|{n} more saves waiting {n} kaydetme daha bekliyor|{n} kaydetme daha bekliyor +@msg Save canceled Kaydetme iptal edildi Add filters from the list above Yukarıdaki listeden filtre ekleyin Add to Stack Yığına Ekle Applied Filters Uygulanan Filtreler diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..85e2fcc1a8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6112,6 +6112,9 @@ lighting Light Світло Continue in Background Продовжити у фоні Cancel Export Скасувати експорт @msg Export cancelled Експорт скасовано + Cancel Save Скасувати збереження +@plural {n} more save waiting|{n} more saves waiting Ще {n} збереження в очікуванні|Ще {n} збереження в очікуванні|Ще {n} збережень в очікуванні +@msg Save canceled Збереження скасовано # Paragraph panel menu › Justification… Desired Бажане Word Spacing: Інтервал між словами: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..7136d5cb96 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6141,6 +6141,9 @@ liquify-list-end {0}, {1} {0} và {1} Continue in Background Tiếp tục trong nền Cancel Export Hủy xuất @msg Export cancelled Đã hủy xuất + Cancel Save Hủy lưu +@plural {n} more save waiting|{n} more saves waiting Còn {n} lượt lưu đang chờ +@msg Save canceled Đã hủy lưu # Paragraph panel menu › Justification… Desired Mong muốn Word Spacing: Khoảng cách từ: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..8af2fbeb47 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6348,6 +6348,9 @@ lighting Light 光源 Continue in Background 在后台继续 Cancel Export 取消导出 @msg Export cancelled 已取消导出 + Cancel Save 取消保存 +@plural {n} more save waiting|{n} more saves waiting 另有 {n} 个保存等待中 +@msg Save canceled 已取消保存 # Paragraph panel menu › Justification… Desired 所需 Word Spacing: 字间距: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..bf65eccdd4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6146,6 +6146,9 @@ lighting Light 光源 Continue in Background 在背景繼續 Cancel Export 取消匯出 @msg Export cancelled 已取消匯出 + Cancel Save 取消儲存 +@plural {n} more save waiting|{n} more saves waiting 另有 {n} 個儲存等待中 +@msg Save canceled 已取消儲存 # Paragraph panel menu › Justification… Desired 所需 Word Spacing: 字間距: diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index ea27320b52..462d903d55 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -35,7 +35,9 @@ pub use open::{ #[cfg(test)] pub(crate) use open::{open_file, opened_with_notes}; pub(crate) use save::save_current; -pub use save::{ask_format_options, ask_pdf_options, remember_active_artboard, remember_view, save, save_pdf}; +pub use save::{ + SAVE_CANCELED, ask_format_options, ask_pdf_options, cancel_saves, hide_saves, remember_active_artboard, remember_view, save, save_pdf, +}; pub(crate) use save::{export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_reporting, write_to}; #[cfg(test)] pub(crate) use save::{report_write_error, saved_status}; diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index e1f50fba45..47d83173af 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -1,10 +1,30 @@ use super::export::file_url; use super::open::{note_recent, open_options}; use super::{ - EngineError, FilePick, Format, SAVE_FORMATS, SaveMode, SavePlan, SavedView, Services, TEMPLATE_FORMATS, Value, VectorcraftApp, Writer, - background, dialogs, fileio, json, svg_options, + EngineError, FilePick, Format, Progress, SAVE_FORMATS, SaveMode, SavePlan, SavedView, Services, TEMPLATE_FORMATS, Value, VectorcraftApp, Writer, + background, dialogs, fileio, json, progress, svg_options, }; +/// The status once a save running in the background was canceled. +pub const SAVE_CANCELED: &str = "Save canceled"; + +/// File › Cancel Save (the progress window's Cancel): every save running in the background stops +/// before it replaces its file. The file stays as it was, and the document keeps its file, format +/// and modified state → `{cancelled: n}`. A save whose file was already written is reported as saved. +pub fn cancel_saves(app: &mut VectorcraftApp) -> Value { + let n = app.background.cancel_saves(); + if n > 0 { + app.status(SAVE_CANCELED); + } + json!({ "cancelled": n }) +} + +/// The progress window's Continue in Background for saves: they go on, shown in the status bar +/// only → `{hidden: n}`. +pub fn hide_saves(app: &mut VectorcraftApp) -> Value { + json!({ "hidden": app.background.hide_saves() }) +} + /// A save or an export that didn't write `path`: say so in a dialog that names the file and the /// reason and stays until it is closed, as an editor does (#1685). The status bar's line, which /// the caller's error becomes, is replaced by the next message, and a document that wasn't saved @@ -566,7 +586,10 @@ fn write_plan( let stream = app.services.stream_shared.clone().filter(|_| job.streams() && !is_web(app)); let (exists, allowed) = checks_replaced(app); let known: Vec = allowed.iter().chain(app.picks.written_beside.get(&uid).into_iter().flatten()).cloned().collect(); - let work = move |write: Writer| { + // The progress window's Cancel: a save canceled before it replaces its file writes nothing. + let progress = Progress::new(); + let (reporting, asked) = (progress.clone(), progress.clone()); + let write_file = move |write: Writer| { let mut own_refused = false; let mut observed = |p: &str, r: vectorcraft_engine::Result<()>| { own_refused = own_path.as_deref() == Some(p) && matches!(&r, Err(EngineError::ReadOnlyLocation(_))); @@ -583,16 +606,21 @@ fn write_plan( (_, _, Some(stream)) => job.write_streamed(&mut |p, fill| stream(p, fill).map_err(EngineError::Other)), _ => job.write_unless(check, |p, b| write(p, b).map_err(EngineError::Other)), }; - r.map_err(|e| { - if let EngineError::ReadOnlyLocation(reason) = &e { - refused_by_work.store(own_refused, std::sync::atomic::Ordering::Relaxed); - if !by_control { - return reason.clone(); + match r { + // Nothing written: the file is as it was. + Err(EngineError::Cancelled) => Ok(json!({ "cancelled": true })), + r => r.map_err(|e| { + if let EngineError::ReadOnlyLocation(reason) = &e { + refused_by_work.store(own_refused, std::sync::atomic::Ordering::Relaxed); + if !by_control { + return reason.clone(); + } } - } - e.to_string() - }) + e.to_string() + }), + } }; + let work = move |write: Writer| progress::scope(&reporting, || write_file(write)); let failed = target.clone().unwrap_or_default(); // The status line before the save starts: on the worker, the save sets one line ("