PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Save: show save progress as Saving NN% in the status bar and tab title (#3389) (#3485)
David Mannbea81c2f3d55
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rsindex 1d25ac2a0..5df122c4d 100644--- a/apps/photocraft/src/services.rs+++ b/apps/photocraft/src/services.rs@@ -191,6 +191,11 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {photocraft_format::atomic_write(path, bytes).map_err(|e| e.to_string())}+/// [`write_atomic`] reporting the fraction written (a background save's progress, #3389).+fn write_atomic_progress(path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> Result<(), String> {+ photocraft_format::atomic_write_progress(path, bytes, progress).map_err(|e| e.to_string())+}+fn export_options(settings: &photocraft_ui_egui::ExportSettings) -> photocraft_io::ExportOptions {let mut opts = photocraft_io::ExportOptions::default();if let Some(q) = settings.jpeg_quality {@@ -207,22 +212,32 @@ fn export_options(settings: &photocraft_ui_egui::ExportSettings) -> photocraft_iopts}+/// The share of a save's progress bar that encoding fills; writing the file fills the rest. A+/// 24 MP, 5-layer PSD (572 MB) takes about 3 s to encode and 0.5 s or more to write and flush.+const ENCODE_SHARE: f32 = 0.85;+/// A save on a worker thread (`Services::save_file` and `Services::automation_save`, #2017):/// encode, then write through `write`. Cancelling while encoding leaves the target untouched;-/// once writing starts the save can't be cancelled.+/// once writing starts the save can't be cancelled. The encoder's progress fills the first+/// [`ENCODE_SHARE`] of the job's progress, so the status bar and tab read "Saving NN%" (#3389).fn save_through(doc: &Document,path: &str,settings: &photocraft_ui_egui::ExportSettings,ctl: &photocraft_ui_egui::jobs_ui::SaveCtl,- write: impl Fn(&str, &[u8]) -> Result<(), String>,+ write: impl Fn(&str, &[u8], &dyn Fn(f32)) -> Result<(), String>,) -> Result<Vec<String>, String> {ctl.progress(0.0, "Encoding");let opts = export_options(settings);- let r = crate::crash_guard::guard("Save", || photocraft_io::export(doc, path, &opts).map_err(|e| e.to_string()))?;+ let cancelled = || ctl.check().is_err();+ let progress = |f: f32| ctl.progress(f * ENCODE_SHARE, "");+ let interrupt = photocraft_raster::Interrupt::new(&cancelled, &progress);+ let r = crate::crash_guard::guard("Save", || photocraft_io::export_with(doc, path, &opts, &interrupt).map_err(|e| e.to_string()))?;ctl.commit()?;- ctl.progress(0.0, "Writing");- write(path, &r.bytes)?;+ ctl.progress(ENCODE_SHARE, "Writing");+ // The last bit is the flush and rename after the last chunk: 100% only once they're done.+ write(path, &r.bytes, &|f| ctl.progress(ENCODE_SHARE + (0.99 - ENCODE_SHARE) * f, ""))?;+ ctl.progress(1.0, "");Ok(r.warnings)}@@ -232,7 +247,7 @@ fn save_file(settings: &photocraft_ui_egui::ExportSettings,ctl: &photocraft_ui_egui::jobs_ui::SaveCtl,) -> Result<Vec<String>, String> {- save_through(doc, path, settings, ctl, |p, b| write_atomic(Path::new(p), b))+ save_through(doc, path, settings, ctl, |p, b, progress| write_atomic_progress(Path::new(p), b, progress))}type SharedRecovery = Rc<RefCell<Option<RecoveryStore>>>;@@ -341,7 +356,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->});let automation_save = automation.clone().map(|workspace| {std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| {- save_through(doc, path, settings, ctl, |p, b| workspace.write(p, b).map_err(|e| e.to_string()))+ save_through(doc, path, settings, ctl, |p, b, _| workspace.write(p, b).map_err(|e| e.to_string()))}) as photocraft_ui_egui::SaveFileFn});let step: fn(&str, &serde_json::Value) -> photocraft_engine::Result<()> = photocraft_automation::workspace::authorize_desktop_engine_step;diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rsindex 25d433db2..bf39fe276 100644--- a/crates/format/src/atomic.rs+++ b/crates/format/src/atomic.rs@@ -32,6 +32,12 @@ use std::sync::atomic::{AtomicU64, Ordering};pub trait AtomicFs {/// Create `tmp` (it must not exist), write all of `bytes` and flush it ([`sync_file`]).fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()>;+ /// [`write_new`](Self::write_new), reporting the fraction of `bytes` written so far to+ /// `progress` (a save's progress bar, #3389). By default it reports nothing.+ fn write_new_progress(&self, tmp: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> {+ let _ = progress;+ self.write_new(tmp, bytes)+ }/// Rename `from` over `to`, replacing it.fn rename(&self, from: &Path, to: &Path) -> io::Result<()>;/// Remove a (temporary) file.@@ -47,10 +53,21 @@ pub trait AtomicFs {#[derive(Debug, Clone, Copy, Default)]pub struct RealFs;+/// How much [`RealFs::write_new_progress`] writes between progress reports.+const WRITE_CHUNK: usize = 8 << 20;+impl AtomicFs for RealFs {fn write_new(&self, tmp: &Path, bytes: &[u8]) -> io::Result<()> {+ self.write_new_progress(tmp, bytes, &|_| {})+ }+ fn write_new_progress(&self, tmp: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> {let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(tmp)?;- f.write_all(bytes)?;+ let mut written = 0usize;+ for chunk in bytes.chunks(WRITE_CHUNK) {+ f.write_all(chunk)?;+ written = written.saturating_add(chunk.len());+ progress(written as f32 / bytes.len().max(1) as f32);+ }sync_file(&f)}fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {@@ -132,8 +149,19 @@ pub fn atomic_write(path: &Path, bytes: &[u8]) -> io::Result<()> {atomic_write_with(&RealFs, RenameRetry::platform(), path, bytes)}+/// [`atomic_write`] reporting the fraction of `bytes` written to `progress` as it goes (a save's+/// progress bar, #3389); the flush and rename follow the last report.+pub fn atomic_write_progress(path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> {+ atomic_write_with_progress(&RealFs, RenameRetry::platform(), path, bytes, progress)+}+/// [`atomic_write`] through an explicit file system and retry policy (the failure-injection seam).pub fn atomic_write_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytes: &[u8]) -> io::Result<()> {+ atomic_write_with_progress(fs, retry, path, bytes, &|_| {})+}++/// [`atomic_write_with`] reporting write progress (see [`atomic_write_progress`]).+pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> {let target = resolve_symlink(path);let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?;let dir = match target.parent() {@@ -147,7 +175,7 @@ pub fn atomic_write_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytlet mut tmp = None;for _ in 0..8 {let candidate = dir.join(temp_name(&name.to_string_lossy()));- match fs.write_new(&candidate, bytes) {+ match fs.write_new_progress(&candidate, bytes, progress) {Ok(()) => {tmp = Some(candidate);break;diff --git a/crates/format/src/atomic/tests.rs b/crates/format/src/atomic/tests.rsindex c03c71cc2..8e71bc7ce 100644--- a/crates/format/src/atomic/tests.rs+++ b/crates/format/src/atomic/tests.rs@@ -87,6 +87,24 @@ fn replaces_and_creates() {assert_no_temp(&d.0);}+/// #3389: a large write reports how far it has got, chunk by chunk, up to 1.0, and writes the+/// same bytes as a plain atomic write.+#[test]+fn reports_write_progress() {+ let d = TempDir::new("progress");+ let p = d.0.join("big.psd");+ let bytes: Vec<u8> = (0..WRITE_CHUNK * 2 + 123).map(|i| (i % 251) as u8).collect();+ let seen = std::sync::Mutex::new(Vec::new());+ atomic_write_progress(&p, &bytes, &|f| seen.lock().unwrap().push(f)).unwrap();+ let seen = seen.into_inner().unwrap();+ assert_eq!(seen.len(), 3, "one report per chunk: {seen:?}");+ assert!(seen.windows(2).all(|w| w[0] < w[1]), "monotonic: {seen:?}");+ assert!(seen[0] > 0.0 && seen[0] < 0.6, "{seen:?}");+ assert_eq!(seen.last().copied(), Some(1.0));+ assert!(std::fs::read(&p).unwrap() == bytes, "the file holds the bytes");+ assert_no_temp(&d.0);+}+#[test]fn creates_missing_parent_folders() {let d = TempDir::new("parent");diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rsindex 961ec37f1..0c8772021 100644--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@ -37,7 +37,7 @@ use std::path::Path;use photocraft_doc::Document;use photocraft_raster::Rgba8Image;-pub use atomic::atomic_write;+pub use atomic::{atomic_write, atomic_write_progress};#[cfg(not(target_arch = "wasm32"))]pub use autosave::RecoveryStore;pub use autosave::{Autosaver, RecoveryEntry, discard_recovery, list_recovery, recover};diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rsindex 99765a0d2..c2632d22b 100644--- a/crates/io/src/flat.rs+++ b/crates/io/src/flat.rs@@ -377,14 +377,33 @@ fn opaque_surface(s: &Surface, r: Rect) -> bool {})}+/// The part of a flat export that rendering the composite takes, the encoder taking the rest.+/// Measured on a 24 MP RGB/8 document: ~1 s to composite, then TIFF ~2.3 s, JPEG ~0.9 s,+/// PNG ~0.4 s, WebP ~0.25 s to encode.+fn composite_share(format: Format) -> f32 {+ match format {+ Format::Tiff => 0.3,+ Format::Jpeg => 0.55,+ _ => 0.7,+ }+}+/// Flattens and encodes as `format`.pub fn export_flat(doc: &Document, format: Format, opts: &ExportOptions) -> Result<ExportResult, IoError> {+ export_flat_with(doc, format, opts, &photocraft_raster::Interrupt::NONE)+}++/// [`export_flat`] reporting a coarse step through `ctl` once the composite is rendered; the+/// encoder does the rest (#3389).+pub(crate) fn export_flat_with(doc: &Document, format: Format, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result<ExportResult, IoError> {use photocraft_cms::{Builtin, Intent};if let Some(r) = export_mode_specific(doc, format, opts)? {return Ok(r);}let mut warnings = Vec::new();let mut img = document_to_image(doc, &mut warnings)?;+ ctl.check().map_err(|_| IoError::Cancelled)?;+ ctl.progress(composite_share(format));if opts.xmp == XmpEmbed::None {// Export As's Metadata: None: the packet lists the text of every type layer and one id// per placed document (#647).diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rsindex a2b30383d..2caf02797 100644--- a/crates/io/src/lib.rs+++ b/crates/io/src/lib.rs@@ -98,7 +98,7 @@ pub enum IoError {/// An SVG that does not parse (or is too large to rasterise).#[error("SVG: {0}")]Svg(String),- /// A background import was cancelled ([`import_with`]).+ /// A background import or save was cancelled ([`import_with`], [`export_with`]).#[error("cancelled")]Cancelled,}@@ -300,6 +300,37 @@ fn has_extension(name: &str, expected: &str) -> bool {/// Exports `doc` to the format named by `name_or_ext` (a file name, path or/// bare extension).pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result<ExportResult, IoError> {+ export_with(doc, name_or_ext, opts, &photocraft_raster::Interrupt::NONE)+}++/// [`export`] for a background save (#3389): reports how far encoding has got through `ctl`+/// (monotonic, `1.0` once the bytes are ready; per layer and per composite band for PSD/PSB and+/// layered TIFF, in coarse steps for the other formats) and checks it between stages. A cancelled+/// export fails with [`IoError::Cancelled`]; otherwise the bytes are exactly [`export`]'s.+pub fn export_with(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result<ExportResult, IoError> {+ ctl.check().map_err(|_| IoError::Cancelled)?;+ let r = export_stages(doc, name_or_ext, opts, ctl)?;+ ctl.check().map_err(|_| IoError::Cancelled)?;+ ctl.progress(1.0);+ Ok(r)+}++/// Run `f` with an interrupt whose progress `0..=1` fills `lo..=hi` of `ctl`'s (same cancellation).+pub(crate) fn with_span<R>(ctl: &photocraft_raster::Interrupt, lo: f32, hi: f32, f: impl FnOnce(&photocraft_raster::Interrupt) -> R) -> R {+ let cancelled = || ctl.cancelled();+ let progress = |p: f32| ctl.progress(lo + (hi - lo) * p.clamp(0.0, 1.0));+ f(&photocraft_raster::Interrupt::new(&cancelled, &progress))+}++/// Where a .pcraft save's progress stands once its thumbnail, then its 1024 px composite preview,+/// are rendered (the bundle itself is written after them).+const PCRAFT_THUMBNAIL_DONE: f32 = 0.15;+const PCRAFT_PREVIEWS_DONE: f32 = 0.4;+/// The share of a PSD/PSB export spent converting the document (layers, then the composite)+/// before its bytes are assembled: about 2.7 s of 3.0 s for a 24 MP, 5-layer RGB/8 document.+const PSD_MODEL_DONE: f32 = 0.9;++fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result<ExportResult, IoError> {let ext = extension(name_or_ext);if ext == "pdn" {return Err(IoError::Unsupported("PDN is import-only; save as .pcraft to preserve all layers and blend modes".into()));@@ -311,15 +342,20 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Resultreturn ora::export(doc);}if ext == photocraft_format::EXTENSION {- let previews = photocraft_format::SaveOptions {- thumbnail: Some(photocraft_compose::thumbnail(doc, 256)),- composite: Some(photocraft_compose::thumbnail(doc, 1024)),- };+ let thumbnail = Some(photocraft_compose::thumbnail(doc, 256));+ ctl.check().map_err(|_| IoError::Cancelled)?;+ ctl.progress(PCRAFT_THUMBNAIL_DONE);+ let composite = Some(photocraft_compose::thumbnail(doc, 1024));+ ctl.check().map_err(|_| IoError::Cancelled)?;+ ctl.progress(PCRAFT_PREVIEWS_DONE);+ let previews = photocraft_format::SaveOptions { thumbnail, composite };return Ok(ExportResult { bytes: photocraft_format::save_to_bytes(doc, &previews)?, warnings: Vec::new() });}if ext == "psd" || ext == "psb" {let o = PsdExportOptions { force_psb: opts.force_psb || ext == "psb", ..Default::default() };- let (mut file, mut warnings) = document_to_psd_with(doc, &o);+ let (mut file, mut warnings) = with_span(ctl, 0.0, PSD_MODEL_DONE, |ctl| psd_export::document_to_psd_interruptible(doc, &o, ctl));+ // A cancelled conversion stops early with an incomplete model: never write it.+ ctl.check().map_err(|_| IoError::Cancelled)?;if !doc.metadata.text.is_empty() {warnings.push("free-form text metadata is not supported by PSD/PSB; it will be dropped".into());}@@ -341,9 +377,9 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result}let format = photocraft_codecs::from_extension(&ext).ok_or_else(|| IoError::UnknownFormat(name_or_ext.to_string()))?;if format == photocraft_codecs::Format::Tiff && opts.tiff_layers && tiff_layers::would_write_layers(doc) {- return tiff_layers::export_layered(doc, opts);+ return tiff_layers::export_layered(doc, opts, ctl);}- flat::export_flat(doc, format, opts)+ flat::export_flat_with(doc, format, opts, ctl)}/// The PSD's merged composite as straight RGBA floats (row-major), converteddiff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex b872019c9..bbbb11992 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -8,7 +8,7 @@ use photocraft_psd::resources::{ImageResource, ResolutionInfo, ids, version_infouse photocraft_psd::{BlendMode as PsdBlend, ColorMode as PsdMode, Compression, Header, ImageData, LayerRecord, PsdFile, Rect as PsdRect, SectionType, TaggedBlock, Version,};-use photocraft_raster::Surface;+use photocraft_raster::{Interrupt, Surface};use crate::adjust_map;use crate::blocks;@@ -873,7 +873,8 @@ impl Ex {return Err(format!("smart objects nest more than {MAX_NESTING} deep"));}let doc = photocraft_format::load_from_bytes(bytes).map_err(|e| format!("its contents can't be read: {e}"))?;- let (file, warnings) = document_to_psd_nested(&doc, &PsdExportOptions { force_psb: true, ..Default::default() }, self.smart.depth + 1);+ let (file, warnings) =+ document_to_psd_nested(&doc, &PsdExportOptions { force_psb: true, ..Default::default() }, self.smart.depth + 1, &Interrupt::NONE);let data = file.to_bytes().map_err(|e| format!("its contents can't be written: {e}"))?;let stem = file_name.rsplit_once('.').map_or(file_name, |(a, _)| a);self.warnings.extend(warnings.into_iter().map(|w| format!("smart object {stem}: {w}")));@@ -919,7 +920,9 @@ impl Ex {s}- fn emit(&mut self, layers: &[Layer]) {+ /// Write the records of `layers` (and their groups' children). `tick` runs after each one:+ /// it reports progress and returns `false` to stop early (a cancelled save, #3389).+ fn emit(&mut self, layers: &[Layer], tick: &mut dyn FnMut() -> bool) {for l in layers {let extra = self.content_blocks(l);match &l.content {@@ -936,7 +939,7 @@ impl Ex {],..Default::default()});- self.emit(&g.children);+ self.emit(&g.children, tick);let kind = if g.expanded { SectionType::OpenFolder } else { SectionType::ClosedFolder };let lsct = TaggedBlock::section_divider(kind, Some(PsdBlend::from_key(l.blend.psd_key())), None);let r = self.record(l, std::iter::once(lsct).chain(extra).collect(), None);@@ -968,6 +971,9 @@ impl Ex {self.records.push(r);}}+ if !tick() {+ return;+ }}}}@@ -1075,7 +1081,9 @@ fn cmyk_of(fmt: &PixelFormat) -> bool {/// The merged image's planes (colour channels, then alpha), big-endian, matted against white/// when `matte`; with whether any pixel needs the alpha channel and whether any is below 1.-fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool) -> (Vec<u8>, bool, bool) {+/// `ctl` gets the fraction of rows done after each band; once it is cancelled the rest of the+/// image is left blank (the caller discards it).+fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, ctl: &Interrupt) -> (Vec<u8>, bool, bool) {let sample = fmt.sample;let cc = fmt.mode.color_channels();let bps = sample.bytes();@@ -1088,7 +1096,11 @@ fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool) ->let w = canvas.width() as usize;let space = photocraft_compose::cmyk_space(doc);let lab16 = fmt.mode == ColorMode::Lab && sample == SampleType::U16;+ let rows = canvas.height().max(1) as f32;let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> {+ if ctl.cancelled() {+ return Err(());+ }// Retain alpha whenever it differs from opaque at the stored precision.has_alpha |= band.px.iter().any(|p| match sample {SampleType::U8 => q255(p[3]) < 255,@@ -1123,6 +1135,7 @@ fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool) ->planes[o..o + src.len()].copy_from_slice(src);}}+ ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows);Ok(())});(planes, has_alpha, translucent)@@ -1137,9 +1150,23 @@ pub fn document_to_psd(doc: &Document) -> PsdFile {/// anything that could not be represented. The merged composite is rendered/// with `photocraft_compose::flatten`.pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile, Vec<String>) {- document_to_psd_nested(doc, opts, 0)+ document_to_psd_nested(doc, opts, 0, &Interrupt::NONE)}+/// [`document_to_psd_with`] for a background save (#3389): reports progress through `ctl` after+/// each layer record and each band of the merged composite. Once `ctl` is cancelled it stops+/// early and returns an **incomplete** model: callers check `ctl` and discard it.+pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> (PsdFile, Vec<String>) {+ document_to_psd_nested(doc, opts, 0, ctl)+}++/// How much of a PSD conversion the merged composite weighs, in layer records: rendering it+/// (all layers composited) and encoding its planes cost about two full-canvas layers.+const MERGED_WEIGHT: f32 = 2.0;+/// The part of the merged composite's share filled once its bands are rendered and converted; the+/// rest is compressing its planes.+const MERGED_RENDERED: f32 = 0.8;+/// Adds headroom for compressed channel streams and their per-row length tables.fn estimate_encoded_size(raw_bytes: u64, rows: u64, structural_bytes: u64) -> Option<u64> {raw_bytes.checked_add(raw_bytes.checked_add(63)?.checked_div(64)?)?.checked_add(rows.checked_mul(8)?)?.checked_add(structural_bytes)@@ -1253,7 +1280,7 @@ pub(crate) fn psd_size_exceeds_limit(doc: &Document) -> bool {}/// [`document_to_psd_with`] for a document embedded `depth` smart objects deep.-fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32) -> (PsdFile, Vec<String>) {+fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> (PsdFile, Vec<String>) {if doc.mode == ColorMode::Multichannel {return crate::multichannel_map::document_to_psd(doc, opts.force_psb);}@@ -1337,15 +1364,27 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32) -ex.text_index.insert(l.id, index);}}+ // Progress: one unit per layer record, then the merged composite (#3389).+ let records = doc.walk().len() as f32;+ let units = records + MERGED_WEIGHT;+ let layers_share = records / units;+ let mut done = 0.0f32;+ let mut tick = || {+ done += 1.0;+ ctl.progress(done / units);+ !ctl.cancelled()+ };let space = photocraft_compose::cmyk_space(doc);- photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers));+ photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers, &mut tick));// Merged composite, rendered and encoded in bands (no full-size float composite). Matting// against white only changes pixels with alpha < 1; if some are slightly translucent but all// round to opaque (so no alpha channel is written), encode once more without the matte.- let (mut planes, has_alpha, translucent) = merged_planes(doc, &fmt, cmyk_of(&fmt), opts.merged_matte);+ let merged_end = layers_share + (1.0 - layers_share) * MERGED_RENDERED;+ let (mut planes, has_alpha, translucent) =+ crate::with_span(ctl, layers_share, merged_end, |ctl| merged_planes(doc, &fmt, cmyk_of(&fmt), opts.merged_matte, ctl));if !has_alpha && translucent && opts.merged_matte {- planes = merged_planes(doc, &fmt, cmyk_of(&fmt), false).0;+ planes = merged_planes(doc, &fmt, cmyk_of(&fmt), false, &Interrupt::cancel_only(&|| ctl.cancelled())).0;}let n = doc.size.area() as usize;if !has_alpha {@@ -1381,6 +1420,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32) -let image_data = ImageData::encode(mcomp, &planes, &header).or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)).unwrap_or(ImageData { compression: Compression::Raw, data: planes });+ ctl.progress(1.0);// Resources.let mut resources = vec![diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rsindex e716c2287..3142bc1a8 100644--- a/crates/io/src/tiff_layers.rs+++ b/crates/io/src/tiff_layers.rs@@ -18,7 +18,7 @@ use photocraft_psd::tiff::{ByteOrder, ImageSourceData, resources_from_bytes, resuse photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, ImageResource, ResolutionInfo};use crate::flat::{csample, encode_image, image_to_document, layout_for, single_layer, try_buffer};-use crate::psd_export::{PsdExportOptions, document_to_psd_with};+use crate::psd_export::PsdExportOptions;use crate::psd_import::psd_to_document;use crate::{ExportOptions, ExportResult, ImportResult, IoError};@@ -179,11 +179,19 @@ fn interleave(planes: &[u8], w: u32, h: u32, channels: usize, color_channels: usOk(out)}+/// A layered TIFF export's progress once the layers and composite are converted, the layer+/// block is assembled and the composite interleaved; the TIFF encoder does the rest (#3389).+/// Measured on a 24 MP, 5-layer RGB/8 document: about 40 %, 70 % and 72 % of the time.+const TIFF_MODEL_DONE: f32 = 0.4;+const TIFF_LAYERS_DONE: f32 = 0.68;+const TIFF_COMPOSITE_DONE: f32 = 0.72;+/// Saves `doc` as a layered TIFF. Documents whose colour mode a TIFF cannot hold in our-/// codec (Lab) are saved flat, with a warning.-pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions) -> Result<ExportResult, IoError> {+/// codec (Lab) are saved flat, with a warning. Reports progress through `ctl` (see+/// [`crate::export_with`]).+pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result<ExportResult, IoError> {if !layered_mode(doc) {- let mut r = crate::flat::export_flat(doc, Format::Tiff, opts)?;+ let mut r = crate::flat::export_flat_with(doc, Format::Tiff, opts, ctl)?;if !doc.layers.is_empty() {r.warnings.push(format!("{:?} documents are saved as a flat TIFF: their layers are not kept", doc.pixel_format().mode));}@@ -194,10 +202,14 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions) -> Result<Exp// The PSD exporter renders the composite we need for the TIFF itself: unmatted (the TIFF// keeps straight alpha) and uncompressed (its planes are interleaved below).let psd_opts = PsdExportOptions { force_psb: opts.force_psb || big, merged_matte: false, merged_compression: Compression::Raw };- let (file, w) = document_to_psd_with(doc, &psd_opts);+ let (file, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psd_opts, ctl));+ // A cancelled conversion stops early with an incomplete model: never encode it.+ ctl.check().map_err(|_| IoError::Cancelled)?;warnings.extend(w);let order = if codecs::tiff_writes_little_endian() { ByteOrder::Little } else { ByteOrder::Big };let (layers, w) = ImageSourceData::from_psd(&file).to_bytes(order)?;+ ctl.check().map_err(|_| IoError::Cancelled)?;+ ctl.progress(TIFF_LAYERS_DONE);warnings.extend(w.into_iter().map(|w| format!("layer data: {w}")));// The profile and XMP are written as TIFF tags, not as resources. EXIF stays a resource// (1058): the TIFF codec has no EXIF directory, and the PSD importer reads it back from there.@@ -216,6 +228,8 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions) -> Result<Explet (w, h) = (doc.size.width, doc.size.height);let cmyk = fmt.mode == ColorMode::Cmyk;let data = interleave(&file.image_data.data, w, h, channels, cc, sample, cmyk)?;+ ctl.check().map_err(|_| IoError::Cancelled)?;+ ctl.progress(TIFF_COMPOSITE_DONE);let layout = layout_for(fmt.mode, has_alpha);let mut img = Image::from_raw(w, h, layout, sample, data)?;img.icc = doc.icc_profile.as_ref().map(|i| i.to_vec());diff --git a/crates/io/tests/export_progress.rs b/crates/io/tests/export_progress.rsnew file mode 100644index 000000000..8f372db4b--- /dev/null+++ b/crates/io/tests/export_progress.rs@@ -0,0 +1,93 @@+//! #3389: a background save's export reports its progress (so the status bar and the tab title+//! can read "Saving NN%") and can be cancelled, without changing a byte of what it writes.++use std::sync::Mutex;+use std::sync::atomic::{AtomicBool, Ordering};++use photocraft_color::{ColorMode, SampleType};+use photocraft_doc::{Document, Layer, LayerContent};+use photocraft_geom::{Rect, Size};+use photocraft_io::{ExportOptions, IoError};+use photocraft_raster::{Interrupt, Surface};++/// Three pixel layers (two in a group) of noise-like pixels at `depth`.+fn layered(depth: SampleType) -> Document {+ let mut d = Document::new("progress", Size::new(300, 200), ColorMode::Rgb, depth);+ let fmt = d.pixel_format();+ let layer = |name: &str, seed: usize, r: Rect| {+ let n = r.width() as usize * r.height() as usize * fmt.bytes_per_pixel();+ let px: Vec<u8> = (0..n).map(|i| ((i * 31 + seed * 17 + i / 7) % 251) as u8).collect();+ Layer::new(name, LayerContent::Raster(Surface::from_interleaved(fmt, r, &px)))+ };+ d.layers.push(layer("Back", 1, d.bounds()));+ d.layers.push(Layer::group("Group", vec![layer("A", 2, Rect::new(10, 10, 200, 150)), layer("B", 3, Rect::new(50, 40, 290, 190))]));+ d+}++/// Exports `doc` as `name` with progress recorded; the bytes and every fraction reported.+fn export_recorded(doc: &Document, name: &str, opts: &ExportOptions) -> (Vec<u8>, Vec<f32>) {+ let seen = Mutex::new(Vec::new());+ let cancel = || false;+ let progress = |f: f32| seen.lock().unwrap().push(f);+ let r = photocraft_io::export_with(doc, name, opts, &Interrupt::new(&cancel, &progress)).unwrap();+ (r.bytes, seen.into_inner().unwrap())+}++#[test]+fn export_reports_monotonic_progress_and_writes_the_same_bytes() {+ let layered_tiff = ExportOptions { tiff_layers: true, ..Default::default() };+ let cases: [(&str, ExportOptions, usize); 6] = [+ // Per layer record (3 layers + the group) and per composite band, then the bytes.+ ("a.psd", ExportOptions::default(), 6),+ ("a.psb", ExportOptions::default(), 6),+ ("a.tif", layered_tiff, 6),+ ("a.pcraft", ExportOptions::default(), 3),+ ("a.png", ExportOptions::default(), 2),+ ("a.jpg", ExportOptions::default(), 2),+ ];+ for depth in [SampleType::U8, SampleType::U16] {+ let doc = layered(depth);+ for (name, opts, min_reports) in &cases {+ if depth == SampleType::U16 && name.ends_with(".jpg") {+ continue;+ }+ let (bytes, seen) = export_recorded(&doc, name, opts);+ let plain = photocraft_io::export(&doc, name, opts).unwrap().bytes;+ // .pcraft bundles carry a save time, so only the formats without one compare exactly.+ if !name.ends_with(".pcraft") {+ assert!(bytes == plain, "{name} {depth:?}: progress reporting changed the bytes");+ }+ assert!(seen.len() >= *min_reports, "{name} {depth:?}: only {} reports: {seen:?}", seen.len());+ assert!(seen.windows(2).all(|w| w[0] <= w[1]), "{name} {depth:?}: progress went backwards: {seen:?}");+ assert!(seen.iter().all(|f| (0.0..=1.0).contains(f)), "{name} {depth:?}: {seen:?}");+ assert_eq!(seen.last().copied(), Some(1.0), "{name} {depth:?}: ends at 100%");+ assert!(seen.iter().any(|f| *f > 0.0 && *f < 1.0), "{name} {depth:?}: something between 0 and 100%: {seen:?}");+ }+ }+}++#[test]+fn psd_progress_moves_per_layer_before_the_composite() {+ let (_, seen) = export_recorded(&layered(SampleType::U8), "a.psd", &ExportOptions::default());+ // 4 layer records + the composite (weighing 2) = 6 units, the bytes after 90 %.+ let first = seen.first().copied().unwrap_or(0.0);+ assert!((first - 0.9 / 6.0).abs() < 1e-3, "the first layer is one sixth of the conversion: {seen:?}");+ let distinct = seen.iter().filter(|f| **f < 1.0).count();+ assert!(distinct >= 5, "{seen:?}");+}++#[test]+fn a_cancelled_export_stops_with_cancelled() {+ let doc = layered(SampleType::U8);+ for name in ["a.psd", "a.tif", "a.pcraft", "a.png"] {+ // Cancelled from the start, and cancelled after the first progress report.+ let cancelled = || true;+ let r = photocraft_io::export_with(&doc, name, &ExportOptions { tiff_layers: true, ..Default::default() }, &Interrupt::cancel_only(&cancelled));+ assert!(matches!(r, Err(IoError::Cancelled)), "{name}: {:?}", r.map(|r| r.bytes.len()));+ let stop = AtomicBool::new(false);+ let cancel = || stop.load(Ordering::Relaxed);+ let progress = |_: f32| stop.store(true, Ordering::Relaxed);+ let r = photocraft_io::export_with(&doc, name, &ExportOptions { tiff_layers: true, ..Default::default() }, &Interrupt::new(&cancel, &progress));+ assert!(matches!(r, Err(IoError::Cancelled)), "{name} midway: {:?}", r.map(|r| r.bytes.len()));+ }+}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex d1501baae..da9ffd96b 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1772,7 +1772,7 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip {.documents().iter().map(|st| {- let name = format!("{}{}", st.doc.name, if st.is_dirty() { " *" } else { "" });+ let name = studio_tab_name(app, st);ui.painter().layout_no_wrap(name, font.clone(), t.text).size().x+ ui.painter().layout_no_wrap(format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits()), meta_font.clone(), t.text_faint).size().x+ STUDIO_TAB_PAD@@ -1802,7 +1802,7 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip {for &(i, r) in placed.iter().filter(|(i, _)| *i < tab_count) {let Some(st) = app.session.documents().get(i) else { continue };let sel = Some(i) == active && !focused_open;- let name = format!("{}{}", st.doc.name, if st.is_dirty() { " *" } else { "" });+ let name = studio_tab_name(app, st);let meta = format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits());let natural_w = natural.get(i).copied().unwrap_or(0.0);let meta_g = ui.painter().layout_no_wrap(meta, meta_font.clone(), t.text_faint);@@ -1811,7 +1811,11 @@ fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip {// The title was cut: the tooltip has the rest of it.let cut = name_g.size().x + 0.5 < natural_w - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x;let resp = ui.interact(r, ui.id().with(("dtab", i)), Sense::click_and_drag());- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, sel, &st.doc.name));+ let saving = crate::jobs_ui::save_progress(app, st.doc.id);+ resp.widget_info(|| {+ let label = saving.as_ref().map_or_else(|| st.doc.name.clone(), |s| format!("{} - {s}", st.doc.name));+ egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, sel, label)+ });doc_tabs.push((i, r));if sel {ui.painter().rect_filled(r, t.radius_sm, t.card);@@ -2019,7 +2023,15 @@ fn pro_tab_title(app: &PhotocraftApp, i: usize) -> String {let mask = app.session.active_index() == Some(i) && app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some());let model = if mask { tl!("Layer Mask").to_string() } else { mode_label(&st.doc).to_string() };let layer = active_layer.map(|l| format!("{}, ", l.name)).unwrap_or_default();- format!("{} @ {}% ({layer}{model}/{}){}", st.doc.name, fmt_zoom(zoom), st.doc.depth.bits(), if st.is_dirty() { "*" } else { "" })+ // A save in progress: "name @ 100% (Layer 1, RGB/16) - Saving 45%", as Photoshop does (#3389).+ let saving = crate::jobs_ui::save_progress(app, st.doc.id).map(|s| format!(" - {s}")).unwrap_or_default();+ format!("{} @ {}% ({layer}{model}/{}){}{saving}", st.doc.name, fmt_zoom(zoom), st.doc.depth.bits(), if st.is_dirty() { "*" } else { "" })+}++/// The Studio strip's tab name: "name *" when unsaved, "name * - Saving 45%" while it saves (#3389).+fn studio_tab_name(app: &PhotocraftApp, st: &photocraft_engine::DocState) -> String {+ let saving = crate::jobs_ui::save_progress(app, st.doc.id).map(|s| format!(" - {s}")).unwrap_or_default();+ format!("{}{}{saving}", st.doc.name, if st.is_dirty() { " *" } else { "" })}/// Photoshop document tabs: "name @ 33.3% (RGB/8)" on a dark strip; active tab matches panels.diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex aecab4b54..5fb4738af 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2168,6 +2168,7 @@Opening {name} Otevírání {name}Saved {name} Uloženo: {name}Saving {name} Ukládání {name}+ Saving {percent} Ukládání {percent}A save to {name} is still running; try again when it finishes Ukládání do {name} stále probíhá; zkuste to znovu, až skončí{label} is writing the file and can no longer be cancelled {label} zapisuje soubor a už ho nelze zrušitOpening {name}… Otevírání {name}…diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 2b3f79feb..853ae997e 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2135,6 +2135,7 @@Opening {name} Öffne {name}Saved {name} Gespeichert: {name}Saving {name} Speichere {name}+ Saving {percent} Speichern {percent}A save to {name} is still running; try again when it finishes {name} wird noch gespeichert; versuchen Sie es erneut, wenn der Vorgang abgeschlossen ist{label} is writing the file and can no longer be cancelled {label} schreibt die Datei und kann nicht mehr abgebrochen werdenOpening {name}… Öffne {name}…diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 1579d5412..e3616002f 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -1583,6 +1583,7 @@Opening {name} Άνοιγμα του {name}Saved {name} Αποθηκεύτηκε το {name}Saving {name} Αποθήκευση του {name}+ Saving {percent} Αποθήκευση {percent}A save to {name} is still running; try again when it finishes Η αποθήκευση στο {name} βρίσκεται ακόμη σε εξέλιξη· δοκιμάστε ξανά όταν ολοκληρωθεί{label} is writing the file and can no longer be cancelled {label}: γίνεται εγγραφή του αρχείου και δεν μπορεί πλέον να ακυρωθείOpening {name}… Άνοιγμα του {name}…diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 13478a8cb..056c32694 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2151,6 +2151,7 @@Opening {name} Abriendo {name}Saved {name} Guardado: {name}Saving {name} Guardando {name}+ Saving {percent} Guardando {percent}A save to {name} is still running; try again when it finishes Todavía se está guardando {name}; inténtelo de nuevo cuando termine{label} is writing the file and can no longer be cancelled {label} está escribiendo el archivo y ya no se puede cancelarOpening {name}… Abriendo {name}…diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 1b86bce63..a658c2d2a 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2113,6 +2113,7 @@Opening {name} Ouverture de {name}Saved {name} Enregistré : {name}Saving {name} Enregistrement de {name}+ Saving {percent} Enregistrement {percent}A save to {name} is still running; try again when it finishes Un enregistrement de {name} est encore en cours ; réessayez lorsqu’il sera terminé{label} is writing the file and can no longer be cancelled {label} écrit le fichier et ne peut plus être annuléOpening {name}… Ouverture de {name}…diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 79582888e..dcfd7636d 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2106,6 +2106,7 @@Opening {name} Membuka {name}Saved {name} Tersimpan: {name}Saving {name} Menyimpan {name}+ Saving {percent} Menyimpan {percent}A save to {name} is still running; try again when it finishes Penyimpanan ke {name} masih berjalan; coba lagi setelah selesai{label} is writing the file and can no longer be cancelled {label} sedang menulis berkas dan tidak dapat dibatalkan lagiOpening {name}… Membuka {name}…diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 9bb31450b..f15459ed5 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2150,6 +2150,7 @@Opening {name} Apertura {name}Saved {name} Salvato: {name}Saving {name} Salvataggio {name}+ Saving {percent} Salvataggio {percent}A save to {name} is still running; try again when it finishes Un salvataggio in {name} è ancora in corso; riprova quando termina{label} is writing the file and can no longer be cancelled {label} sta scrivendo il file e non può più essere annullatoOpening {name}… Apertura {name}…diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 3142d52ad..8132248ce 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2147,6 +2147,7 @@Opening {name} {name} を開いていますSaved {name} {name} を保存しましたSaving {name} {name} を保存しています+ Saving {percent} 保存中 {percent}A save to {name} is still running; try again when it finishes {name} への保存がまだ実行中です。完了してからもう一度お試しください{label} is writing the file and can no longer be cancelled {label} はファイルを書き込み中のため、キャンセルできませんOpening {name}… {name} を開いています…diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 30a7ca878..77a0947f3 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2105,6 +2105,7 @@Opening {name} {name} 여는 중Saved {name} {name} 저장됨Saving {name} {name} 저장 중+ Saving {percent} 저장 중 {percent}A save to {name} is still running; try again when it finishes {name}에 저장하는 작업이 아직 진행 중입니다. 완료된 후 다시 시도하세요{label} is writing the file and can no longer be cancelled {label}: 파일을 쓰는 중이므로 더 이상 취소할 수 없습니다Opening {name}… {name} 여는 중…diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex 28a0effa5..97b2e911b 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -2116,6 +2116,7 @@Opening {name} {name} openenSaved {name} {name} opgeslagenSaving {name} {name} opslaan+ Saving {percent} Opslaan {percent}A save to {name} is still running; try again when it finishes Er wordt nog opgeslagen naar {name}; probeer het opnieuw zodra dat klaar is{label} is writing the file and can no longer be cancelled {label} schrijft het bestand en kan niet meer worden geannuleerdOpening {name}… {name} openen…diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex d62fdb253..f903084ac 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -2138,6 +2138,7 @@Opening {name} Otwieranie {name}Saved {name} Zapisano: {name}Saving {name} Zapisywanie {name}+ Saving {percent} Zapisywanie {percent}A save to {name} is still running; try again when it finishes Zapisywanie do {name} wciąż trwa; spróbuj ponownie, gdy się zakończy{label} is writing the file and can no longer be cancelled {label} zapisuje plik i nie można już tego anulowaćOpening {name}… Otwieranie {name}…diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex c218dfece..2030c3f20 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2110,6 +2110,7 @@Opening {name} Abrindo {name}Saved {name} Salvo: {name}Saving {name} Salvando {name}+ Saving {percent} Salvando {percent}A save to {name} is still running; try again when it finishes Um salvamento em {name} ainda está em andamento; tente novamente quando terminar{label} is writing the file and can no longer be cancelled {label} está gravando o arquivo e não pode mais ser canceladoOpening {name}… Abrindo {name}…diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 799ca6a17..16c4e57b6 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2430,6 +2430,7 @@Opening {name} Открытие {name}Saved {name} Сохранено: {name}Saving {name} Сохранение {name}+ Saving {percent} Сохранение {percent}A save to {name} is still running; try again when it finishes Сохранение в {name} ещё выполняется; повторите попытку после его завершения{label} is writing the file and can no longer be cancelled {label}: идёт запись файла, отменить уже нельзяOpening {name}… Открытие {name}…diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 177644f70..81f3482af 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -2403,6 +2403,7 @@Opening {name} Відкриття {name}Saved {name} Збережено: {name}Saving {name} Збереження {name}+ Saving {percent} Збереження {percent}A save to {name} is still running; try again when it finishes Збереження в {name} ще триває; спробуйте ще раз, коли воно завершиться{label} is writing the file and can no longer be cancelled {label}: триває запис файлу, скасувати вже не можнаOpening {name}… Відкриття {name}…diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex c0218eef1..f15a50834 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2211,6 +2211,7 @@ cameraRaw Blending 混合Opening {name} 正在打开 {name}Saved {name} 已保存 {name}Saving {name} 正在保存 {name}+ Saving {percent} 正在保存 {percent}A save to {name} is still running; try again when it finishes 仍在保存到 {name};请在完成后重试{label} is writing the file and can no longer be cancelled {label} 正在写入文件,已无法取消Opening {name}… 正在打开 {name}…diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex c51d29bb9..8548e3300 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2150,6 +2150,7 @@Opening {name} 正在開啟 {name}Saved {name} 已儲存 {name}Saving {name} 正在儲存 {name}+ Saving {percent} 正在儲存 {percent}A save to {name} is still running; try again when it finishes 仍在儲存到 {name};請在完成後再試一次{label} is writing the file and can no longer be cancelled {label} 正在寫入檔案,已無法取消Opening {name}… 正在開啟 {name}…diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rsindex 07c235846..301460fc5 100644--- a/crates/ui-egui/src/jobs_ui.rs+++ b/crates/ui-egui/src/jobs_ui.rs@@ -566,12 +566,31 @@ fn shown_fraction(j: &JobInfo) -> Option<f32> {fn percent(j: &JobInfo) -> String {// Nothing yet reported: the bar is indeterminate, so no number.- if j.progress > 0.0 { format!("{:.0}%", j.progress * 100.0) } else { String::new() }+ if j.progress > 0.0 { whole_percent(j.progress) } else { String::new() }}-/// The status bar's job readout: "Gaussian Blur ▬▬▬▭▭ 45 % ×". Draws nothing when no job runs.+/// "45%": rounded down, so a job reads 100% only once it's done.+fn whole_percent(fraction: f32) -> String {+ format!("{:.0}%", (fraction.clamp(0.0, 1.0) * 100.0).floor())+}++/// A save's progress as Photoshop words it in the status bar and the tab title: "Saving 45%"+/// (#3389).+fn saving_percent(j: &JobInfo) -> String {+ crate::i18n::fmt(tl!("Saving {percent}"), &[("percent", &whole_percent(j.progress))])+}++/// "Saving 45%" while a save of document `doc` runs, for its tab title; `None` otherwise.+pub fn save_progress(app: &PhotocraftApp, doc: DocId) -> Option<String> {+ let save = app.jobs.saves.iter().find(|s| s.doc == doc && !s.ended)?;+ app.session.job(save.job).map(|j| saving_percent(&j))+}++/// The status bar's job readout: "Gaussian Blur ▬▬▬▭▭ 45 % ×", and for a save "Saving 45% ▬▬▬▭▭ ×"+/// (the file name on hover). Draws nothing when no job runs.pub fn status_progress(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let Some(j) = job_in_view(app) else { return };+ let saving = app.jobs.saves.iter().any(|s| s.job == j.id);let t = Tokens::get(ui.ctx());let (bar_w, bar_h) = if t.pro { (120.0, 6.0) } else { (140.0, 6.0) };let more = app.session.jobs().len().saturating_sub(1);@@ -582,11 +601,17 @@ pub fn status_progress(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_dim });let xresp = xresp.on_hover_text(tl!("Cancel (Esc)"));- ui.label(RichText::new(percent(&j)).color(t.text_dim).size(11.5).monospace());+ if !saving {+ ui.label(RichText::new(percent(&j)).color(t.text_dim).size(11.5).monospace());+ }let (br, _) = ui.allocate_exact_size(vec2(bar_w, bar_h), Sense::hover());bar(ui, br, shown_fraction(&j), &t);- let label = if more > 0 { format!("{} (+{more})", tl!(&j.label)) } else { tl!(&j.label).to_owned() };- ui.label(RichText::new(label).color(t.text_dim).size(12.0));+ let name = if saving { saving_percent(&j) } else { tl!(&j.label).to_owned() };+ let label = if more > 0 { format!("{name} (+{more})") } else { name };+ let resp = ui.label(RichText::new(label).color(t.text_dim).size(12.0));+ if saving {+ resp.on_hover_text(tl!(&j.label));+ }if xresp.clicked() {cancel(app, j.id);}diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui_tests.rsindex f0c629105..1893075ac 100644--- a/crates/ui-egui/src/jobs_ui_tests.rs+++ b/crates/ui-egui/src/jobs_ui_tests.rs@@ -402,9 +402,11 @@ fn saves_run_in_the_background_and_are_recorded_when_they_end() {let st = h.state().session.active().unwrap();assert!(st.is_dirty() && st.path.is_none());assert!(h.state_mut().run("layer.new.layer", json!({})).is_err(), "the saving document is locked");- // The progress dialog and the status bar name the save; the dialog shows its stage.- assert_eq!(h.query_all_by_label("Saving big.psd").count(), 2);+ // The progress dialog names the save and shows its stage; the status bar reads "Saving 0%"+ // until the encoder reports progress (#3389).+ assert_eq!(h.query_all_by_label("Saving big.psd").count(), 1);h.get_by_label("Encoding");+ h.get_by_label("Saving 0%");gates.encode.store(true, Ordering::Relaxed);step_until(&mut h, |a| !a.saving());@@ -469,6 +471,41 @@ fn a_save_that_has_started_writing_cannot_be_cancelled() {assert!(!h.state().session.active().unwrap().is_dirty(), "the written save is recorded");}+/// #3389: like Photoshop, a running save reads "Saving 45%" in the status bar and appends+/// " - Saving 45%" to its document's tab title, in both tab strips; both go when it ends.+#[test]+fn a_running_save_shows_its_percentage_in_the_status_bar_and_tab_title() {+ for theme in crate::theme::ThemeKind::ALL {+ let mut h = app_harness();+ h.state_mut().run("prefs.set", json!({"values": {"interface.theme": theme.id()}})).unwrap();+ h.run_steps(2);+ let gate = Arc::new(AtomicBool::new(false));+ let g = gate.clone();+ let save: crate::SaveFileFn = Arc::new(move |_, _, _, ctl| {+ ctl.progress(0.4567, "Encoding");+ while !g.load(Ordering::Relaxed) {+ ctl.check()?;+ std::thread::sleep(Duration::from_millis(1));+ }+ ctl.commit()?;+ ctl.progress(1.0, "Writing");+ Ok(Vec::new())+ });+ h.state_mut().services.save_file = Some(save);+ h.state_mut().save_as(Some("/tmp/photocraft-test/pct.psd".into())).unwrap();+ let t = Instant::now();+ while h.query_by_label("Saving 45%").is_none() && t.elapsed() < Duration::from_secs(30) {+ h.step();+ }+ assert!(h.query_by_label("Saving 45%").is_some(), "{theme:?}: the status bar reads Saving 45%");+ assert!(h.query_by_label_contains(" - Saving 45%").is_some(), "{theme:?}: the tab title carries the save's progress");+ gate.store(true, Ordering::Relaxed);+ step_until(&mut h, |a| !a.saving());+ assert!(h.query_by_label_contains("Saving").is_none(), "{theme:?}: the readout and the tab suffix are gone once saved");+ assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("/tmp/photocraft-test/pct.psd"));+ }+}+/// One frame with the window's close button pressed; whether the guard cancelled the close.fn press_window_close(app: &mut PhotocraftApp) -> bool {let mut info = egui::ViewportInfo::default();