diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index aeefa0d900..4be9c65a2b 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -243,6 +243,8 @@ pub struct Layout { /// a colour table too short for its pixels. One line each, for a window to say (AGENTS.md, /// Never silent); drawing in place shows the file grey without them, as before. pub lost: Vec, + /// Who holds the rights to the picture (its Copyright tag), as [`super::Raster::copyright`]. + pub copyright: Option, } impl Layout { @@ -393,6 +395,25 @@ fn read_layout(r: Sparse) -> Result { }; // Another body's system is said, as when the file is read whole. let mut lost: Vec = super::planetary::note_of(geo.0).into_iter().collect(); + // A datum assumed, and the file's copyright, as when it is read whole. + if geo.3 { + lost.push(super::geotiff::NO_EPSG_GEOGRAPHIC.to_string()); + } + // Its bytes asked for when not read yet, as the other tags' are. + let copyright = match tag(&mut dec, Tag::Copyright)? { + Ok(None) => None, + Ok(Some(v)) => match v.into_string() { + Ok(c) => Some(c.trim().to_string()), + Err(e) => { + lost.push(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out")); + None + } + }, + Err(e) => { + lost.push(format!("its Copyright tag: it can't be read ({e}), so it is left out")); + None + } + }; let palette = match color { ColorHint::Gray if palette_image => match tag(&mut dec, Tag::ColorMap)? { Ok(None) => { @@ -623,6 +644,7 @@ fn read_layout(r: Sparse) -> Result { palette, described, lost, + copyright, }))) } @@ -794,6 +816,8 @@ pub struct Example { /// Overviews half the size before them rounded down (500 of 1001), as terrio 0.8 writes /// them; GDAL rounds up (501). pub rounded_down: bool, + /// Geographic without an EPSG code (no GeographicTypeGeoKey): read as WGS 84, said. + pub no_epsg: bool, } impl Default for Example { @@ -818,6 +842,7 @@ impl Default for Example { no_overviews: false, wavelengths: false, rounded_down: false, + no_epsg: false, } } } @@ -950,7 +975,11 @@ pub fn example_with(e: &Example) -> Vec { t.push((33550, V::D(vec![px, px, 0.0]))); t.push((33922, V::D(vec![0.0, 0.0, 0.0, 10.0, 46.0, 0.0]))); } - t.push((34735, V::S(vec![1, 1, 0, 2, 1024, 0, 1, 2, 2048, 0, 1, 4326]))); + if e.no_epsg { + t.push((34735, V::S(vec![1, 1, 0, 1, 1024, 0, 1, 2]))); + } else { + t.push((34735, V::S(vec![1, 1, 0, 2, 1024, 0, 1, 2, 2048, 0, 1, 4326]))); + } if e.classes { let xml = if e.lossy { r#"Forest FormationFar"# @@ -1110,6 +1139,36 @@ pub(crate) mod tests { assert!(take_tiles(&mut allowance, 1).is_err()); } + /// What reading the file whole says of its header, reading it in place says too: a datum + /// assumed for a geographic file without an EPSG code; a clean file says nothing and has no + /// copyright, and one written with a copyright keeps it. + #[test] + fn a_layout_says_an_assumed_datum_and_keeps_the_copyright() { + let layout_of = |file: Vec| match layout(&Sparse::default().with(0, file)) { + Ok(Parse::Done(l)) => l, + _ => panic!("not a COG"), + }; + let clean = layout_of(example(64, 32)); + assert!(clean.lost.is_empty() && clean.copyright.is_none(), "{:?}", clean.lost); + let assumed = layout_of(example_with(&Example { size: 64, tile: 32, no_epsg: true, ..Example::default() })); + assert_eq!(assumed.lost, vec![super::super::geotiff::NO_EPSG_GEOGRAPHIC.to_string()]); + let mut r = crate::raster::Raster::new( + "credited", + 64, + 64, + vec![vec![1.0; 64 * 64]], + crate::raster::GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.01, pixel_height: -0.01 }, + crate::raster::Crs::LonLat, + None, + crate::raster::ColorHint::Gray, + "UInt8", + ) + .unwrap(); + r.copyright = Some("Example Survey".into()); + let credited = layout_of(super::super::cogwrite::write(&r, 0).unwrap()); + assert_eq!(credited.copyright.as_deref(), Some("Example Survey")); + } + #[test] fn layout_from_the_header_then_tiles_one_by_one() { let file = example(1024, 256); diff --git a/crates/data/src/raster/file_revision.rs b/crates/data/src/raster/file_revision.rs index 5e465ed88b..8363d998e4 100644 --- a/crates/data/src/raster/file_revision.rs +++ b/crates/data/src/raster/file_revision.rs @@ -4,7 +4,7 @@ use std::{fs::Metadata, path::Path}; #[derive(Clone, Debug, PartialEq, Eq)] -pub(super) struct FileRevision { +pub struct FileRevision { len: u64, modified: std::time::SystemTime, #[cfg(unix)] @@ -16,7 +16,7 @@ pub(super) struct FileRevision { impl FileRevision { /// The path a revision was read from is not part of it: the callers check the path they hold, /// so a changed working directory never looks like a changed file. - pub(super) fn capture(metadata: &Metadata) -> std::io::Result { + pub fn capture(metadata: &Metadata) -> std::io::Result { #[cfg(unix)] use std::os::unix::fs::MetadataExt; #[cfg(windows)] @@ -41,7 +41,21 @@ impl FileRevision { } } +impl FileRevision { + /// The revision of the file at `path` as it is now, or `None` when its metadata can't be read. + pub fn of(path: &Path) -> Option { + std::fs::metadata(path).ok().and_then(|m| Self::capture(&m).ok()) + } +} + impl super::Raster { + /// Records `revision` as that of the file its pixels came from: for pixels another reader + /// assembled from the file (a GeoTIFF on this computer read in place), checked against it as + /// they were read, so the checks that pair later reads of the file with them can be made. + pub fn set_source_revision(&mut self, revision: FileRevision) { + self.source_file = Some(Ok(revision)); + } + fn original_revision(&self) -> std::result::Result<&FileRevision, String> { match &self.source_file { Some(Ok(original)) => Ok(original), diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 13491401b5..215874f700 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -315,11 +315,12 @@ fn geo_tags_with_keys(dec: &mut Decoder, keys: &[u16]) -> Res /// A cloud-optimised GeoTIFF's coordinate system, georeferencing and no-data value, from its first /// image (as [`read`] finds them); `None` for a rotated or skewed image, or one with no GeoTIFF /// tags (a scan), which is read whole. -pub(crate) fn cog_geo(dec: &mut Decoder) -> Result)>> { +pub(crate) fn cog_geo(dec: &mut Decoder) -> Result, bool)>> { let geo = geo_tags(dec)?; if geo.affine.is_some() || !geo.referenced { return Ok(None); } + let assumed = geo.crs.is_none() && geo.geographic_model; let crs = match geo.crs { Some(c) => c, None if geo.geographic_model => Crs::LonLat, @@ -333,7 +334,22 @@ pub(crate) fn cog_geo(dec: &mut Decoder) -> Result(dec: &mut Decoder) -> std::result::Result, String> { + match dec.find_tag(Tag::Copyright).map(|v| v.map(|v| v.into_string())) { + Ok(None) => Ok(None), + Ok(Some(Ok(c))) => Ok(Some(c.trim().to_string())), + Ok(Some(Err(e))) => Err(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out")), + Err(e) => Err(format!("its Copyright tag: it can't be read ({e}), so it is left out")), + } } #[cfg(test)] @@ -1527,11 +1543,9 @@ pub(super) fn read_limited_with_nodata( // Who holds the rights to the picture, kept as it reads so an export of it says so too (the // writers make it the ASCII a tag holds, and the exports say what that changed); one that // doesn't read as text is left out, and said. - let (copyright, copyright_lost) = match dec.find_tag(Tag::Copyright).map(|v| v.map(|v| v.into_string())) { - Ok(None) => (None, None), - Ok(Some(Ok(c))) => (Some(c.trim().to_string()), None), - Ok(Some(Err(e))) => (None, Some(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out"))), - Err(e) => (None, Some(format!("its Copyright tag: it can't be read ({e}), so it is left out"))), + let (copyright, copyright_lost) = match copyright_tag(&mut dec) { + Ok(c) => (c, None), + Err(e) => (None, Some(e)), }; let spp = samples(&mut dec); let full_alpha = extra_alpha(&mut dec); @@ -1842,11 +1856,7 @@ pub(super) fn read_limited_with_nodata( "its own coordinate system can't be read ({})", e.strip_prefix("GeoTIFF: ").unwrap_or(e) )), - None if geo.geographic_model => { - "its geographic coordinate system has no EPSG code, so its datum isn't read; its coordinates are \ - read as longitude/latitude on WGS 84" - .to_string() - } + None if geo.geographic_model => NO_EPSG_GEOGRAPHIC.to_string(), None => super::assumed_wgs84_note("it doesn't say its coordinate system"), }); Crs::LonLat diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index a5de7c420d..cfed852fc2 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -16,6 +16,8 @@ pub mod dted; #[cfg(not(target_arch = "wasm32"))] mod file_revision; #[cfg(not(target_arch = "wasm32"))] +pub use file_revision::FileRevision; +#[cfg(not(target_arch = "wasm32"))] pub mod gdal; pub mod geotiff; pub mod grib; diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index db40af40fe..230e4c586d 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -395,7 +395,7 @@ pub fn external_start(s: &mut Session, tool: &str, params: &Value) -> Result Result inputs, // A Cancel while the inputs are read names the tool, as one while it runs does. Err(_) if control.is_cancelled() => { @@ -1309,6 +1314,11 @@ struct MapInputs<'a> { /// Import warnings from local file inputs, kept in the tool result and history. messages: Vec, losses: Vec, + /// Raster layers read in place from a file on this computer, read again from it for the run + /// ([`tiled_inputs`]), by lowercase name. + rasters: std::collections::HashMap>, + /// [`MapInputs::rasters`] counted as held while the run holds them (kept only to be dropped). + _held: Vec>, /// The flat map's projection (its name, the projection and its unit in metres), built the /// first time a tool asks for it (Tissot's indicatrix does), once for the run; `None` on the /// globe. @@ -1363,14 +1373,50 @@ impl MapInputs<'_> { } } -fn map_inputs<'a>(s: &'a Session, spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> Result, String> { - inputs_of(Snapshot::of(s), spec, params) +/// How a tool's inputs read a raster layer read in place from a file on this computer +/// ([`rustgis_map::raster::RasterLayer::tiled`]). +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Tiled { + /// From the file, at the finest level the run can hold ([`tiled_inputs`]): a built-in tool's + /// run, on its own thread or where the caller waits. + File, + /// The overview the layer holds, said: a plugin's run, whose inputs are read on the app's + /// thread. + Overview, + /// By its path: a suite tool stages the file itself. + ByPath, +} + +/// How a run of `pin` reads a raster read in place from a file ([`Tiled`]): a plugin reads the +/// overview the layer holds, a suite tool stages the file by its path, a built-in tool reads it. +fn tiled_for(pin: &crate::policy::ToolPin) -> Tiled { + #[cfg(feature = "geolibre")] + if pin.resolved().source() == Some(rustgis_geolibre::SOURCE) { + return Tiled::ByPath; + } + if pin.plugin().is_some() { Tiled::Overview } else { Tiled::File } +} + +/// [`inputs_of`] from the session as it is; `tiled` as there. +fn map_inputs<'a>( + s: &'a Session, + spec: Option<&rustgis_analysis::ToolSpec>, + params: &Value, + tiled: Tiled, +) -> Result, String> { + inputs_of(Snapshot::of(s), spec, params, tiled) } /// A tool's inputs from what it read of the session: the streamed layers and files it names read /// whole, and the rows of each layer it runs on. It reads, so a background run does this on its -/// thread. -fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> Result, String> { +/// thread. `tiled` says how the raster layers it reads that are read in place from a file on this +/// computer are read ([`Tiled`]). +fn inputs_of<'a>( + snap: Snapshot<'a>, + spec: Option<&rustgis_analysis::ToolSpec>, + params: &Value, + tiled: Tiled, +) -> Result, String> { let (full, said) = streamed_inputs(&snap.map, spec, params)?; let (mut messages, mut losses) = (Vec::new(), Vec::new()); for m in said { @@ -1401,6 +1447,15 @@ fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, let mut rows = env_inputs(&snap.map, &full, &snap.env, params)?; narrow_to_queries(&snap.map, spec, params, &full, &mut rows, &mut messages)?; let unread = if work == Crs::LonLat { std::collections::HashSet::new() } else { attributes_only(spec, params) }; + #[cfg(not(target_arch = "wasm32"))] + let mut held = Vec::new(); + #[cfg(not(target_arch = "wasm32"))] + let rasters = tiled_inputs(&snap.map, spec, params, tiled, &mut messages, &mut held)?; + #[cfg(target_arch = "wasm32")] + let (rasters, held) = { + let _ = tiled; + (std::collections::HashMap::new(), Vec::new()) + }; Ok(MapInputs { snap, rows, @@ -1409,11 +1464,213 @@ fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, unread, messages, losses, + rasters, + _held: held, flat: std::cell::OnceCell::new(), view: std::cell::OnceCell::new(), }) } +/// The raster layers `spec`'s parameters name that are read in place from a file on this +/// computer ([`rustgis_map::raster::RasterLayer::tiled`]), each read again from the file for the +/// run, by lowercase name: such a layer holds only the small overview the map draws from zoomed +/// out, and a tool reads the finest level of the file it can hold, the full image when it fits +/// (#2761). Read on the run's thread; one read from an overview is said. The GeoTIFF reader looks +/// at Cancel between its chunks through the progress probe, which a run from [`tool_start`] +/// installs before reading its inputs; a run made where the caller waits stops there only when +/// the caller installed one, else after the read. +/// Read only for [`Tiled::File`]: for [`Tiled::Overview`] each such layer's held overview is said, +/// and for [`Tiled::ByPath`] nothing is read or said, but a file no longer there is refused. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn tiled_inputs( + map: &rustgis_map::Map, + spec: Option<&rustgis_analysis::ToolSpec>, + params: &Value, + tiled: Tiled, + messages: &mut Vec, + held: &mut Vec>, +) -> Result>, String> { + use rustgis_analysis::ParamKind; + let mut read = std::collections::HashMap::new(); + // Raster to PMTiles draws its input as the map does, in place at each zoom's level, and + // reads no pixels through the run's inputs. + let Some(spec) = spec.filter(|t| t.id != "rasterToPmtiles") else { return Ok(read) }; + let mut seen = std::collections::HashSet::new(); + let (mut overviews, mut held_overviews, mut rounded) = (Vec::new(), Vec::new(), Vec::new()); + for parameter in spec.params { + let value = params.get(parameter.name).unwrap_or(&Value::Null); + let names: Vec<&str> = match parameter.kind { + ParamKind::RasterLayer => value.as_str().into_iter().collect(), + ParamKind::RasterLayers => rustgis_analysis::layer_list(value).unwrap_or_default(), + // A suite tool stages any layer a parameter names, whatever its kind. + _ if tiled == Tiled::ByPath => match value { + Value::String(t) => t.split(';').map(str::trim).collect(), + Value::Array(v) => v.iter().filter_map(Value::as_str).collect(), + _ => continue, + }, + _ => continue, + }; + for name in names { + let Some(l) = map.layer_by_name(name) else { continue }; + let key = l.name.to_ascii_lowercase(); + let Some(path) = l.raster.as_ref().filter(|rl| rl.tiled).and_then(|rl| rl.path.as_deref()) else { continue }; + if !seen.insert(key.clone()) { + continue; + } + // A suite tool stages the file by its path: one no longer there would have it stage + // the overview the layer holds instead, so it is refused. + if tiled == Tiled::ByPath { + if !std::path::Path::new(path).is_file() { + return Err(format!("{}: its file {path} is no longer there: Reload Data or Repair Data Source first", l.name)); + } + continue; + } + if tiled == Tiled::Overview { + if let Some(held) = l.raster.as_ref().and_then(|rl| rl.data.as_ref()) + && let Some((fw, fh)) = held.overview + { + held_overviews + .push(format!("{} at the {} × {} overview of the {fw} × {fh} raster it holds", l.name, held.width, held.height)); + } + continue; + } + let (r, count) = match BATCH_READS.with(|b| b.borrow().as_ref().and_then(|reads| reads.get(path).cloned())) { + Some(kept) => kept, + None => { + #[cfg(test)] + TILED_READS.with(|n| n.set(n.get() + 1)); + // The last file a batch read alone: let go before another is read, so a batch + // over several files holds one, and doesn't hold it uncounted while the next + // is planned. + BATCH_READS.with(|b| { + if let Some(reads) = b.borrow_mut().as_mut() { + reads.clear(); + } + }); + let _turn = tiled_turn().map_err(|e| format!("{}: {e}", l.name))?; + let r = std::sync::Arc::new( + rustgis_data::raster::read_path_with(std::path::Path::new(path), None, None) + .map_err(|e| format!("{}: {e}", l.name))?, + ); + // Counted as held from before the next run's turn, for as long as anything + // (this run, the batch) holds it. + let bytes: usize = r.bands.iter().map(|b| b.data.len().saturating_mul(4)).sum(); + let count = std::sync::Arc::new(rustgis_data::memory::Holding::of(bytes as u64)); + BATCH_READS.with(|b| { + if let Some(reads) = b.borrow_mut().as_mut() { + reads.insert(path.to_string(), (r.clone(), count.clone())); + } + }); + (r, count) + } + }; + held.push(count); + let n: u64 = r.rounded.iter().sum(); + if n > 0 { + rounded.push(format!("{} {n}", l.name)); + } + if let Some((fw, fh)) = r.overview { + overviews.push(format!("{} at its {} × {} overview of the {fw} × {fh} raster", l.name, r.width, r.height)); + } + read.insert(key, r); + } + } + // Said once for the run, every raster named. + if !held_overviews.is_empty() { + messages.push(format!( + "read as the layer holds it, as plugin tools don't read a raster read in place from its file: {}", + held_overviews.join("; ") + )); + } + if !rounded.is_empty() { + messages.push(format!( + "values rounded to 32-bit floats as the file was read for the run, the tool's results built on them: {}", + rounded.join("; ") + )); + } + if !overviews.is_empty() { + messages.push(format!("read at the finest level each can hold: {}", overviews.join("; "))); + } + Ok(read) +} + +/// A raster file read in place for a run, and its count in [`rustgis_data::memory::held`], which +/// lasts as long as anything holds it. +#[cfg(not(target_arch = "wasm32"))] +type CountedRead = (std::sync::Arc, std::sync::Arc); + +/// Taken by each read of a raster file read in place for a run ([`tiled_inputs`]): such reads +/// run one at a time across runs, so each plans its size with the ones before it held. +#[cfg(not(target_arch = "wasm32"))] +static TILED_TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// [`TILED_TURN`], waited for while another run reads, looking at the run's Cancel every 50 ms +/// (through the progress probe it installed). +#[cfg(not(target_arch = "wasm32"))] +fn tiled_turn() -> rustgis_data::Result> { + loop { + match TILED_TURN.try_lock() { + Ok(turn) => return Ok(turn), + Err(std::sync::TryLockError::Poisoned(e)) => return Ok(e.into_inner()), + Err(std::sync::TryLockError::WouldBlock) => { + rustgis_data::progress::check()?; + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +thread_local! { + /// The raster file read in place that a batch's items last read ([`tiled_inputs`]), by path, + /// kept while the batch runs on this thread ([`BatchReads`]): items reading the same file read + /// it once, not once an item, and a batch over several files holds one at a time. `None` + /// outside a batch, where nothing is kept past the run. + static BATCH_READS: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +thread_local! { + /// How many raster files read in place [`tiled_inputs`] has read from their file on this + /// thread, under test. + pub(crate) static TILED_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Whether a batch's reads are kept on this thread now ([`BATCH_READS`]), under test. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn batch_reads_kept() -> bool { + BATCH_READS.with(|b| b.borrow().is_some()) +} + +/// Keeps [`BATCH_READS`] while it lives: the outermost batch on this thread starts it and lets +/// it go, so a file it read is held only as long as the batch runs. +#[cfg(not(target_arch = "wasm32"))] +struct BatchReads(bool); + +#[cfg(not(target_arch = "wasm32"))] +impl BatchReads { + fn start() -> BatchReads { + BatchReads(BATCH_READS.with(|b| { + let mut b = b.borrow_mut(); + let outer = b.is_none(); + if outer { + *b = Some(std::collections::HashMap::new()); + } + outer + })) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for BatchReads { + fn drop(&mut self) { + if self.0 { + BATCH_READS.with(|b| *b.borrow_mut() = None); + } + } +} + /// Narrows the rows a tool reads of each layer to the features its definition query keeps, as the /// map draws them (#1995): a selection is cut to its drawn features, and a layer without one (or /// with only the environment's extent) reads the kept features instead of every one. A layer whose @@ -1990,9 +2247,11 @@ impl Inputs for MapInputs<'_> { *self.view.get_or_init(|| view_extent(&self.snap)) } fn raster(&self, layer: &str) -> Option> { - let rl = self.snap.map.layer_by_name(layer)?.raster.as_ref()?; + let l = self.snap.map.layer_by_name(layer)?; + let rl = l.raster.as_ref()?; + let read = self.rasters.get(&l.name.to_ascii_lowercase()).map(std::sync::Arc::as_ref); Some(RasterInput { - raster: rl.data.as_deref()?, + raster: read.or(rl.data.as_deref())?, path: rl.path.as_deref(), embedded: rl.embedded.as_deref().map(|b| (rl.file_name.as_deref().unwrap_or("raster.tif"), b.as_slice())), }) @@ -2038,6 +2297,9 @@ fn batch(s: &mut Session, p: &Value) -> CmdResult { /// Runs a geoprocessing tool in batch across multiple layers or files with cancellation and progress reporting. pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc) -> CmdResult { + // A raster file read in place is read once for the batch, not once an item. + #[cfg(not(target_arch = "wasm32"))] + let _reads = BatchReads::start(); let tool_name = ps(p, "tool").ok_or("tool is required")?; let tool_id = tool_id(tool_name).ok_or_else(|| format!("no tool '{tool_name}'"))?; let spec = rustgis_analysis::tool(tool_id).ok_or_else(|| format!("no tool '{tool_name}'"))?; @@ -3100,7 +3362,13 @@ pub(crate) fn execute( } #[cfg(not(target_arch = "wasm32"))] let read = recording.then(|| Snapshot::owned(s)); - let inputs = match map_inputs(s, Some(spec), params) { + // Reading the inputs stops on Cancel too, as a run the app starts on a thread does. + #[cfg(not(target_arch = "wasm32"))] + let _probe = rustgis_analysis::control::install_progress(Some(control.clone())); + // A built-in tool run here (the command line, a script on its own thread) reads a + // raster file read in place, as one the app starts on a thread does. + let tiled = tiled_for(pin); + let inputs = match map_inputs(s, Some(spec), params, tiled) { Ok(inputs) => inputs, // A batch item that can't read its input is kept in the history as a failed run. Err(e) if opts.record.is_some() => return apply_with(s, run_of(t0), kept(), Err(e), now_ms().saturating_sub(t0), opts), diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index c62ef7ecfa..d4e9454b37 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -402,7 +402,7 @@ pub(super) fn read_notices(s: &mut Session, name: &str, layer: &mut RasterLayer) let lost = layer.lost_unsaid(); let pixels = layer.pixels_unsaid(); if let Some(r) = pixels.as_deref() - && let Some((fw, fh)) = r.overview.filter(|_| !layer.in_place) + && let Some((fw, fh)) = r.overview.filter(|_| !layer.reads_in_place()) { s.notify(format!("{name}: showing a {} × {} overview of the {fw} × {fh} raster", r.width, r.height), false); } @@ -410,12 +410,24 @@ pub(super) fn read_notices(s: &mut Session, name: &str, layer: &mut RasterLayer) s.notify(format!("{name}: {loss}"), false); } if let Some(r) = pixels.as_deref() { - if let Some(held) = layer.in_place.then(|| crate::in_place_overview(r)).flatten() { + if let Some(held) = layer.reads_in_place().then(|| crate::in_place_overview(r, layer.tiled)).flatten() { s.notify(format!("{name}: {held}"), false); } if let Some(count) = rounded_count(r) { let held = "pixels are held as 32-bit floats, exact for whole numbers up to 16,777,216 and to about 7 significant digits"; - s.notify(format!("{name}: {count} rounded as the file was read: {held}, so an export writes the rounded values"), false); + // Read in place, the count is of the overview held; the finer levels the map and an + // export draw round their own values too, not counted. + if layer.reads_in_place() { + s.notify( + format!( + "{name}: {count} rounded in its {} × {} overview as it was read: {held}, so the map and an export, which read finer levels too, show rounded values there and in more places", + r.width, r.height + ), + false, + ); + } else { + s.notify(format!("{name}: {count} rounded as the file was read: {held}, so an export writes the rounded values"), false); + } } } } @@ -567,7 +579,7 @@ pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) { /// Opens a raster file by path; `ignored` is said with what reading it lost (options given that /// don't apply to it). pub fn add_path(s: &mut Session, path: &str, name: Option<&str>, page: Option<&str>, scan: bool, ignored: Option) -> CmdResult { - let mut r = match super::reads::take(s, &read_key(path, page, scan)) { + let (mut r, tiled) = match super::reads::take::(s, &read_key(path, page, scan)) { Some(r) => r, None => read_raster_as(path, page, scan), }?; @@ -580,7 +592,7 @@ pub fn add_path(s: &mut Session, path: &str, name: Option<&str>, page: Option<&s // gives plain paths on Windows rather than `\\?\` ones). let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string()); // A scan is laid over the view as it is added, and that placement makes it reopen as one. - let mut rl = RasterLayer::from_path(r, full); + let mut rl = if tiled { RasterLayer::tiled_file(r, full) } else { RasterLayer::from_path(r, full) }; // A PDF's page, kept so the project opens the same page again. rl.subdataset = page.map(str::to_string); add_raster(s, &name, rl) @@ -637,12 +649,84 @@ pub fn read_download_shared_page(name: &str, bytes: std::sync::Arc>, pag raster::read_shared_page(name, bytes, page, place).map_err(|e| format!("{name}: {e}")) } -/// The raster at `path` (a PDF's `page`), read whole; for a `scan`, as the file holds it, without -/// the world file beside it (#2075). -pub(crate) fn read_raster_as(path: &str, page: Option<&str>, scan: bool) -> Result { +/// The raster at `path` (a PDF's `page`), read whole, or for a large tiled GeoTIFF on this +/// computer its overview, read in place ([`tiled_in_place`]); for a `scan`, as the file holds it, +/// without the world file beside it (#2075). +pub(crate) fn read_raster_as(path: &str, page: Option<&str>, scan: bool) -> RasterRead { + // A large tiled GeoTIFF: its overview, the part in view read as the map draws. Read whole + // as before when its overview can't be read after all. + #[cfg(not(target_arch = "wasm32"))] + if !scan && page.is_none() { + let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string()); + if tiled_in_place(&full) + && let Ok(mut r) = crate::render::rustgis_tiles::cog::raster::overview_blocking(&full) + { + r.name = Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or("raster").to_string(); + return Ok((r, true)); + } + } let p = Path::new(path); let read = if scan { raster::read_path_unplaced(p, page, None) } else { raster::read_path_with(p, page, None) }; - read.map_err(|e| format!("{path}: {e}")) + read.map(|r| (r, false)).map_err(|e| format!("{path}: {e}")) +} + +/// The most samples a raster file is held whole with: [`raster::max_samples`], or under test what +/// [`HELD_WHOLE`] sets on this thread, as no small fixture reaches the real limit. +#[cfg(not(target_arch = "wasm32"))] +fn held_whole() -> usize { + #[cfg(test)] + if let Some(max) = HELD_WHOLE.with(std::cell::Cell::get) { + return max; + } + raster::max_samples() +} + +#[cfg(test)] +thread_local! { + /// [`held_whole`]'s limit on this thread, under test. + pub(crate) static HELD_WHOLE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// A raster file read for [`add_path`]: its pixels, and whether they are the overview of a large +/// tiled GeoTIFF read in place ([`tiled_in_place`]). +pub(crate) type RasterRead = Result<(Raster, bool), String>; + +/// Whether the GeoTIFF at `path` (a full path on this computer) is read in place rather than +/// held, as a cloud-optimised GeoTIFF's web address is (#2761): the map then reads the part in +/// view at the level the view needs, where holding it means one overview at every zoom. It is +/// when the file is tiled with overviews, too large to hold whole ([`raster::max_samples`]), and +/// reading it in place loses nothing reading it whole keeps: its header reports no loss (a +/// transparency mask, metadata that can't be read) and no `.aux.xml` or world file is beside it. +/// Reads the file's header (a few reads of the file, on the fetch workers), or takes the one kept +/// while the file hasn't changed since; forgotten when it isn't read in place. The wait for the +/// header, and [`read_raster_as`]'s for the overview, don't look at Cancel: a local file answers +/// in milliseconds, and a hung one (an unreachable mount) is given up after two minutes. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn tiled_in_place(path: &str) -> bool { + use crate::render::rustgis_tiles::cog; + use crate::render::rustgis_tiles::{address::Reach, cache}; + // A `#` would be taken for a look's start by the in-place reader. A document that may reach + // only public addresses reads no file in place, and nothing of it is looked at here. + if !cog::is_local_file(path) || path.contains('#') || cache::ceiling_for(path) != Reach::Local { + return false; + } + let p = Path::new(path); + if !p.is_file() || raster::pam::read(p).is_some() || raster::world::beside(p).is_some() { + return false; + } + // A header kept for the file is read again only when the file has changed since (see + // `cog::with_info`), so its tiles stay while it hasn't. + let tiled = cog::info_blocking(path).is_ok_and(|info| { + let l = &info.layout; + let full = l.levels.first().map_or(0, |f| u64::from(f.width) * u64::from(f.height)); + let samples = full.saturating_mul(l.bands.max(1) as u64); + let lossless = l.lost.is_empty() && l.described.as_ref().is_none_or(|d| d.lost.is_empty()); + samples > held_whole() as u64 && lossless && cog::raster::overview_level(&info).is_some() + }); + if !tiled { + cog::forget_local_file(path); + } + tiled } /// The key [`add_path`]'s read of `path` (a PDF's `page`) is taken by (see [`super::reads`]): a diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 29b4d17548..a2e62479bc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -421,13 +421,20 @@ fn names_said(names: &[String]) -> String { } /// What a raster layer read in place holds for its statistics and tools, when it holds an -/// overview of the image the map draws. -pub(crate) fn in_place_overview(d: &rustgis_data::raster::Raster) -> Option { +/// overview of the image the map draws. A file on this computer (`tools_read_file`) is read again +/// by each geoprocessing tool, at the finest level it can hold ([`crate::cmd::gp`]). +pub(crate) fn in_place_overview(d: &rustgis_data::raster::Raster, tools_read_file: bool) -> Option { let (fw, fh) = d.overview?; - Some(format!( - "read in place: the map draws its {fw} × {fh} pixels as it needs them, while statistics, histograms and raster tools read a {} × {} overview", - d.width, d.height - )) + let (w, h) = (d.width, d.height); + Some(if tools_read_file { + format!( + "read in place: the map draws its {fw} × {fh} pixels as it needs them, and geoprocessing tools read the file (built-in ones at the finest level they can hold, GeoLibre ones whole), while statistics, histograms, plugin tools and other raster commands read a {w} × {h} overview" + ) + } else { + format!( + "read in place: the map draws its {fw} × {fh} pixels as it needs them, while statistics, histograms and raster tools read a {w} × {h} overview" + ) + }) } pub struct Registry { @@ -1416,6 +1423,9 @@ impl Session { // cloud-optimised GeoTIFFs' overviews for raster layers read in place. render::rustgis_tiles::remote::install(); map::raster::set_in_place_reader(render::rustgis_tiles::cog::raster::overview); + // A large tiled GeoTIFF on this computer is read in place too, on the desktop (#2761). + #[cfg(not(target_arch = "wasm32"))] + map::raster::set_tiled_probe(crate::cmd::raster::tiled_in_place); rustgis_data::diagnostics::set_clock(|| { web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0) }); @@ -2832,10 +2842,10 @@ impl Session { if !dropped_here.is_empty() { dropped.push((l.name.clone(), dropped_here)); } - let in_place = rl.in_place; + let (in_place, tiled) = (rl.reads_in_place(), rl.tiled); lost.extend(rl.lost_unsaid().into_iter().map(|what| (l.name.clone(), what))); let Some(d) = rl.pixels_unsaid() else { continue }; - if let Some(what) = in_place.then(|| in_place_overview(&d)).flatten() { + if let Some(what) = in_place.then(|| in_place_overview(&d, tiled)).flatten() { held.push((l.name.clone(), what)); } } @@ -2977,7 +2987,7 @@ impl Session { .filter_map(|l| { let name = l.name.clone(); let rl = l.raster.as_mut()?; - rl.in_place.then_some((name, rl)) + rl.reads_in_place().then_some((name, rl)) }) .collect(); let mut layers: Vec<&mut rustgis_map::raster::RasterLayer> = named.iter_mut().map(|(_, rl)| &mut **rl).collect(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 79cb03ee8c..616828fb59 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -67,6 +67,9 @@ mod service_logins; #[path = "tests/scopes_and_redaction.rs"] mod scopes_and_redaction; +#[path = "tests/tiled_files.rs"] +mod tiled_files; + #[path = "tests/elevation_tiles.rs"] mod elevation_tiles; diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs new file mode 100644 index 0000000000..f800a5e19c --- /dev/null +++ b/crates/engine/src/tests/tiled_files.rs @@ -0,0 +1,299 @@ +//! A large tiled GeoTIFF on this computer is read in place (#2761): the map reads the part in view +//! at the level the view needs instead of drawing one overview at every zoom, geoprocessing tools +//! read the file, and a project keeps it as the file it is. A file that fits, or one with a +//! sidecar the in-place reader wouldn't apply, is held whole as before. + +use super::*; +use crate::cmd::raster::HELD_WHOLE; +use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + +/// A directory of its own for one test's files, removed when it goes, whether the test passed. +struct Dir(std::path::PathBuf); + +impl std::ops::Deref for Dir { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn dir(name: &str) -> Dir { + let d = std::env::temp_dir().join(format!("rustgis-2761-{name}-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + Dir(d) +} + +/// Holds files whole up to `max` samples on this thread while it lives, then as before. +struct HeldWhole; + +impl HeldWhole { + fn at(max: usize) -> HeldWhole { + HELD_WHOLE.with(|c| c.set(Some(max))); + HeldWhole + } +} + +impl Drop for HeldWhole { + fn drop(&mut self) { + HELD_WHOLE.with(|c| c.set(None)); + } +} + +/// A 1024-pixel RGB cloud-optimised GeoTIFF over 10°–11° E, 45°–46° N in tiles of 512, with its +/// 512 overview: 3.1 million samples. Its red band is a checkerboard of single pixels (200 and +/// 20), which an overview averages away; green and blue climb across and down it. +fn checkerboard(dir: &std::path::Path) -> String { + const N: u32 = 1024; + let at = |f: fn(u32, u32) -> f32| (0..N * N).map(|i| f(i % N, i / N)).collect::>(); + let bands = vec![at(|x, y| if (x + y) % 2 == 0 { 200.0 } else { 20.0 }), at(|x, _| (x / 4) as f32), at(|_, y| (y / 4) as f32)]; + let gt = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 1.0 / f64::from(N), pixel_height: -1.0 / f64::from(N) }; + let r = Raster::new("checks", N, N, bands, gt, Crs::LonLat, None, ColorHint::Rgb { alpha: false }, "UInt8").unwrap(); + let path = dir.join("checks.tif"); + let info = rustgis_data::raster::cogwrite::write_file(&r, 0, &path).unwrap(); + assert_eq!(info.levels, vec![(N, N), (N / 2, N / 2)], "the fixture's levels"); + path.display().to_string() +} + +/// The notices given since `mark`, as text. +fn said(s: &Session, mark: u64) -> Vec { + s.notices_since(mark).iter().map(|n| n.text.clone()).collect() +} + +/// The raster layer named `name`. +fn raster<'a>(s: &'a Session, name: &str) -> &'a rustgis_map::raster::RasterLayer { + s.map().layer_by_name(name).and_then(|l| l.raster.as_ref()).unwrap() +} + +/// The map zoomed in on 80 of the file's pixels a side, drawn 320 pixels a side: each of its +/// pixels four of the export's. +fn zoomed_in(s: &mut Session) -> tiny_skia::Pixmap { + s.run("map.basemap", &json!({"name": "blank"})).unwrap(); + let side = 80.0 / 1024.0; + s.run("map.zoomToExtent", &json!({"extent": [10.4, 45.4, 10.4 + side, 45.4 + side]})).unwrap(); + let png = crate::cmd::share::map_png(s, Some(320.0), Some(320.0), None).unwrap(); + crate::render::decode_png(&png).unwrap() +} + +/// The mean difference of two drawings' red values, pixel for pixel. +fn red_difference(a: &tiny_skia::Pixmap, b: &tiny_skia::Pixmap) -> f64 { + assert_eq!((a.width(), a.height()), (b.width(), b.height())); + let total: u64 = a.pixels().iter().zip(b.pixels()).map(|(p, q)| u64::from(p.demultiply().red().abs_diff(q.demultiply().red()))).sum(); + total as f64 / a.pixels().len() as f64 +} + +/// Added past the size held whole, the file is read in place: the layer holds the 512 overview, +/// says so (and that geoprocessing tools read the file), and draws zoomed in as the file held whole +/// does, its single-pixel checks and all; drawn from the overview it holds, the checks are gone. +#[test] +fn a_large_local_tiled_geotiff_draws_its_full_image_zoomed_in() { + let d = dir("draw"); + let path = checkerboard(&d); + // Held whole (the file fits): the full image, drawn from the pixels held. + let mut whole = Session::new(Project::default()); + whole.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(!raster(&whole, "checks").tiled, "a file that fits is held whole"); + assert_eq!(raster(&whole, "checks").data.as_ref().map(|r| (r.width, r.overview)), Some((1024, None))); + let reference = zoomed_in(&mut whole); + // Past the size held whole: read in place. + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + { + let _held = HeldWhole::at(1_000_000); + s.run("layer.addData", &json!({"path": path})).unwrap(); + } + let rl = raster(&s, "checks"); + assert!(rl.tiled && !rl.in_place, "read in place as a file"); + assert_eq!(rl.data.as_ref().map(|r| (r.width, r.height, r.overview)), Some((512, 512, Some((1024, 1024))))); + let notes = said(&s, mark); + assert!( + notes.iter().any(|n| n.starts_with("checks: read in place: the map draws its 1024 × 1024 pixels") + && n.contains("geoprocessing tools read the file") + && n.contains("read a 512 × 512 overview")), + "{notes:?}" + ); + assert!(!notes.iter().any(|n| n.contains("showing a")), "not said as an overview shown at every zoom: {notes:?}"); + let in_place = zoomed_in(&mut s); + let near = red_difference(&in_place, &reference); + assert!(near < 2.0, "zoomed in, the full image is drawn: {near}"); + // Drawn from the overview the layer holds (as before #2761), the checks average away. + s.map_mut().layers.iter_mut().filter_map(|l| l.raster.as_mut()).for_each(|rl| rl.tiled = false); + let held = zoomed_in(&mut s); + let far = red_difference(&held, &reference); + assert!(far > 40.0, "the overview drawn instead differs: {far}"); +} + +/// A project keeps the file as a file (nothing says it is read in place), and reads it in place +/// again as it opens, as long as it is still too large to hold whole. +#[test] +fn a_project_keeps_a_tiled_file_as_a_file_and_reads_it_in_place_again() { + let d = dir("project"); + let path = checkerboard(&d); + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path})).unwrap(); + let project = d.join("checks.rgis"); + s.run("project.save", &json!({"path": project.display().to_string()})).unwrap(); + let text = std::fs::read_to_string(&project).unwrap(); + assert!(!text.contains("in_place") && !text.contains("tiled"), "saved as a file: {text}"); + let mut opened = Session::new(Project::default()); + opened.run("project.open", &json!({"path": project.display().to_string()})).unwrap(); + let rl = raster(&opened, "checks"); + assert!(rl.tiled, "read in place again"); + assert_eq!(rl.data.as_ref().map(|r| (r.width, r.overview)), Some((512, Some((1024, 1024))))); + // Reload Data reads it in place again too, not whole. + opened.run("layer.reloadData", &json!({"layer": "checks"})).unwrap(); + let rl = raster(&opened, "checks"); + assert!(rl.tiled, "reloaded in place"); + assert_eq!(rl.data.as_ref().map(|r| (r.width, r.overview)), Some((512, Some((1024, 1024))))); +} + +/// A geoprocessing tool reads the file, not the overview the layer holds: Zonal Statistics over +/// the whole image counts each of its 1024 × 1024 pixels. +#[test] +fn a_tool_reads_a_tiled_file_at_its_full_size() { + let d = dir("tool"); + let path = checkerboard(&d); + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(raster(&s, "checks").tiled); + let zone = d.join("zone.geojson"); + std::fs::write( + &zone, + r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"id": 1}, + "geometry": {"type": "Polygon", "coordinates": [[[9.9, 44.9], [11.1, 44.9], [11.1, 46.1], [9.9, 46.1], [9.9, 44.9]]]}}]}"#, + ) + .unwrap(); + s.run("layer.addData", &json!({"path": zone.display().to_string(), "name": "zone"})).unwrap(); + let r = s.run("gp.run", &json!({"tool": "zonalStats", "params": {"raster": "checks", "polygons": "zone", "output": "stats"}})).unwrap(); + let out = &s.map().layer_by_name("stats").unwrap_or_else(|| panic!("{r}")).dataset; + let names: Vec<&str> = out.fields.iter().map(|f| f.name.as_str()).collect(); + let count = names.iter().position(|n| n.ends_with("_count")).unwrap_or_else(|| panic!("{names:?}")); + assert_eq!(out.value(0, count), &rustgis_data::Value::Int(1024 * 1024), "every pixel of the file, not of its overview: {names:?}"); +} + +/// Held whole as before: a file that fits, and one too large with an `.aux.xml` beside it, which +/// the in-place reader wouldn't apply. +#[test] +fn a_file_that_fits_or_has_a_sidecar_is_held_whole() { + let d = dir("whole"); + let path = checkerboard(&d); + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + s.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(!raster(&s, "checks").tiled); + assert!(!said(&s, mark).iter().any(|n| n.contains("read in place")), "{:?}", said(&s, mark)); + std::fs::write(format!("{path}.aux.xml"), "").unwrap(); + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(!raster(&s, "checks").tiled, "a sidecar keeps it whole"); +} + +/// How each kind of run reads a raster layer read in place from its file: a built-in tool's run +/// reads the file, a plugin's reads the overview the layer holds and says so, and a suite tool +/// (which stages the file by its path) neither reads nor says anything. A layer held whole is +/// read as it is, with nothing said. +#[test] +fn each_kind_of_run_reads_a_tiled_file_as_it_says() { + use crate::cmd::gp::{Tiled, tiled_inputs}; + let d = dir("kinds"); + let path = checkerboard(&d); + let spec = rustgis_analysis::TOOLS.iter().find(|t| t.id == "zonalStats").unwrap(); + let params = json!({"raster": "checks", "polygons": "zone"}); + let read = |s: &Session, tiled: Tiled| { + let mut messages = Vec::new(); + let read = tiled_inputs(s.map(), Some(spec), ¶ms, tiled, &mut messages, &mut Vec::new()).unwrap(); + (read.get("checks").map(|r| (r.width, r.overview)), messages) + }; + let mut s = Session::new(Project::default()); + { + let _held = HeldWhole::at(1_000_000); + s.run("layer.addData", &json!({"path": path})).unwrap(); + } + assert_eq!(read(&s, Tiled::File), (Some((1024, None)), Vec::new()), "the full image, as it fits"); + let (none, said) = read(&s, Tiled::Overview); + assert_eq!(none, None, "the layer's own overview is read"); + assert_eq!( + said, + [ + "read as the layer holds it, as plugin tools don't read a raster read in place from its file: checks at the 512 × 512 overview of the 1024 × 1024 raster it holds" + ] + ); + assert_eq!(read(&s, Tiled::ByPath), (None, Vec::new())); + // A suite tool would stage the held overview of a file no longer there: refused. + let moved = d.join("moved.tif"); + std::fs::rename(&path, &moved).unwrap(); + let e = tiled_inputs(s.map(), Some(spec), ¶ms, Tiled::ByPath, &mut Vec::new(), &mut Vec::new()).unwrap_err(); + assert!(e.starts_with("checks: its file") && e.contains("is no longer there"), "{e}"); + std::fs::rename(&moved, &path).unwrap(); + // Held whole: nothing read again, nothing said. + let mut whole = Session::new(Project::default()); + whole.run("layer.addData", &json!({"path": path})).unwrap(); + assert_eq!(read(&whole, Tiled::Overview), (None, Vec::new())); +} + +/// A batch reads a raster file read in place once for its items (kept only while it runs), and +/// each item reads the file, not the overview the layer holds: Zonal Statistics batched over two +/// zone layers counts every pixel of the file in each. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_batch_over_a_tiled_file_reads_the_file_for_each_item() { + let d = dir("batch"); + let path = checkerboard(&d); + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(raster(&s, "checks").tiled); + let box_around = r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"id": 1}, + "geometry": {"type": "Polygon", "coordinates": [[[9.9, 44.9], [11.1, 44.9], [11.1, 46.1], [9.9, 46.1], [9.9, 44.9]]]}}]}"#; + for name in ["one", "two"] { + let zone = d.join(format!("{name}.geojson")); + std::fs::write(&zone, box_around).unwrap(); + s.run("layer.addData", &json!({"path": zone.display().to_string(), "name": name})).unwrap(); + } + let reads = || crate::cmd::gp::TILED_READS.with(std::cell::Cell::get); + let before = reads(); + let p = json!({"tool": "zonalStats", "inputs": ["one", "two"], "param": "polygons", "params": {"raster": "checks"}, "outputPattern": "{input}_stats"}); + let r = s.run("gp.batch", &p).unwrap(); + assert_eq!(reads() - before, 1, "the file read once for both items"); + assert!(!crate::cmd::gp::batch_reads_kept(), "nothing kept once the batch ends"); + // Outside a batch, each run reads the file again: nothing is kept between runs. + let before = reads(); + for out in ["again_1", "again_2"] { + s.run("gp.run", &json!({"tool": "zonalStats", "params": {"raster": "checks", "polygons": "one", "output": out}})).unwrap(); + } + assert_eq!(reads() - before, 2); + for name in ["one_stats", "two_stats"] { + let out = &s.map().layer_by_name(name).unwrap_or_else(|| panic!("no {name}: {r}")).dataset; + let count = out.fields.iter().position(|f| f.name.ends_with("_count")).unwrap(); + assert_eq!(out.value(0, count), &rustgis_data::Value::Int(1024 * 1024), "{name}"); + } +} + +/// Original image grids read a tiled file's own grid, as for a file held whole: its overview +/// records the file's revision, which the grid read is checked against, and a file written again +/// since is refused. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_original_image_grid_reads_a_tiled_files_grid() { + let d = dir("grid"); + let path = checkerboard(&d); + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(raster(&s, "checks").tiled); + crate::image_grid::read(raster(&s, "checks")).unwrap(); + // Written again (the same bytes, a new file): the revision the overview came from is gone. + let bytes = std::fs::read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + std::fs::write(&path, bytes).unwrap(); + let e = crate::image_grid::read(raster(&s, "checks")).err().unwrap_or_default(); + assert!(e.contains("changed since its pixels were loaded"), "{e}"); +} diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 78c699ca56..5df1209661 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -26,6 +26,11 @@ pub struct RasterLayer { /// in view as it draws (see [`set_in_place_reader`]). #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub in_place: bool, + /// `path` is a file on this computer read in place this session, as a web address's is: a + /// tiled GeoTIFF too large to hold whole (#2761), found so each time it is read (see + /// [`set_tiled_probe`]). Never saved: a project keeps it as the file it is. + #[serde(skip)] + pub tiled: bool, /// The file's own name (for its format) when it is embedded. #[serde(default)] pub file_name: Option, @@ -117,7 +122,7 @@ pub type InPlaceRead = Box) + Send>; /// place in `layers`: without waiting, the reads that couldn't start. pub fn read_together(layers: &mut [&mut RasterLayer], wait: bool) -> Vec<(usize, String)> { let mut failed = Vec::new(); - let unread = |l: &RasterLayer| l.in_place && l.data.is_none() && l.opening.is_none() && l.time_zarr.is_none(); + let unread = |l: &RasterLayer| l.reads_in_place() && l.data.is_none() && l.opening.is_none() && l.time_zarr.is_none(); for (i, l) in layers.iter_mut().enumerate() { // Started without waiting: waited for below, together. if unread(l) @@ -146,7 +151,7 @@ pub fn wait_for_reads(layers: &mut [&mut RasterLayer]) -> Vec<(usize, String)> { let deadline = Instant::now() + rustgis_data::raster::IN_PLACE_WAIT; let mut failed = Vec::new(); for (i, l) in layers.iter_mut().enumerate() { - if l.in_place + if l.reads_in_place() && l.opening.is_some() && let Err(e) = l.wait_for_read(deadline) { @@ -169,6 +174,55 @@ pub fn set_in_place_reader(f: impl Fn(&str, InPlaceRead) + Send + Sync + 'static *in_place_reader().lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(f)); } +type TiledProbe = Arc bool + Send + Sync>; + +fn tiled_probe() -> &'static Mutex> { + static P: std::sync::OnceLock>> = std::sync::OnceLock::new(); + P.get_or_init(Mutex::default) +} + +/// Sets how a raster file on this computer is found to be read in place rather than held whole +/// ([`RasterLayer::tiled`]): the app's test, which reads the file's header. Without one, every +/// file is read whole. +pub fn set_tiled_probe(f: impl Fn(&str) -> bool + Send + Sync + 'static) { + *tiled_probe().lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(f)); +} + +/// Whether the file at `path` is read in place, by the installed probe. +fn probed_tiled(path: &str) -> bool { + let probe = tiled_probe().lock().unwrap_or_else(|e| e.into_inner()).clone(); + probe.is_some_and(|p| p(path)) +} + +/// The overview of the file at `path` read in place by the installed reader, waited for +/// (natively; at most two minutes); `None` when it can't be read so, or in the browser. +fn read_in_place_now(path: &str) -> Option { + #[cfg(target_arch = "wasm32")] + { + let _ = path; + None + } + #[cfg(not(target_arch = "wasm32"))] + { + use rustgis_data::source::remote; + let reader = in_place_reader().lock().unwrap_or_else(|e| e.into_inner()).clone()?; + let still = remote::current_still(); + let (tx, rx) = std::sync::mpsc::channel(); + reader(path, Box::new(move |r| tx.send(r).unwrap_or_default())); + // Waited for as `wait_for_read` waits: given up as soon as the read is asked to stop (a + // Cancel, a project replaced). + let deadline = Instant::now() + rustgis_data::raster::IN_PLACE_WAIT; + loop { + remote::check_still(&still).ok()?; + match rx.recv_timeout(std::time::Duration::from_millis(10)) { + Ok(r) => return r.ok(), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) if Instant::now() < deadline => {} + Err(_) => return None, + } + } + } +} + /// The renderer bands' statistics without the masked pixels, and what they were worked out for: /// the mask, the renderer's bands and the pixels (held weakly, so their address isn't reused). #[derive(Clone, Default)] @@ -192,6 +246,13 @@ impl RasterLayer { self.read_generation == other.read_generation && self.restyle == other.restyle && self.look == other.look } + /// Whether the map reads the part in view as it draws, holding only an overview: a web + /// address's cloud-optimised GeoTIFF ([`RasterLayer::in_place`]), or a large tiled GeoTIFF on + /// this computer ([`RasterLayer::tiled`]). + pub fn reads_in_place(&self) -> bool { + self.in_place || self.tiled + } + /// Detaches a fully read replacement from the prior opening's pending reads and notices. pub fn reset_replacement_read(&mut self) { self.read_generation = next_read_generation(); @@ -222,7 +283,23 @@ impl RasterLayer { return Err("give a raster file or Zarr store on this computer: web addresses aren't repaired here".into()); } let sub = subdataset.or(self.subdataset.as_deref()); - let r = self.read_placed(path, sub, false).map_err(|e| format!("{path}: {e}"))?; + // A large tiled GeoTIFF is read in place, as when it was added (#2761): its overview, + // waited for (a repair or reload reads ahead of the window, natively); read whole when + // that can't be read after all. + let in_place = if sub.is_none() && self.crs.is_none() && self.placement.is_none() && probed_tiled(path) { + read_in_place_now(path) + } else { + None + }; + let tiled = in_place.is_some(); + let r = match in_place { + Some(r) => r, + None => { + // Not read whole for a read asked to stop (a Cancel, a project replaced). + rustgis_data::source::remote::check_still(&rustgis_data::source::remote::current_still())?; + self.read_placed(path, sub, false).map_err(|e| format!("{path}: {e}"))? + } + }; self.validate_replacement(&r, path)?; let mut style = self.style.clone(); style.repair(&r); @@ -232,6 +309,7 @@ impl RasterLayer { Ok(RasterLayer { path: Some(path.into()), in_place: false, + tiled, file_name: None, embedded: None, subdataset: sub.filter(|_| !elevation).map(String::from), @@ -281,6 +359,7 @@ impl RasterLayer { RasterLayer { path: Some(path.into()), in_place: false, + tiled: false, file_name: None, embedded: None, subdataset: None, @@ -318,6 +397,7 @@ impl RasterLayer { RasterLayer { path: None, in_place: false, + tiled: false, file_name: Some(file_name.into()), embedded: Some(bytes), subdataset: None, @@ -349,12 +429,19 @@ impl RasterLayer { RasterLayer { in_place: true, ..RasterLayer::from_path(raster, address) } } + /// A large tiled GeoTIFF on this computer read in place ([`RasterLayer::tiled`]), its overview + /// `raster` read. + pub fn tiled_file(raster: Raster, path: impl Into) -> RasterLayer { + RasterLayer { tiled: true, ..RasterLayer::from_path(raster, path) } + } + /// A cloud-optimised GeoTIFF read in place by its address, its overview not read yet: drawn, /// in its own look, once [`RasterLayer::reload`] (or [`read_together`]) has read it. pub fn unread_in_place(address: impl Into) -> RasterLayer { RasterLayer { path: Some(address.into()), in_place: true, + tiled: false, file_name: None, embedded: None, subdataset: None, @@ -423,8 +510,11 @@ impl RasterLayer { remote::check_still(&still)?; let Some(address) = self.path.clone() else { return Err("the raster has no source".to_string()) }; // Checked as a tile layer's address is (http(s) or s3, a host, no control characters): a - // project edited by hand asks for nothing else. - crate::tiles::check_url(&address)?; + // project edited by hand asks for nothing else. A local file read in place was found so + // by the probe, and the reader checks its path again. + if !self.tiled { + crate::tiles::check_url(&address)?; + } let Some(reader) = in_place_reader().lock().unwrap_or_else(|e| e.into_inner()).clone() else { return Err(format!("{address}: can't be read in place here")); }; @@ -449,6 +539,8 @@ impl RasterLayer { /// one being read, and one that waits for something other than time (its bucket's connection: /// see [`RasterLayer::fail`]). pub fn read_failure(&self) -> Option<(&str, Instant, u32)> { + // A web address's read is made again; a local file's read in place that failed is the + // file's, which Reload Data reads again, deciding afresh how. if !self.in_place || self.data.is_some() || self.opening.is_some() { return None; } @@ -503,21 +595,48 @@ impl RasterLayer { self.error = None; self.failed_at = None; self.failures = 0; + // A large tiled GeoTIFF on this computer is read in place, as a web address's is (#2761): + // asked each time it is read where the read is waited for (the probe reads the file's + // header), as the file may have been written again since; a read that isn't waited for + // keeps what was found. A scan laid by hand, a page, or a coordinate system given is read + // whole, as those apply to it. + if wait { + self.tiled = !self.in_place + && self.embedded.is_none() + && self.subdataset.is_none() + && self.crs.is_none() + && self.placement.is_none() + && self.path.as_deref().is_some_and(probed_tiled); + } // Read in place: its overview, by the reader the app installed; waited for natively when - // asked to (as a file is read), else landing later, as always in the browser. - if self.in_place { - if let Err(e) = self.begin_in_place_read() { - self.error = Some(e.clone()); - self.error_said = false; - return Err(e); - } + // asked to (as a file is read), else landing later, as always in the browser. A local + // file whose overview can't be read so after all is read whole, as it was added. + if self.reads_in_place() { + let read = self.begin_in_place_read(); #[cfg(not(target_arch = "wasm32"))] - if wait { - return self.wait_for_read(Instant::now() + rustgis_data::raster::IN_PLACE_WAIT); - } + let read = match read { + Ok(()) if wait => self.wait_for_read(Instant::now() + rustgis_data::raster::IN_PLACE_WAIT), + other => other, + }; #[cfg(target_arch = "wasm32")] let _ = wait; - return Ok(()); + match read { + // The in-place reader failing on its own, not a read asked to stop (a Cancel, a + // project replaced), which the whole read below wouldn't stop for. + Err(_) if self.tiled && rustgis_data::source::remote::check_still(&self.read_still).is_ok() => { + self.tiled = false; + self.opening = None; + self.error = None; + self.failed_at = None; + self.failures = 0; + } + Err(e) => { + self.error = Some(e.clone()); + self.error_said = false; + return Err(e); + } + Ok(()) => return Ok(()), + } } if self.embedded.is_none() && let Some(path) = self.path.as_deref().filter(|p| { @@ -661,7 +780,7 @@ impl RasterLayer { /// Why a layer read in place couldn't be read, the first time it is asked for after the read /// failed, so it is said once (a project, an import or the browser read it after adding it). pub fn error_unsaid(&mut self) -> Option { - if !self.in_place || self.error_said { + if !self.reads_in_place() || self.error_said { return None; } let e = self.error.clone()?; @@ -749,6 +868,8 @@ impl RasterLayer { let RasterLayer { path, in_place, + // Read in place too. + tiled, // Read into `data`, compared itself. file_name: _, embedded: _, @@ -776,7 +897,7 @@ impl RasterLayer { look_lost: _, dropped: _, } = self; - if *in_place || opening.is_some() || read_still.is_some() || self.casts_shadows() { + if *in_place || *tiled || opening.is_some() || read_still.is_some() || self.casts_shadows() { return None; } Some(RasterLook { @@ -850,7 +971,7 @@ impl RasterLayer { let Some(r) = self.data.as_ref().filter(|_| on && z_factor.is_finite()) else { return CastShadows::None }; let not_drawn = grid.not_drawn(); // Read in place, the layer holds an overview; the part in view is read as the map draws. - if self.in_place && r.overview.is_some_and(|(w, _)| w > r.width) { + if self.reads_in_place() && r.overview.is_some_and(|(w, _)| w > r.width) { return CastShadows::Unavailable(format!("{not_drawn}: it is read in place, and only its overview is held")); } let cells = r.width as usize * r.height as usize; @@ -2366,7 +2487,7 @@ impl RasterLayer { let Some(r) = &self.data else { return false }; let every = self.lists_every_class(all_classes); self.style.renderer.draws_classes() - && (self.in_place || r.overview.is_some()) + && (self.reads_in_place() || r.overview.is_some()) && !every && !self.classes_unknown() && !self.mask_hides_all() @@ -2471,6 +2592,7 @@ impl RasterLayer { read_still: _, read_generation: _, in_place: _, + tiled: _, restyle: _, look: _, pixels_said: _, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 00c646fe11..303e1e3d61 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5005,7 +5005,7 @@ fn render_frame( water: lake_light.as_deref(), }; // Read in place: the part in view, at the level the view needs. - let address = rl.path.as_deref().filter(|_| rl.in_place); + let address = rl.path.as_deref().filter(|_| rl.reads_in_place()); let mut draw_it = |pm: &mut Pixmap, opacity: f32| match address { // Drawn from less than the view needs (a coarser level, tiles that couldn't be // read): shown, and said with the tile errors. diff --git a/crates/render/src/raster_export.rs b/crates/render/src/raster_export.rs index 86a095f080..6b1a7b37ab 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -91,7 +91,7 @@ pub fn export(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32) -> let place = raster::Place::Flat(&Flat::Mercator, "EPSG:3857"); let stats = stats.as_deref().map(Vec::as_slice); let mut image = Pixmap::new(TILE_SIZE, TILE_SIZE).ok_or("couldn't allocate a raster tile")?; - match layer.path.as_deref().filter(|_| layer.in_place) { + match layer.path.as_deref().filter(|_| layer.reads_in_place()) { // Read in place: at the tile's level, once its parts have arrived (natively; // the browser draws what has). Some(address) => { diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 86ceec6fe1..98e788d9ca 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -192,6 +192,11 @@ pub struct Info { stretch_failed: Mutex, bool), Instant>>, /// The file's alpha band, shown with any look. alpha: Option, + /// A GeoTIFF on this computer: the revision of the file its header was read from, taken + /// before it was read. The header is kept only while the file is that revision, and what is + /// read with it is checked against it. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) revision: OnceLock, } impl Info { @@ -256,7 +261,9 @@ enum TileState { /// Decoded: its bands, how many samples they hold, and when it was last used (see /// [`Tiles::clock`]). Ready(Bands, usize, u64, crate::address::Reach), - Loading(Vec) + Send>>, crate::address::Reach), + /// Being read: who waits for it, the reach it is read under, and the header (`Info`, by its + /// address, alive while the read is) it is decoded with. + Loading(Vec) + Send>>, crate::address::Reach, usize), } #[derive(Default)] @@ -339,6 +346,15 @@ pub(crate) fn forget_file(url: &str) { forget_file_in(&mut tiles().lock().unwrap_or_else(|e| e.into_inner()), url); } +/// Forgets what was read of a GeoTIFF on this computer ([`is_local_file`]), so its header and +/// tiles are read again from the file as it is now: it is added or reloaded after it may have +/// been written again. Nothing for a web address, whose reads follow the tile cache's. +pub fn forget_local_file(url: &str) { + if is_local_file(url) { + forget_file(url); + } +} + /// Forgets a file's tiles kept (not those loading) from `t`. fn forget_file_in(t: &mut Tiles, url: &str) { let mut freed = 0; @@ -358,6 +374,9 @@ pub fn info(url: &str) -> Result>, String> { crate::cache::check_still(&crate::cache::current_still())?; crate::logins::check(url).map_err(str::to_string)?; let url = split(url).0; + // A local file written again since its header was read is read again (as with `with_info`). + #[cfg(not(target_arch = "wasm32"))] + forget_if_rewritten(url); { let i = infos().lock().unwrap_or_else(|e| e.into_inner()); match i.get(url) { @@ -405,6 +424,25 @@ pub fn landed_count() -> u64 { LANDED.load(Ordering::Relaxed) } +/// Forgets what was read of a GeoTIFF on this computer whose header was read from another +/// revision of the file than it is now: a file written again while it is open is read again, not +/// drawn from its old header and tiles. +#[cfg(not(target_arch = "wasm32"))] +fn forget_if_rewritten(url: &str) { + if !is_local_file(url) { + return; + } + let kept = match infos().lock().unwrap_or_else(|e| e.into_inner()).get(url) { + Some(State::Ready(info, _)) => info.revision.get().cloned(), + _ => return, + }; + if let Some(kept) = kept + && Some(kept) != rustgis_data::raster::FileRevision::of(std::path::Path::new(url)) + { + forget_file(url); + } +} + /// Shares parsed headers and loading waiters, retaining retry delays only for resource failures. fn with_info(url: &str, then: Box, String>) + Send>) { with_info_at(url, crate::cache::ceiling_for(url), then); @@ -422,6 +460,8 @@ fn with_info_at(url: &str, ceiling: crate::address::Reach, then: Box bool { + // A plain path, as a layer's file is given: a `file:` address isn't read in place. + !url.get(..5).is_some_and(|p| p.eq_ignore_ascii_case("file:")) + && crate::pmtiles::is_local(url) + && crate::pmtiles::check_local_path(url, "a GeoTIFF read in place", &["tif", "tiff"]).is_ok() +} + +/// Whether a local GeoTIFF may be read in place: a full path to a `.tif` or `.tiff` file, asked +/// for where this computer may be reached (never by a document limited to public addresses), and +/// not in the browser, which has no files to read by path. +fn local_read_allowed(url: &str, ceiling: crate::address::Reach) -> Result<(), String> { + if cfg!(target_arch = "wasm32") { + return Err(message_with_address(url, "the web app reads GeoTIFFs in place from web addresses only")); + } + if ceiling != crate::address::Reach::Local { + return Err(message_with_address(url, "a file on this computer can't be read from here")); + } + crate::pmtiles::check_local_path(url, "a GeoTIFF read in place", &["tif", "tiff"]) +} + /// Reads a file's header (then its stretch): the start, then whatever more the IFDs need. /// /// A file an API makes on request (an address not named `.tif`, such as Vantor's @@ -519,6 +592,25 @@ fn read(url: &str, at: u64, len: u64, ceiling: crate::address::Reach, done: Done /// would send its whole answer); a GeoTIFF mislabelled so on a server that answers ranges is still /// read. Without an answer, the first [`HEAD`] bytes are read as for any other file. fn load(url: String, ceiling: crate::address::Reach, done: Box, String>) + Send>) { + // A file on this computer: its header read from the file, as any other part of it is. + if is_local_file(&url) { + if let Err(e) = local_read_allowed(&url, ceiling) { + done(Err(e)); + return; + } + // The revision the header is read at, taken before it is read, kept with the header. + #[cfg(not(target_arch = "wasm32"))] + let done: Box, String>) + Send> = { + let revision = rustgis_data::raster::FileRevision::of(std::path::Path::new(&url)); + Box::new(move |r: Result, String>| { + if let (Ok(info), Some(revision)) = (&r, revision) { + let _ = info.revision.set(revision); + } + done(r); + }) + }; + return read_header(url, HEAD, ceiling, done); + } if let Err(e) = crate::address::check_reach(&url, ceiling) { done(Err(e)); return; @@ -705,6 +797,8 @@ fn stats( stretching: Mutex::new(HashMap::new()), stretch_failed: Mutex::new(HashMap::new()), alpha, + #[cfg(not(target_arch = "wasm32"))] + revision: OnceLock::new(), }); // 8-bit colour images are shown as they are; others between the coarsest overview's // percentiles (a palette image's own look needs none: its table colours its values, see @@ -1134,13 +1228,18 @@ fn get_tile_at( let per_band = (l.tile_width as usize) * (l.tile_height as usize); let samples = per_band * nb; let started_reach = ceiling.min(info.reach).min(crate::cache::ceiling_for(&url)); + // The header this read decodes with. A local file's read in flight is joined only by a + // reader with the same header: one holding the header of a file written again since waits for + // it to land, then reads the tile again (#2814), so no old tile reaches its overview. + let header = Arc::as_ptr(&info) as usize; + let joins = |reach: crate::address::Reach, from: usize| reach == started_reach && (from == header || !is_local_file(&url)); // A tile the file leaves out (GDAL's sparse files: no bytes) is empty: kept as any other, so // a window over it is whole at once rather than asking for it at every draw. if len == 0 { let key = (url.clone(), level, idx); let mut t = tiles().lock().unwrap_or_else(|e| e.into_inner()); - if let Some(TileState::Loading(waiting, reach)) = t.map.get_mut(&key) { - if *reach == started_reach { + if let Some(TileState::Loading(waiting, reach, from)) = t.map.get_mut(&key) { + if joins(*reach, *from) { waiting.push(then); } else { waiting.push(crate::cache::caller_retry(Box::new(move |_| get_tile_at(info, url, level, idx, started_reach, then)))); @@ -1151,7 +1250,13 @@ fn get_tile_at( Some(b) => b, None => { let b: Bands = Arc::new(vec![vec![f32::NAN; per_band]; nb].into()); - t.keep(key, b.clone(), samples, started_reach); + // Kept only under the file's current header, as a decoded tile is (a local file + // written again since is read again). + let current = !is_local_file(&url) + || matches!(infos().lock().unwrap_or_else(|e| e.into_inner()).get(&url), Some(State::Ready(i, _)) if Arc::ptr_eq(i, &info)); + if current { + t.keep(key, b.clone(), samples, started_reach); + } b } }; @@ -1178,10 +1283,10 @@ fn get_tile_at( t.samples = t.samples.saturating_sub(n); t.order.remove(&used); } - t.map.insert(key.clone(), TileState::Loading(vec![then], started_reach)); + t.map.insert(key.clone(), TileState::Loading(vec![then], started_reach, header)); } - Some(TileState::Loading(w, reach)) => { - if *reach == started_reach { + Some(TileState::Loading(w, reach, from)) => { + if joins(*reach, *from) { w.push(then); } else { w.push(crate::cache::caller_retry(Box::new(move |_| get_tile_at(info, url, level, idx, started_reach, then)))); @@ -1189,7 +1294,7 @@ fn get_tile_at( return; } None => { - t.map.insert(key.clone(), TileState::Loading(vec![then], started_reach)); + t.map.insert(key.clone(), TileState::Loading(vec![then], started_reach, header)); } } } @@ -1207,17 +1312,24 @@ fn get_tile_at( let mut r = r; let waiting = { let mut t = tiles().lock().unwrap_or_else(|e| e.into_inner()); + // A local file's tile decoded with a header since forgotten (the file written + // again while it was read) is handed on, not kept: the next draw reads it with the + // new one. Looked at under the tiles' lock: a header is forgotten before its tiles + // are, under this lock, so a tile kept here goes with them. + let superseded = is_local_file(&key.0) + && !matches!(infos().lock().unwrap_or_else(|e| e.into_inner()).get(&key.0), Some(State::Ready(i, _)) if Arc::ptr_eq(i, &info)); if started_reach > crate::cache::ceiling_for(&key.0) { r = Err(REACH_CHANGED.into()); } let old = match &r { + Ok(_) if superseded => t.map.remove(&key), // Over the budget: the tiles used longest ago make room. Ok(b) => t.keep(key, b.clone(), samples, started_reach), // A failed tile is read again by the next map tile that needs it. Err(_) => t.map.remove(&key), }; match old { - Some(TileState::Loading(w, _)) => w, + Some(TileState::Loading(w, ..)) => w, _ => Vec::new(), } }; @@ -1890,6 +2002,8 @@ mod tests { stretching: Mutex::default(), stretch_failed: Mutex::default(), alpha: None, + #[cfg(not(target_arch = "wasm32"))] + revision: OnceLock::new(), }); let own = super::Look::default(); assert_eq!(info.palette(&own).map(<[[u8; 4]]>::len), Some(256)); @@ -1982,6 +2096,8 @@ mod tests { stretching: Mutex::default(), stretch_failed: Mutex::default(), alpha: None, + #[cfg(not(target_arch = "wasm32"))] + revision: OnceLock::new(), }); let asked = Arc::new(AtomicUsize::new(0)); let a = asked.clone(); @@ -2494,6 +2610,8 @@ mod tests { stretching: Mutex::default(), stretch_failed: Mutex::default(), alpha: None, + #[cfg(not(target_arch = "wasm32"))] + revision: OnceLock::new(), }); let url = format!("https://sparse-pending.example/{reader:?}.tif"); let key = (url.clone(), 0, 0); @@ -2502,10 +2620,10 @@ mod tests { .lock() .unwrap() .map - .insert(key.clone(), TileState::Loading(vec![Box::new(move |r| old_tx.send(r).unwrap())], Reach::Local)); + .insert(key.clone(), TileState::Loading(vec![Box::new(move |r| old_tx.send(r).unwrap())], Reach::Local, 0)); let (new_tx, new_rx) = std::sync::mpsc::channel(); get_tile(info, url.clone(), 0, 0, Box::new(move |r| new_tx.send(r).unwrap())); - let Some(TileState::Loading(waiting, _)) = tiles().lock().unwrap().map.remove(&key) else { + let Some(TileState::Loading(waiting, ..)) = tiles().lock().unwrap().map.remove(&key) else { panic!("the old loader must remain") }; assert_eq!(waiting.len(), 2); @@ -2603,4 +2721,69 @@ mod tests { forget_file(&url); } } + + /// A GeoTIFF on this computer is read in place from its file, by its full path (#2761): its + /// header and overview, as a web address's are by range. Refused for a document that may reach + /// only public addresses; a path that isn't a full one to a `.tif` or `.tiff` isn't taken for + /// one, nor is a web address. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_local_geotiff_is_read_in_place_from_its_file() { + let _turn = crate::cache::turn(); + let dir = std::env::temp_dir().join(format!("rustgis-cog-local-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("local.tif"); + std::fs::write(&path, cog::example(512, 128)).unwrap(); + let url = path.display().to_string(); + assert!(is_local_file(&url)); + let info = info_blocking(&url).unwrap(); + let sizes: Vec = info.layout.levels.iter().map(|l| l.width).collect(); + assert_eq!(sizes, vec![512, 256, 128]); + let overview = raster::overview_blocking(&url).unwrap(); + assert_eq!((overview.width, overview.overview), (512, None), "small enough to hold its full image as the overview"); + assert!(overview.rounded.is_empty(), "bytes round nothing"); + // Int32 values past 16,777,216: the odd ones `f32` rounds are counted, as the whole-file + // reader counts them. + let wide = dir.join("wide.tif"); + // 200 pixels a side in tiles of 128: the edge tiles' padding isn't counted. + std::fs::write(&wide, cog::example_with(&cog::Example { size: 200, tile: 128, wide: true, ..cog::Example::default() })).unwrap(); + let read = raster::overview_blocking(&wide.display().to_string()).unwrap(); + assert_eq!(read.rounded, vec![200 * 200 / 2]); + let (tx, rx) = std::sync::mpsc::channel(); + load(url.clone(), crate::address::Reach::Public, Box::new(move |r| tx.send(r.err()).unwrap())); + let refused = rx.recv_timeout(Duration::from_secs(5)).unwrap().unwrap_or_default(); + assert!(refused.contains("a file on this computer can't be read from here"), "{refused}"); + for not in ["local.tif", "./local.tif", "//server/share/local.tif", "https://example.com/local.tif", "file:///tmp/local.tif"] { + assert!(!is_local_file(not), "{not}"); + } + assert!(!is_local_file(&dir.join("local.png").display().to_string())); + // Written again while open (another image, another file): its header is read again, not + // the one kept. + std::fs::remove_file(&path).unwrap(); + std::fs::write(&path, cog::example(256, 128)).unwrap(); + let info = info_blocking(&url).unwrap(); + let sizes: Vec = info.layout.levels.iter().map(|l| l.width).collect(); + assert_eq!(sizes, vec![256, 128]); + // A read of a tile still in flight from before the rewrite (another header) isn't joined: + // given the old read's stale tile, the new reader reads the tile again from the file. + let key = (url.clone(), 0usize, 0u32); + let (old_tx, old_rx) = std::sync::mpsc::channel(); + tiles() + .lock() + .unwrap() + .map + .insert(key.clone(), TileState::Loading(vec![Box::new(move |r| old_tx.send(r).unwrap())], crate::address::Reach::Local, 0)); + let (new_tx, new_rx) = std::sync::mpsc::channel(); + get_tile(info.clone(), url.clone(), 0, 0, Box::new(move |r| new_tx.send(r).unwrap())); + let Some(TileState::Loading(waiting, ..)) = tiles().lock().unwrap().map.remove(&key) else { panic!("the old read must remain") }; + let stale: Bands = Arc::new(vec![vec![999.0; 128 * 128]].into()); + for then in waiting { + then(Ok(stale.clone())); + } + assert_eq!(old_rx.recv().unwrap().unwrap().bands[0][0], 999.0); + let fresh = new_rx.recv_timeout(Duration::from_secs(5)).unwrap().unwrap(); + assert_eq!(fresh.bands[0][1], 1.0, "pixel (1, 0) of the file, not the stale tile"); + forget_local_file(&url); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/tiles/src/cog/raster.rs b/crates/tiles/src/cog/raster.rs index 25804784a2..765cfdfdab 100644 --- a/crates/tiles/src/cog/raster.rs +++ b/crates/tiles/src/cog/raster.rs @@ -95,6 +95,10 @@ fn read_overview(info: Arc, url: String, done: Box, url: String, done: Box = bands + .iter() + .map(|&b| { + let mut n = 0u64; + for tile in 0..l.tiles() { + let Some((c, at)) = i.layout.chunk(l, tile, b) else { continue }; + let Some(t) = got.get(c as usize).filter(|t| t.rounded.get(at).is_some()) else { continue }; + let (x0, y0) = ((tile % across).saturating_mul(tw), (tile / across).saturating_mul(th)); + let (cols, rows) = (tw.min(w.saturating_sub(x0)), th.min(h.saturating_sub(y0))); + for y in 0..rows { + for x in 0..cols { + n += u64::from(t.rounded_at(at, (y * tw + x) as usize)); + } + } + } + n + }) + .collect(); + if rounded.iter().any(|n| *n > 0) { + r.rounded = rounded; + } if let Some(full) = i.layout.levels.first().filter(|_| level > 0) { r.overview = Some((full.width, full.height)); } @@ -125,10 +155,23 @@ fn read_overview(info: Arc, url: String, done: Box, url: String, done: Box String { let path = url.split(['?', '#']).next().unwrap_or(url).trim_end_matches('/'); - path.rsplit('/').next().filter(|n| !n.is_empty()).unwrap_or("raster").to_string() + path.rsplit(['/', '\\']).next().filter(|n| !n.is_empty()).unwrap_or("raster").to_string() } /// The chunks a window of a level needs, of the bands given (each band of a tile its own chunk @@ -507,6 +550,8 @@ mod tests { stretching: Mutex::default(), stretch_failed: Mutex::default(), alpha: None, + #[cfg(not(target_arch = "wasm32"))] + revision: std::sync::OnceLock::new(), } } diff --git a/crates/tiles/src/pmtiles.rs b/crates/tiles/src/pmtiles.rs index afc009c054..7de3a9ca0d 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -196,16 +196,25 @@ pub fn is_local(archive: &str) -> bool { /// Whether a local archive may be read: an absolute path to a `.pmtiles` file (checked again /// here, whatever route the address came by). pub fn check_local(archive: &str) -> Result<(), String> { + check_local_path(archive, "a PMTiles file", &["pmtiles"]) +} + +/// Whether a local file may be read by range: an absolute path on this computer (not a network +/// share) whose extension is one of `extensions` (lowercase, without the dot). `kind` names the +/// file in the refusal. +pub(crate) fn check_local_path(archive: &str, kind: &str, extensions: &[&str]) -> Result<(), String> { let p = archive.strip_prefix("file://").unwrap_or(archive); let drive = p.as_bytes().get(1) == Some(&b':') && p.as_bytes().first().is_some_and(u8::is_ascii_alphabetic); // A path on this computer: not a network share (\\server\share, or file://server/…), which a // project could use to make Windows connect to another machine. let share = p.starts_with("\\\\") || p.starts_with("//") || (archive.starts_with("file://") && !p.starts_with('/')); if share || !(p.starts_with('/') || drive) || p.chars().any(char::is_control) || p.len() > 4096 { - return Err(format!("'{p}': a PMTiles file is given by its full path on this computer")); + return Err(format!("'{p}': {kind} is given by its full path on this computer")); } - if !p.to_ascii_lowercase().ends_with(".pmtiles") { - return Err(format!("'{p}' isn't a .pmtiles file")); + let lower = p.to_ascii_lowercase(); + if !extensions.iter().any(|e| lower.rsplit_once('.').is_some_and(|(_, ext)| ext == *e)) { + let named: Vec = extensions.iter().map(|e| format!(".{e}")).collect(); + return Err(format!("'{p}' isn't a {} file", named.join(" or "))); } Ok(()) } diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 74c3666fe0..2e3505c533 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -1687,7 +1687,7 @@ fn casts_shadows(m: &rustgis_engine::map::Map) -> bool { /// Whether the map has raster layers read in place: the part in view arrives a tile at a time, /// through the tile cache, and the map is drawn again as it does. fn reads_in_place(m: &rustgis_engine::map::Map) -> bool { - m.layers.iter().any(|l| l.raster.as_ref().is_some_and(|r| r.in_place)) + m.layers.iter().any(|l| l.raster.as_ref().is_some_and(|r| r.reads_in_place())) } /// The GPU scene buffers a worker uploaded for its frame (see [`gpu_upload`]), if it did. diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index c4a624a3e7..819a9a2b55 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -2118,7 +2118,7 @@ fn layer_row(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, scale: f64, reorder: ("renderer", tl_raw!(rl.style.renderer.label())), ], ), - None if rl.error.is_none() && rl.in_place => tl!("Reading in place…").to_string(), + None if rl.error.is_none() && rl.reads_in_place() => tl!("Reading in place…").to_string(), None => crate::i18n::fmt( "The raster's data couldn't be read: {error}", &[("error", rl.error.as_deref().or(rl.path.as_deref()).unwrap_or(""))], @@ -7112,7 +7112,7 @@ fn raster_details(ui: &mut Ui, rl: &rustgis_engine::map::RasterLayer, t: &Tokens let Some(d) = &rl.data else { // Read in place, its overview is on its way until it lands, or fails (said why). match &rl.error { - None if rl.in_place => { + None if rl.reads_in_place() => { ui.label(egui::RichText::new(tl!("Reading in place…")).color(t.text_dim)); } error => { @@ -7130,7 +7130,7 @@ fn raster_details(ui: &mut Ui, rl: &rustgis_engine::map::RasterLayer, t: &Tokens let e = d.extent(); let unit = if d.crs.is_geographic() { "°" } else { " m" }; // Read in place, the map draws the full image: its size and cell size, not the overview's. - let full = d.overview.filter(|_| rl.in_place); + let full = d.overview.filter(|_| rl.reads_in_place()); let (w, h) = full.unwrap_or((d.width, d.height)); let (cx, cy) = d.cell_size(); let (cx, cy) = (cx * f64::from(d.width) / f64::from(w.max(1)), cy * f64::from(d.height) / f64::from(h.max(1))); @@ -7152,7 +7152,7 @@ fn raster_details(ui: &mut Ui, rl: &rustgis_engine::map::RasterLayer, t: &Tokens ]; match d.overview { // Read in place: the overview is what the layer holds. - Some(_) if rl.in_place => { + Some(_) if rl.reads_in_place() => { rows.insert( 1, ( @@ -7165,7 +7165,7 @@ fn raster_details(ui: &mut Ui, rl: &rustgis_engine::map::RasterLayer, t: &Tokens ); } Some((fw, fh)) => rows.insert(1, ("Full size", format!("{fw} × {fh}"))), - None if rl.in_place => rows.insert(1, ("Read", tl!("In place").to_string())), + None if rl.reads_in_place() => rows.insert(1, ("Read", tl!("In place").to_string())), None => {} } let value_w = (ui.available_width() - 140.0).max(80.0); @@ -7246,7 +7246,7 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { let Some(rl) = l.raster.clone() else { return }; let Some(d) = rl.data.clone() else { // Read in place, its overview is on its way until it lands, or fails (as Details says). - if rl.error.is_none() && rl.in_place { + if rl.error.is_none() && rl.reads_in_place() { ui.label(egui::RichText::new(tl!("Reading in place…")).color(t.text_dim)); } else { ui.label(egui::RichText::new(tl!("The raster's data couldn't be read.")).color(t.red));