diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 78e9b63991..13d5029c20 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -1191,7 +1191,7 @@ pub fn add_outputs(s: &mut Session, rasters: Vec, dates: usize) -> CmdRe let name = r.name.clone(); let tif = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?; let file: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') { c } else { '_' }).collect(); - let layer = rustgis_map::raster::RasterLayer::from_bytes(r, format!("{file}.tif"), tif); + let layer = rustgis_map::raster::RasterLayer::from_written(r, format!("{file}.tif"), tif); let out = super::raster::add_raster(s, &name, layer)?; layers.push(out["layer"].clone()); } diff --git a/crates/engine/src/cmd/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index a7151863c7..291a8c281c 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -526,9 +526,10 @@ fn add_zones(s: &mut Session, p: &Value, d: &emb::EmbeddingDataset, name: Option let year = year(d, p)?; let b = bands(p, z.bands, tessera::DEFAULT_BANDS)?; let none = format!("{} has no embeddings there", z.name); - let (r, tif) = match handed(s, p)? { + // Whether `tif` is the file `geotiff::write` wrote of `r`, rather than one handed over. + let (r, tif, written) = match handed(s, p)? { Some((_, tif)) => match raster::read_bytes(&format!("{}.tif", z.id), &tif) { - Ok(r) if r.bands.iter().any(|band| band.stats.count > 0) => (r, tif), + Ok(r) if r.bands.iter().any(|band| band.stats.count > 0) => (r, tif, false), Ok(_) => return Err(none), Err(e) => return Err(e.to_string()), }, @@ -550,7 +551,7 @@ fn add_zones(s: &mut Session, p: &Value, d: &emb::EmbeddingDataset, name: Option s.notify(format!("{}: the view is larger than one read; its centre was read (zoom in for the rest)", z.name), false); } let tif = raster::geotiff::write(&r, 0).map_err(|e| e.to_string())?; - (r, tif) + (r, tif, true) } } }; @@ -558,7 +559,8 @@ fn add_zones(s: &mut Session, p: &Value, d: &emb::EmbeddingDataset, name: Option return Err(none); } let name = name.unwrap_or_else(|| format!("{} {year} ({})", z.name, band_label(b))); - let layer = RasterLayer::from_bytes(r, format!("{}_{year}.tif", z.id), tif); + let file = format!("{}_{year}.tif", z.id); + let layer = if written { RasterLayer::from_written(r, file, tif) } else { RasterLayer::from_bytes(r, file, tif) }; let mut out = super::raster::add_raster(s, &name, layer)?; if !d.license.is_empty() { out["license"] = json!(d.license); @@ -880,7 +882,7 @@ const IN_THE_BROWSER: &str = "AlphaEarth's similarity and change are worked out fn made_saying(r: rustgis_data::raster::Raster, notes: Vec, extra: Value) -> Result { let bytes = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?; let name = r.name.clone(); - let layer = RasterLayer::from_bytes(r, format!("{name}.tif"), bytes); + let layer = RasterLayer::from_written(r, format!("{name}.tif"), bytes); let said = name.clone(); let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { let id = v.get("layer").and_then(Value::as_u64).and_then(|i| u32::try_from(i).ok()); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 273c4ad11d..fbe1e67fe2 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -170,7 +170,7 @@ pub(crate) fn bands_param(p: &Value, r: &Raster) -> Result, String> { fn layer_of(r: Raster) -> Result { let bytes = rustgis_data::raster::geotiff::write_all(&r).map_err(|e| e.to_string())?; let fname = format!("{}.tif", r.name); - Ok(rustgis_map::RasterLayer::from_bytes(r, fname, bytes)) + Ok(rustgis_map::RasterLayer::from_written(r, fname, bytes)) } /// Adds a raster layer; classes get unique-value colours. diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 17f561c12e..a4205caf25 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6702,7 +6702,11 @@ pub fn read_cog_window_until(asked: &WindowAsked, stop: &std::sync::atomic::Atom bytes } }; - let layer = rustgis_map::RasterLayer::from_bytes(r, format!("{name}.tif"), bytes); + let layer = if plain.is_some() { + rustgis_map::RasterLayer::from_written(r, format!("{name}.tif"), bytes) + } else { + rustgis_map::RasterLayer::from_bytes(r, format!("{name}.tif"), bytes) + }; let mut notes = vec![read]; notes.extend(plain); notes.extend(finer); diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index ee94cfcca8..bee26a01b6 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -287,7 +287,7 @@ fn band(p: &Value, k: &str, r: &Raster) -> Result, String> { /// `zoom` is the adding command's `"zoom"`, as for the layers beside it. pub(crate) fn add_overlay(s: &mut Session, name: &str, r: raster::Raster, zoom: Option) -> CmdResult { let tif = raster::geotiff::write(&r, 0).map_err(|e| e.to_string())?; - add_raster_after(s, name, RasterLayer::from_bytes(r, format!("{name}.tif"), tif), zoom) + add_raster_after(s, name, RasterLayer::from_written(r, format!("{name}.tif"), tif), zoom) } /// Sets how rasters added from now on are drawn when they hold a single band of continuous values @@ -1251,10 +1251,13 @@ fn info(s: &mut Session, p: &Value) -> CmdResult { /// GeoTIFF bytes of a raster layer (band is 1-based; RGB rasters keep their colour bands; `cog` /// makes it a cloud-optimised one). pub fn geotiff_bytes(s: &mut Session, p: &Value) -> Result<(String, Vec), String> { - let (_, r) = get(s, p)?; + let (id, r) = get(s, p)?; let bi = band(p, "band", &r)?.unwrap_or(0); let cog = b(p, "cog") == Some(true); - let bytes = if cog { raster::cogwrite::write(&r, bi) } else { raster::geotiff::write(&r, bi) }.map_err(|e| e.to_string())?; + let bytes = match written_export(s, id, &r, bi, cog) { + Some(bytes) => bytes.to_vec(), + None => if cog { raster::cogwrite::write(&r, bi) } else { raster::geotiff::write(&r, bi) }.map_err(|e| e.to_string())?, + }; let note = geotiff_note(&r, bi, cog, "give \"band\" for another")?; if !note.is_empty() { s.notify(format!("Exported {}.tif{note}", r.name), false); @@ -1279,12 +1282,30 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Option>> { + if cog || raster::geotiff::written_bands(r, bi).len() != r.bands.len() { + return None; + } + s.map().layer(id).and_then(|l| l.raster.as_ref()).and_then(|rl| rl.written_file()).cloned() +} + /// Writes raster `r` (band `bi`, or its colour bands) to `path`, and says what the file holds. pub(super) fn write_geotiff(r: &Raster, bi: usize, cog: bool, path: &str) -> Result { write_geotiff_with_guidance(r, bi, cog, path, "give \"band\" for another") diff --git a/crates/engine/src/cmd/stac_bands.rs b/crates/engine/src/cmd/stac_bands.rs index 23a084d7e5..4d6cdc832f 100644 --- a/crates/engine/src/cmd/stac_bands.rs +++ b/crates/engine/src/cmd/stac_bands.rs @@ -223,7 +223,7 @@ mod desktop { rustgis_data::progress::check().map_err(|e| e.to_string())?; let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?; let layer_name = raster.name.clone(); - let mut layer = RasterLayer::from_bytes(raster, format!("{layer_name}.tif"), bytes); + let mut layer = RasterLayer::from_written(raster, format!("{layer_name}.tif"), bytes); // Drawn in colour over the range the index means something in, not grey over this window's own. let (ramp, min, max) = index_look(id); layer.style.renderer = RasterRenderer::Stretch { band: 0, ramp, invert: false }; @@ -674,7 +674,7 @@ mod desktop { rustgis_data::progress::check().map_err(|e| e.to_string())?; let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?; let name = raster.name.clone(); - let mut layer = RasterLayer::from_bytes(raster, format!("{name}.tif"), bytes); + let mut layer = RasterLayer::from_written(raster, format!("{name}.tif"), bytes); layer.style.renderer = RasterRenderer::Rgb { red: 0, green: 1, blue: 2 }; let then = noted(name.clone(), notes); Ok(super::super::workflows::made_layer(name, layer, Some(extra), Some(then))) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 529d6a4e38..d2cbaf3990 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -412,7 +412,7 @@ pub(crate) type Then = Box; pub(crate) fn made(raster: Raster, extra: Option) -> Result { let bytes = rustgis_data::raster::geotiff::write_all(&raster).map_err(|e| e.to_string())?; let name = raster.name.clone(); - let layer = rustgis_map::RasterLayer::from_bytes(raster, format!("{name}.tif"), bytes); + let layer = rustgis_map::RasterLayer::from_written(raster, format!("{name}.tif"), bytes); Ok(made_layer(name, layer, extra, None)) } diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 071596b8fe..0f519b8a52 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -547,7 +547,7 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { let mut layer = if sel.window.is_some() { r.source = Some(full.clone()); let tif = zarr::write_project_slice(&r).map_err(|e| e.to_string())?; - let mut layer = RasterLayer::from_bytes(r, format!("{}.tif", store_name(&full)), tif); + let mut layer = RasterLayer::from_written(r, format!("{}.tif", store_name(&full)), tif); layer.path = Some(full); layer } else { @@ -579,7 +579,7 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { // The writer refuses systems its keys cannot preserve, as for a directory window or // a slice handed over by the UI. let tif = zarr::write_project_slice(&r).map_err(|e| e.to_string())?; - let mut layer = RasterLayer::from_bytes(r, format!("{}.tif", store_name(&u)), tif); + let mut layer = RasterLayer::from_written(r, format!("{}.tif", store_name(&u)), tif); layer.subdataset = Some(sel.label()); // The coordinate system given for a store that doesn't say, kept as a folder's slice // keeps it, so a time series read from the layer finds it. @@ -2025,7 +2025,7 @@ fn reduce(s: &mut Session, p: &Value) -> CmdResult { let run = reduce_start(s, p)?; let r = run.run(&std::sync::atomic::AtomicBool::new(false), &std::sync::atomic::AtomicUsize::new(0))?; let tif = zarr::write_project_slice(&r).map_err(|e| e.to_string())?; - let mut layer = RasterLayer::from_bytes(r, format!("{}.tif", store_name(&run.root)), tif); + let mut layer = RasterLayer::from_written(r, format!("{}.tif", store_name(&run.root)), tif); layer.subdataset = None; let mut out = super::raster::add_raster(s, &run.name, layer)?; out["steps"] = serde_json::json!(run.total()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index af5180eb7a..041838b684 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -18971,6 +18971,41 @@ fn hillshade_is_made_and_written_as_bytes() { std::fs::remove_dir_all(&dir).ok(); } +/// A made raster embeds the bytes an encode would write, and its plain export writes the file the +/// layer embeds; once its pixels change, the export encodes them. +#[test] +fn exporting_a_made_raster_writes_its_embedded_file_until_its_pixels_change() { + let mut s = world(); + s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": dem_b64()})).unwrap(); + let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); + let v = s.run("raster.function", &json!({"layer": dem, "function": "hillshade", "name": "hill"})).unwrap(); + let id = v["layer"].as_u64().unwrap() as u32; + let rl = s.map().layer(id).unwrap().raster.clone().unwrap(); + let embedded = rl.embedded.clone().unwrap(); + assert_eq!(embedded.as_slice(), rustgis_data::raster::geotiff::write(rl.data.as_ref().unwrap(), 0).unwrap().as_slice()); + let dir = std::env::temp_dir().join(format!("rustgis-written-export-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // Marked bytes in its place show which file the export writes: a fresh encode wouldn't hold them. + let marked = [embedded.as_slice(), b"written"].concat(); + let pixels = rl.data.clone().unwrap(); + drop(rl); + s.map_mut().layer_mut(id).unwrap().raster = + Some(rustgis_map::RasterLayer::from_written(std::sync::Arc::unwrap_or_clone(pixels), "hill.tif", marked.clone())); + let tif = dir.join("hill.tif"); + s.run("share.exportRaster", &json!({"layer": id, "path": tif.display().to_string()})).unwrap(); + assert_eq!(std::fs::read(&tif).unwrap(), marked); + // The browser's download takes the same file; a cloud-optimised one is encoded. + assert_eq!(crate::cmd::raster::geotiff_bytes(&mut s, &json!({"layer": id})).unwrap().1, marked); + assert_ne!(crate::cmd::raster::geotiff_bytes(&mut s, &json!({"layer": id, "cog": true})).unwrap().1, marked); + let rl = s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap(); + let band = &mut std::sync::Arc::make_mut(rl.data.as_mut().unwrap()).bands[0]; + band.data[0] = if band.data[0] == 7.0 { 8.0 } else { 7.0 }; + let changed = band.data[0]; + s.run("share.exportRaster", &json!({"layer": id, "path": tif.display().to_string()})).unwrap(); + assert_eq!(rustgis_data::raster::read_path(&tif).unwrap().bands[0].data[0], changed); + std::fs::remove_dir_all(&dir).ok(); +} + #[test] fn exporting_a_raster_as_a_cog() { let mut s = world(); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 5df1209661..b0fa2ee2c8 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -110,6 +110,11 @@ pub struct RasterLayer { /// [`RasterLayer::dropped_unsaid`]). #[serde(skip)] dropped: Vec<&'static str>, + /// The pixels and the file that `embedded` was written from them as, while both are still the + /// layer's (see [`RasterLayer::written_file`]): held weakly, so a change to either, which takes + /// a new allocation, breaks the pairing. + #[serde(skip)] + written: Option<(Weak, Weak>)>, } /// Called once with a cloud-optimised GeoTIFF's overview, or why it couldn't be read. @@ -333,6 +338,7 @@ impl RasterLayer { lost_said: false, look_lost: None, dropped: Vec::new(), + written: None, }) } @@ -383,6 +389,7 @@ impl RasterLayer { lost_said: false, look_lost: None, dropped: Vec::new(), + written: None, } } @@ -391,6 +398,24 @@ impl RasterLayer { Self::from_shared(raster, file_name, Arc::new(bytes)) } + /// A raster with the file [`rustgis_data::raster::geotiff::write_all`] wrote of it (or + /// [`rustgis_data::raster::geotiff::write`] of its first band, the same file when that writes every + /// band), kept in the project: [`RasterLayer::written_file`] gives that file back while neither + /// changes. + pub fn from_written(raster: Raster, file_name: impl Into, bytes: Vec) -> RasterLayer { + let mut layer = Self::from_bytes(raster, file_name, bytes); + layer.written = layer.data.as_ref().map(Arc::downgrade).zip(layer.embedded.as_ref().map(Arc::downgrade)); + layer + } + + /// The embedded file, when it is the one [`RasterLayer::from_written`] was given for the + /// pixels the layer holds now: an export that writes every band writes those same bytes. + pub fn written_file(&self) -> Option<&Arc>> { + let (pixels, file) = self.written.as_ref()?; + let (data, embedded) = (self.data.as_ref()?, self.embedded.as_ref()?); + (Weak::as_ptr(pixels) == Arc::as_ptr(data) && Weak::as_ptr(file) == Arc::as_ptr(embedded)).then_some(embedded) + } + /// Keeps the original shared allocation used to decode an uploaded raster. pub fn from_shared(raster: Raster, file_name: impl Into, bytes: Arc>) -> RasterLayer { let style = RasterStyle::default_for(&raster); @@ -421,6 +446,7 @@ impl RasterLayer { lost_said: false, look_lost: None, dropped: Vec::new(), + written: None, } } @@ -465,6 +491,7 @@ impl RasterLayer { lost_said: false, look_lost: None, dropped: Vec::new(), + written: None, } } @@ -896,6 +923,7 @@ impl RasterLayer { lost_said: _, look_lost: _, dropped: _, + written: _, } = self; if *in_place || *tiled || opening.is_some() || read_still.is_some() || self.casts_shadows() { return None; @@ -2602,6 +2630,7 @@ impl RasterLayer { lost_said: _, look_lost: _, dropped: _, + written: _, } = self; let mut out = Vec::new(); if let Some(p) = path { @@ -3217,6 +3246,25 @@ mod tests { assert!(missing.data.is_none()); } + #[test] + fn a_written_file_is_given_back_only_while_its_pixels_and_bytes_are_the_layers() { + let r = dem(); + let bytes = rustgis_data::raster::geotiff::write_all(&r).unwrap(); + assert!(RasterLayer::from_bytes(r.clone(), "dem.tif", bytes.clone()).written_file().is_none()); + let written = RasterLayer::from_written(r, "dem.tif", bytes.clone()); + assert_eq!(written.written_file().map(|b| b.as_slice()), Some(bytes.as_slice())); + // A copy shares both, so it gives the file too. + assert!(written.clone().written_file().is_some()); + let mut edited = written.clone(); + if let Some(band) = edited.data.as_mut().and_then(|d| Arc::make_mut(d).bands.first_mut()) { + band.data[0] += 1.0; + } + assert!(edited.written_file().is_none()); + let mut replaced = written.clone(); + replaced.embedded = Some(Arc::new(bytes)); + assert!(replaced.written_file().is_none()); + } + /// A plain web address is read as it was before logins: never downloaded whole on reload. #[test] fn reload_downloads_only_s3_and_login_wrapped_addresses() {