From 41d1e67785410447a4d7530f268a6b17e8899b70 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 7 Nov 2026 21:11:24 +0100 Subject: [PATCH 01/12] feat(share): Export Map writes the view as a GeoTIFF placed on the ground (#1561) A .tif path writes the view as an RGB GeoTIFF in the map's projection, its layers and labels without the scale bar; tile credits go into the Copyright tag, which the GeoTIFF reader and both writers now keep. A turned map is drawn north up over its box, and says so; a tilted map, the globe, another body and a projection GeoTIFF keys can't hold are refused before drawing. --- crates/data/src/raster/cogwrite.rs | 3 + crates/data/src/raster/geotiff.rs | 35 ++++++ crates/data/src/raster/mod.rs | 28 +++++ crates/engine/src/cmd/share.rs | 178 ++++++++++++++++++++++++++++- crates/engine/src/tests.rs | 157 +++++++++++++++++++++++++ crates/render/src/lib.rs | 35 ++++-- crates/ui-egui/src/lib.rs | 3 +- docs/user-guide/data-formats.md | 1 + docs/user-guide/sharing.md | 15 ++- docs/user-guide/web-data.md | 4 + 10 files changed, 444 insertions(+), 15 deletions(-) diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index e70a0a6c3b..2bd3b8cdfc 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -400,6 +400,9 @@ fn entries(r: &Raster, plan: &Plan, lv: &Level, first: bool, geo: &GeoKeys, big: } e.push(shorts(339, &vec![format; spp])); if first { + if let Some(c) = r.copyright.as_deref().map(super::tag_text).filter(|c| !c.is_empty()) { + e.push(ascii(33432, &c)); + } let gt = r.transform; e.push(doubles(33550, &[gt.pixel_width.abs(), gt.pixel_height.abs(), 0.0])); e.push(doubles(33922, &[0.0, 0.0, 0.0, gt.origin_x, gt.origin_y, 0.0])); diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index ae118606e4..c70ea17271 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -466,6 +466,13 @@ fn same_projection(a: &str, b: &str) -> bool { }) } +/// Whether a raster in `crs` can be written as a GeoTIFF: an EPSG system always, a user-defined +/// one when it came with GeoKeys or its PROJ definition can be said as them (see +/// [`keys_from_proj4`]). +pub fn describes(crs: Crs) -> bool { + crs.custom_def().is_none_or(|d| !d.geokeys.is_empty() || keys_from_proj4(&d.proj4, &d.label).is_some()) +} + /// GeoKeys for a user-defined projection from its PROJ definition (one read from WKT, which /// came with no keys), the inverse of [`custom_crs`]: the key directory, its double parameters and /// its ASCII parameters. `None` for a projection the keys can't say. @@ -1221,6 +1228,13 @@ pub(super) fn read_limited_with_nodata( }, Err(e) => Some(super::pam::Pam::losing(format!("it doesn't decode ({e}): band and class names are left out"))), }; + // Who holds the rights to the picture, kept so an export of it says so too; 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(super::tag_text(&c)), None), + Ok(Some(Err(e))) | Err(e) => (None, Some(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out"))), + }; let spp = samples(&mut dec); let bytes = sample_bytes(&mut dec); // The decoded image is held at its own pixel size before conversion to f32, so bound bytes @@ -1487,6 +1501,8 @@ pub(super) fn read_limited_with_nodata( let mut r = Raster::new(name, w, h, bands, transform, crs, geo.nodata, color, data_type)?; r.overview = overview; r.rounded = rounded; + r.copyright = copyright.filter(|c| !c.is_empty()); + r.lost.extend(copyright_lost); r.lost.extend(super::planetary::note_of(crs)); r.lost.extend(table_lost); if let Some(p) = &described { @@ -1623,6 +1639,7 @@ fn encode(r: &Raster, band: usize) -> Result> { // Each branch below names the bands it writes as samples (`$written`): their names, and the // first one's class names (the red band's, for a colour file), go to GDAL's metadata tag, // read back on open. + let copyright = r.copyright.as_deref().map(super::tag_text).filter(|c| !c.is_empty()); macro_rules! tags { ($img:expr, $written:expr) => {{ let classes = super::gdal_metadata_of(r, $written); @@ -1648,6 +1665,9 @@ fn encode(r: &Raster, band: usize) -> Result> { if let Some(xml) = &classes { e.write_tag(Tag::Unknown(42112), xml.as_str()).map_err(err)?; } + if let Some(c) = ©right { + e.write_tag(Tag::Copyright, c.as_str()).map_err(err)?; + } if let Some(nd) = r.nodata { e.write_tag(Tag::GdalNodata, nd.to_string().as_str()).map_err(err)?; } @@ -1721,6 +1741,21 @@ mod tests { use super::*; use crate::raster::tests::small; + /// Who holds the rights (the Copyright tag) is written by both writers and read back, as the + /// ASCII a TIFF tag holds (`©` as `(c)`, control characters as spaces, others as `?`); a + /// raster without it writes none. + #[test] + fn copyright_round_trips() { + let mut r = small(); + assert_eq!(read(std::io::Cursor::new(write(&r, 0).unwrap()), "none").unwrap().copyright, None); + r.copyright = Some("© OpenStreetMap contributors | Bundesamt für Landestopografie\0\n".into()); + let want = Some("(c) OpenStreetMap contributors | Bundesamt f?r Landestopografie".to_string()); + assert_eq!(super::super::tag_text_lost(r.copyright.as_deref().unwrap()), 1); + assert_eq!(read(std::io::Cursor::new(write(&r, 0).unwrap()), "tif").unwrap().copyright, want); + let cog = super::super::cogwrite::write(&r, 0).unwrap(); + assert_eq!(read(std::io::Cursor::new(cog), "cog").unwrap().copyright, want); + } + #[test] fn float_colour_round_trip() { let r = small(); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index ab4b75bc58..ab549acf07 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -580,6 +580,11 @@ pub struct Raster { /// values with more digits than `f32` holds), by band; empty when none did. NaN and no-data /// values aren't counted. pub rounded: Vec, + /// Who holds the rights to the picture (the TIFF Copyright tag): the credits a map's tile + /// layers ask for, on a GeoTIFF of the view. Read from a GeoTIFF that has it, and written + /// when this raster is exported; a raster made from it (clipped, reprojected) starts + /// without. + pub copyright: Option, transformer: Transformer, extent: Extent, } @@ -608,6 +613,28 @@ pub(crate) fn gdal_metadata_of(r: &Raster, bands: &[usize]) -> Option { pam::gdal_metadata(&names, first) } +/// Text for a TIFF ASCII tag, which holds 7-bit ASCII only: control characters (a NUL would end +/// it early) as spaces, `©` and `®` as `(c)` and `(R)`, any other character outside ASCII as `?` +/// ([`tag_text_lost`] counts them), trimmed. +pub fn tag_text(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '©' => out.push_str("(c)"), + '®' => out.push_str("(R)"), + c if c.is_control() => out.push(' '), + c if c.is_ascii() => out.push(c), + _ => out.push('?'), + } + } + out.trim().to_string() +} + +/// How many characters of `s` [`tag_text`] writes as `?`: for a writer to say. +pub fn tag_text_lost(s: &str) -> usize { + s.chars().filter(|c| !c.is_ascii() && !matches!(c, '©' | '®')).count() +} + /// How many of the names [`gdal_metadata_of`] writes for `bands` hold a character XML can't (a /// control character), which is written as a space: for a writer to say. pub fn gdal_metadata_changed(r: &Raster, bands: &[usize]) -> usize { @@ -701,6 +728,7 @@ impl Raster { georeferenced: true, lost: Vec::new(), rounded: Vec::new(), + copyright: None, transformer, extent: Extent::EMPTY, }; diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 9f347ef027..f328df421f 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -1,4 +1,4 @@ -//! Publish tab: export the map as PNG and layers as GeoJSON, CSV, FlatGeobuf, GeoPackage, +//! Publish tab: export the map as PNG or GeoTIFF and layers as GeoJSON, CSV, FlatGeobuf, GeoPackage, //! GeoParquet, Shapefile, KML/KMZ or GPX. use std::path::Path; @@ -26,7 +26,7 @@ pub fn commands() -> Vec { super::exports::write_here(s, p, "share.exportMap") }).inputs(map_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() - .params(r#"{"path": "*.png", "width"?: px, "height"?: px, "dpi"?: 96..600}"#), + .params(r#"{"path": "*.png|*.tif|*.tiff", "width"?: px, "height"?: px, "dpi"?: 96..600, "cog"?: "true for a cloud-optimised GeoTIFF"}"#), C::new("share.exportLayer", "Export Features", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportLayer")).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_layer) @@ -157,25 +157,37 @@ pub fn map_png(s: &mut Session, width: Option, height: Option, dpi: Op /// Renders `map` at its camera in a view of `(vw, vh)` points (or a requested size) to PNG bytes. fn png_of( map: &mut rustgis_map::Map, - (vw, vh): (f64, f64), + view_size: (f64, f64), width: Option, height: Option, dpi: Option, ) -> Result, String> { + let view = export_view(map.camera, view_size, width, height, dpi); + rustgis_render::render_png(map, &view) +} + +/// The view an export of the map at `camera` draws, in a view of `(vw, vh)` points: a requested +/// size keeps the same ground extent, and `dpi` sets the pixels per point. +fn export_view( + camera: rustgis_map::camera::Camera, + (vw, vh): (f64, f64), + width: Option, + height: Option, + dpi: Option, +) -> View { // NaN would pass through `clamp`; non-finite values fall back to the defaults. let fin = |v: Option| v.filter(|x| x.is_finite()); let (width, height, dpi) = (fin(width), fin(height), fin(dpi)); let w = width.unwrap_or(vw).clamp(16.0, 8000.0); let h = height.unwrap_or(vh).clamp(16.0, 8000.0); let ppp = (dpi.unwrap_or(96.0) / 96.0).clamp(0.5, 6.0); - let mut camera = map.camera; + let mut camera = camera; // Keep the same ground extent when the size differs from the view. if width.is_some() || height.is_some() { camera.res *= (vw / w).max(vh / h); camera.clamp(); } - let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; - rustgis_render::render_png(map, &view) + View { width: w, height: h, pixels_per_point: ppp, camera, sky: false } } /// The map view on one PDF page (for printing): the page is the view's shape at 96 points per @@ -205,6 +217,17 @@ pub fn map_pdf(s: &mut Session, dpi: f64) -> Result, String> { pub(crate) fn map_work(s: &Session, p: &Value) -> Result { let path = ps(p, "path").ok_or("path is required")?.to_string(); let (width, height, dpi) = (f(p, "width"), f(p, "height"), f(p, "dpi")); + let ext = Path::new(&path).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + let cog = match p.get("cog") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or("cog must be true or false")?, + }; + if matches!(ext.as_str(), "tif" | "tiff") { + return geotiff_work(s, path, export_view(s.map().camera, s.view_size, width, height, dpi), cog); + } + if cog { + return Err("cog is for a GeoTIFF (.tif) export".into()); + } let (mut map, view_size) = (s.map().detached(), s.view_size); Ok(Box::new(move || { let written = (|| { @@ -217,6 +240,149 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { })) } +/// `share.exportMap` to a GeoTIFF: the view drawn as data (its layers and labels, without the +/// scale bar and credits, which sit on the screen), RGB (a drawn view is opaque), placed on the +/// ground in the map's +/// projection, the credits in its Copyright tag. A turned view is drawn north up over the box +/// around it, and says so; a tilted view, the globe and a map of another body are refused, as +/// no grid of square pixels in one coordinate system holds them. +fn geotiff_work(s: &Session, path: String, view: View, cog: bool) -> Result { + let m = s.map(); + let crs = map_crs(m)?; + if view.camera.pitch.abs() > 1e-6 { + return Err(format!( + "the map is tilted {:.0}°: a GeoTIFF needs it looking straight down (pitch 0), or export a PNG", + view.camera.pitch + )); + } + let mut view = view; + let mut notices = Vec::new(); + let bearing = view.camera.bearing; + let turned = bearing.rem_euclid(360.0).min(360.0 - bearing.rem_euclid(360.0)) > 1e-9; + if turned { + // North up over the box around the turned view: everything it shows, and more at the + // corners. + let (bw, bh) = view.camera.rotated_size(view.width, view.height); + view.width = bw.ceil(); + view.height = bh.ceil(); + view.camera.bearing = 0.0; + notices.push(( + rustgis_data::diagnostics::Severity::Info, + format!("{path}: the map is turned {bearing:.0}°, so the GeoTIFF is drawn north up over the box around the view"), + )); + } + let (pw, ph) = (view.width * view.pixels_per_point, view.height * view.pixels_per_point); + let most = f64::from(rustgis_render::MAX_SIDE); + if pw.round() > most || ph.round() > most { + // A turned view's box is larger than the view: say so, as the fix differs. + let turned = if turned { " (the box around the turned view; or set the bearing to 0)" } else { "" }; + return Err(format!( + "{} × {} pixels{turned} is more than the {most} a side an export draws: give a smaller width, height or dpi", + pw.round(), + ph.round() + )); + } + let name = m.name.clone(); + let mut map = m.detached(); + Ok(Box::new(move || { + let mut notices = notices; + let written = (|| { + let (pm, credits) = rustgis_render::render_placed(&mut map, &view)?; + rustgis_data::progress::check().map_err(|e| e.to_string())?; + // The drawn picture goes as the raster is made: both at once would double the memory. + let mut r = placed_raster(&name, pm, &view, crs)?; + r.copyright = (!credits.is_empty()).then(|| credits.join(" | ")); + rustgis_data::progress::check().map_err(|e| e.to_string())?; + let bytes = if cog { + // Tiles go to the file as they are made. + let c = rustgis_data::raster::cogwrite::write_file(&r, 0, Path::new(&path)).map_err(|e| format!("{path}: {e}"))?; + c.bytes + } else { + let bytes = rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| format!("{path}: {e}"))?; + rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; + bytes.len() as u64 + }; + let mut out = json!({"path": path, "width": r.width, "height": r.height, "crs": crs.label(), "bytes": bytes}); + if let Some(c) = &r.copyright { + out["copyright"] = json!(c); + let lost = rustgis_data::raster::tag_text_lost(c); + if lost > 0 { + let chars = if lost == 1 { + "1 character of the credits is".to_string() + } else { + format!("{lost} characters of the credits are") + }; + notices.push(( + rustgis_data::diagnostics::Severity::Info, + format!("{path}: the Copyright tag holds ASCII only, so {chars} written as ?: {c}"), + )); + } + } + Ok(out) + })(); + super::exports::drawn(std::slice::from_ref(&map), notices, written, path) + })) +} + +/// The coordinate system a GeoTIFF of map `m`'s view is in: its flat projection's. +fn map_crs(m: &rustgis_map::Map) -> Result { + let body = m.body(); + if !body.is_earth() { + return Err(format!("a map of {} can't be saved as a GeoTIFF yet: export a PNG", body.name)); + } + match &m.projection { + rustgis_map::Projection::Globe => { + Err("the globe can't be saved as a GeoTIFF: switch to a flat projection (View › Projection), or export a PNG".into()) + } + rustgis_map::Projection::WebMercator => Ok(Crs::WebMercator), + rustgis_map::Projection::Custom(code) => { + let (proj4, label) = rustgis_map::projection::lookup(code)?; + // An EPSG system is written by its code; any other by its definition. + if let Some(n) = label.strip_prefix("EPSG:").and_then(|n| n.parse::().ok()) + && let Some(crs) = Crs::from_epsg(n) + { + return Ok(crs); + } + let shown = label.clone(); + let def = rustgis_data::raster::crs::CustomCrs { proj4, label, geokeys: Vec::new(), doubles: Vec::new(), ascii: String::new() }; + let crs = Crs::custom(def)?; + if !rustgis_data::raster::geotiff::describes(crs) { + return Err(format!( + "the map's projection, {shown}, can't be described in a GeoTIFF: switch the map to an EPSG projection, or export a PNG" + )); + } + Ok(crs) + } + } +} + +/// The drawn view `pm` as an RGB raster placed on the ground: the view's centre at the image's +/// centre, each pixel `res / pixels_per_point` map units a side. A drawn view is opaque (its +/// background is filled), so it has no alpha band. +fn placed_raster(name: &str, pm: tiny_skia::Pixmap, view: &View, crs: Crs) -> Result { + let (w, h) = (pm.width(), pm.height()); + let n = w as usize * h as usize; + let mut bands: Vec> = (0..3).map(|_| Vec::with_capacity(n)).collect(); + for px in pm.pixels() { + // tiny-skia keeps colours premultiplied; a file keeps them straight. + let c = px.demultiply(); + for (band, v) in bands.iter_mut().zip([c.red(), c.green(), c.blue()]) { + band.push(f32::from(v)); + } + } + drop(pm); + let cam = view.camera; + let cell = cam.res / view.pixels_per_point; + let transform = rustgis_data::raster::GeoTransform { + origin_x: cam.center.x - view.width / 2.0 * cam.res, + origin_y: cam.center.y + view.height / 2.0 * cam.res, + pixel_width: cell, + pixel_height: -cell, + }; + let color = rustgis_data::raster::ColorHint::Rgb { alpha: false }; + rustgis_data::raster::Raster::new(name, w, h, bands, transform, crs, None, color, "UInt8").map_err(|e| e.to_string()) +} + /// `share.exportLayer`: writes a layer to a file by its extension. A streamed layer exports its /// whole source, a chunk at a time where the source and format allow (see `data::export`). Says /// what the file couldn't hold: features without drawable geometry, a missing `.prj`, Z or M diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c488a4749c..cd2d80af46 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33084,3 +33084,160 @@ fn topology_refuses_latitudes_past_the_poles() { } } } + +/// `share.exportMap` to a `.tif` writes the view placed on the ground (#1561): in the map's +/// projection, each pixel where the view drew it, RGBA; a turned view north up over its box, and +/// says so; a tilted view, the globe and junk refused. +#[test] +fn export_map_to_geotiff_places_the_view_on_the_ground() { + use rustgis_data::raster::{Crs, geotiff}; + use rustgis_geom::{Coord, lonlat_to_merc}; + let mut s = world(); + s.map_mut().basemap = rustgis_map::Basemap::Blank; + // The export's size is the view's, so its pixel is the camera's resolution. + s.view_size = (400.0, 300.0); + s.run("map.goToXY", &json!({"lon": 5.0, "lat": 47.0, "scale": 20_000_000})).unwrap(); + let dir = std::env::temp_dir().join(format!("rustgis-map-tif-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("view.tif"); + let read = |p: &std::path::Path| geotiff::read(std::io::Cursor::new(std::fs::read(p).unwrap()), "view").unwrap(); + let out = s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 400, "height": 300})).unwrap(); + assert_eq!((out["width"].as_u64(), out["height"].as_u64(), out["crs"].as_str()), (Some(400), Some(300), Some("EPSG:3857"))); + let r = read(&path); + // RGB: a drawn view is opaque. + assert_eq!((r.width, r.height, r.crs, r.bands.len()), (400, 300, Crs::WebMercator, 3)); + // Its grid is the view's: the centre in the middle, the camera's resolution a pixel. + let cam = s.map().camera; + let t = r.transform; + assert!((t.pixel_width - cam.res).abs() < 1e-6 * cam.res && (t.pixel_height + cam.res).abs() < 1e-6 * cam.res, "{t:?}"); + assert!((t.origin_x + 200.0 * cam.res - cam.center.x).abs() < 1e-3 && (t.origin_y - 150.0 * cam.res - cam.center.y).abs() < 1e-3); + // Land and sea where they are: the pixel at a place inland differs from one at sea. + let at = |r: &rustgis_data::raster::Raster, lon: f64, lat: f64| { + let m = lonlat_to_merc(Coord::new(lon, lat)); + let (c, row) = ( + ((m.x - r.transform.origin_x) / r.transform.pixel_width) as usize, + ((m.y - r.transform.origin_y) / r.transform.pixel_height) as usize, + ); + let i = row * r.width as usize + c; + r.bands.iter().map(|b| b.data[i]).collect::>() + }; + let (land, sea) = (at(&r, 10.0, 50.0), at(&r, -20.0, 45.0)); + assert_ne!(land, sea, "land {land:?}, sea {sea:?}"); + // The same view exported twice is the same picture: a turned one is a different grid. + s.run("map.setBearing", &json!({"bearing": 30})).unwrap(); + let turned = dir.join("turned.tif"); + let out = s.run("share.exportMap", &json!({"path": turned.display().to_string(), "width": 400, "height": 300})).unwrap(); + let r2 = read(&turned); + assert!(r2.width > 400 && r2.height > 300, "{} × {}", r2.width, r2.height); + assert!(s.notices.iter().any(|n| n.text.contains("turned 30°")), "{out}"); + // North up over the box: the same place lands on the same ground. + assert_eq!(at(&r2, 10.0, 50.0), land); + assert!((r2.transform.pixel_width - cam.res).abs() < 1e-6 * cam.res); + s.run("map.setBearing", &json!({"bearing": 0})).unwrap(); + // `cog` writes a cloud-optimised one; it's for a GeoTIFF only. + let cog = dir.join("view-cog.tif"); + let out = s.run("share.exportMap", &json!({"path": cog.display().to_string(), "width": 400, "height": 300, "cog": true})).unwrap(); + assert!(out["bytes"].as_u64().unwrap() > 0); + assert_eq!(read(&cog).width, 400); + let png = dir.join("view.png"); + let e = s.run("share.exportMap", &json!({"path": png.display().to_string(), "cog": true})).unwrap_err(); + assert!(e.contains("cog is for a GeoTIFF"), "{e}"); + let e = s.run("share.exportMap", &json!({"path": cog.display().to_string(), "cog": "yes"})).unwrap_err(); + assert!(e.contains("cog must be true or false"), "{e}"); + // Too many pixels a side is refused, saying how many. + let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 8000, "dpi": 192})).unwrap_err(); + assert!(e.contains("16000") && e.contains("8192") && !e.contains("turned"), "{e}"); + // A tilted map and the globe are refused, and write nothing. + let none = dir.join("none.tif"); + s.run("map.setPitch", &json!({"pitch": 40})).unwrap(); + let e = s.run("share.exportMap", &json!({"path": none.display().to_string()})).unwrap_err(); + assert!(e.contains("tilted 40°"), "{e}"); + s.run("map.setPitch", &json!({"pitch": 0})).unwrap(); + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + let e = s.run("share.exportMap", &json!({"path": none.display().to_string()})).unwrap_err(); + assert!(e.contains("globe can't be saved as a GeoTIFF"), "{e}"); + s.run("map.projection", &json!({"type": "mercator"})).unwrap(); + // So is a map of another body, whose ground no Earth system holds. + s.run("map.body", &json!({"name": "mars", "basemap": false})).unwrap(); + let e = s.run("share.exportMap", &json!({"path": none.display().to_string()})).unwrap_err(); + assert!(e.contains("a map of Mars can't be saved as a GeoTIFF"), "{e}"); + assert!(!none.exists()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A GeoTIFF of a map in another projection is in that projection: an EPSG one by its code, +/// another by its definition; one the GeoTIFF keys can't say is refused. +#[test] +fn export_map_to_geotiff_keeps_the_maps_projection() { + use rustgis_data::raster::{Crs, geotiff}; + let mut s = world(); + s.map_mut().basemap = rustgis_map::Basemap::Blank; + s.run("map.goToXY", &json!({"lon": 7.45, "lat": 46.95, "scale": 2_000_000})).unwrap(); + let dir = std::env::temp_dir().join(format!("rustgis-map-tif-crs-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let read = |p: &std::path::Path| geotiff::read(std::io::Cursor::new(std::fs::read(p).unwrap()), "view").unwrap(); + s.run("map.projection", &json!({"type": "EPSG:2056"})).unwrap(); + let lv95 = dir.join("lv95.tif"); + let out = s.run("share.exportMap", &json!({"path": lv95.display().to_string(), "width": 200, "height": 200})).unwrap(); + assert_eq!(out["crs"], "EPSG:2056"); + let r = read(&lv95); + assert_eq!(r.crs, Crs::Epsg(2056)); + // Bern's centre in LV95 metres (about 2 600 000, 1 200 000) is near the middle of the image. + let (cx, cy) = (r.transform.origin_x + 100.0 * r.transform.pixel_width, r.transform.origin_y + 100.0 * r.transform.pixel_height); + assert!((cx - 2_600_000.0).abs() < 5_000.0 && (cy - 1_200_000.0).abs() < 5_000.0, "{cx} {cy}"); + // A local view (azimuthal equidistant about Bern) by its definition. + s.run("map.projection", &json!({"type": "local:7.45,46.95"})).unwrap(); + let local = dir.join("local.tif"); + s.run("share.exportMap", &json!({"path": local.display().to_string(), "width": 200, "height": 200})).unwrap(); + let r = read(&local); + assert!(r.crs.custom_def().is_some_and(|d| d.proj4.contains("+proj=aeqd")), "{:?}", r.crs); + // One the GeoTIFF keys can't say is refused before anything is drawn, saying what to do. + s.run("map.projection", &json!({"type": "mollweide"})).unwrap(); + let moll = dir.join("moll.tif"); + let e = s.run("share.exportMap", &json!({"path": moll.display().to_string()})).unwrap_err(); + assert!(e.contains("can't be described in a GeoTIFF") && e.contains("export a PNG"), "{e}"); + assert!(!moll.exists()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A tile layer's pictures are in a GeoTIFF of the view where they lie, and its credits in the +/// file's Copyright tag (#1561). +#[test] +fn export_map_to_geotiff_draws_tile_layers_and_keeps_their_credits() { + use rustgis_data::raster::geotiff; + let dir = std::env::temp_dir().join(format!("rustgis-map-tif-tiles-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let archive = dir.join("red.mbtiles"); + let mut red = tiny_skia::Pixmap::new(256, 256).unwrap(); + red.fill(tiny_skia::Color::from_rgba8(255, 0, 0, 255)); + let c = rusqlite::Connection::open(&archive).unwrap(); + c.execute_batch( + "CREATE TABLE metadata (name text, value text); CREATE TABLE tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob); + INSERT INTO metadata VALUES ('name', 'Red'), ('format', 'png'), ('minzoom', '0'), ('maxzoom', '0'), ('attribution', '© Röd');", + ) + .unwrap(); + c.execute("INSERT INTO tiles VALUES (0, 0, 0, ?1)", [red.encode_png().unwrap()]).unwrap(); + drop(c); + let mut s = Session::new(Project::default()); + s.map_mut().basemap = rustgis_map::Basemap::Blank; + s.view_size = (300.0, 200.0); + s.run("layer.addData", &json!({"path": archive.display().to_string()})).unwrap(); + s.run("map.goToXY", &json!({"lon": 10.0, "lat": 20.0, "scale": 50_000_000})).unwrap(); + let path = dir.join("tiles.tif"); + let out = s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + // The answer has the credits whole; the tag holds ASCII, and the export says what it changed. + assert_eq!(out["copyright"], "© Röd"); + let r = geotiff::read(std::io::Cursor::new(std::fs::read(&path).unwrap()), "tiles").unwrap(); + assert_eq!(r.copyright.as_deref(), Some("(c) R?d")); + assert!(s.notices.iter().any(|n| n.text.contains("1 character of the credits is written as ?: © Röd")), "{:?}", s.notices); + // The middle pixel is the tile's red. + let i = 100 * r.width as usize + 150; + let px: Vec = r.bands.iter().map(|b| b.data[i]).collect(); + assert_eq!(px, [255.0, 0.0, 0.0]); + // Credits that are ASCII but for © say nothing. + let n = s.notices.len(); + s.map_mut().tiles[0].attribution = "© Red".into(); + s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + assert!(!s.notices[n..].iter().any(|n| n.text.contains("written as ?")), "{:?}", &s.notices[n..]); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5f1d9da013..99884ce5b8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5714,6 +5714,33 @@ pub fn render_drawing(map: &mut Map, view: &View) -> Option { /// Renders a map with its labels, a scale bar and a north arrow to PNG bytes. pub fn render_png(map: &mut Map, view: &View) -> Result, String> { + let r = render_exported(map, view)?; + let mut pm = Canvas::from_pixmap(r.pixmap); + for l in r.unplaced.iter().chain(&r.labels) { + text::draw(&mut pm, l, view.pixels_per_point as f32); + } + text::scale_bar(&mut pm, view, map.ground_res_at(&view.camera)); + draw_attribution(&mut pm, &r.attribution, view.pixels_per_point as f32); + pm.into_pixmap().encode_png().map_err(|e| e.to_string()) +} + +/// A map drawn as data, for an image placed on the ground (a GeoTIFF of the view): its layers +/// and labels (the unplaced ones too, when the map shows them, as [`render_png`] draws them), +/// without the scale bar and the credits, which sit on the screen, not the ground. Gives back the +/// pixels (premultiplied, as tiny-skia keeps them) and the credits the map's tile layers ask for, +/// for the file to keep. Refuses what [`render_png`] refuses. +pub fn render_placed(map: &mut Map, view: &View) -> Result<(Pixmap, Vec), String> { + let r = render_exported(map, view)?; + let mut pm = Canvas::from_pixmap(r.pixmap); + for l in r.unplaced.iter().chain(&r.labels) { + text::draw(&mut pm, l, view.pixels_per_point as f32); + } + Ok((pm.into_pixmap(), r.attribution)) +} + +/// The map drawn whole for an export, or why it can't be written: a raster read in place whose +/// tiles haven't come, or that is drawn from less than the view needs. +fn render_exported(map: &mut Map, view: &View) -> Result { let r = render_complete(map, view).ok_or("could not allocate the image")?; // A raster read in place drawn from less than the view needs isn't written: its tiles still // on their way (the browser can't wait; natively the wait ran out), or a coarser level or @@ -5730,13 +5757,7 @@ pub fn render_png(map: &mut Map, view: &View) -> Result, String> { }); return Err(format!("{why}, so the image isn't written")); } - let mut pm = Canvas::from_pixmap(r.pixmap); - for l in r.unplaced.iter().chain(&r.labels) { - text::draw(&mut pm, l, view.pixels_per_point as f32); - } - text::scale_bar(&mut pm, view, map.ground_res_at(&view.camera)); - draw_attribution(&mut pm, &r.attribution, view.pixels_per_point as f32); - pm.into_pixmap().encode_png().map_err(|e| e.to_string()) + Ok(r) } /// The tile layers' credits, small, in the bottom-right corner. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 16127dce29..8d1e25c163 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3959,7 +3959,8 @@ impl RustGisApp { } "ui.exportMap" => { let name = format!("{}.png", self.session.map().name); - if let Some(path) = dialogs::pick_save(&name, &["png"], tl!("PNG image")) { + // A .tif is the view placed on the ground (a GeoTIFF), without the scale bar. + if let Some(path) = dialogs::pick_save(&name, &["png", "tif", "tiff"], tl!("PNG image or GeoTIFF")) { // Drawn on a thread of its own, with progress and Cancel in the status bar; // here while a style added with its own view loads, as the command waits for // it to move the map there first. diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 501084c1e5..cf41c86c1f 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -581,6 +581,7 @@ were rounded, and Export Raster, which writes the rounded values, says so again. | GeoJSON, KML, GPX, CSV, CSV with WKT | Analyze › Workflows › Data Interop (`data.convert`; `"format": "geojson"`, `"kml"`, `"gpx"`, `"csv"` or `"wkt"`) | Returns text when `"path"` is omitted; writes a file on desktop when it is given. | | GeoTIFF / Cloud-optimised GeoTIFF | Data › Export Raster (`share.exportRaster`) | Untiled GeoTIFF by default; `"cog": true` writes 512-pixel tiles, Deflate compression and overviews. Writes the loaded raster's resolution (an overview when that is what was opened), the selected band or its colour bands. The web app's Export Raster downloads an ordinary GeoTIFF. | | PNG | Publish › Export Map (`share.exportMap`) | Configurable DPI, with labels, scale bar and tile credits. | +| GeoTIFF of the map view | Publish › Export Map to `.tif` (`share.exportMap`) | The view as an RGB GeoTIFF in the map's projection, with labels but no scale bar; tile credits in the Copyright tag; `"cog": true` for a cloud-optimised one. Flat, untilted maps of the Earth only (see [Exporting](sharing.md#exporting)). | | PDF | Layouts, reports, presentations and the map view (Print Map), as vectors | | | Wavefront OBJ, STL, glTF | Publish › Export To 3D, Share As › Web Scene | Polygons extruded by a field. STL is binary and triangles only (no lines). | | Web map, OGC API Features, MapLibre style | Publish › Share As | Open-format files that need no server: see [Sharing](sharing.md). | diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index ff5fd9dbb8..ba2e80ff32 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -4,7 +4,20 @@ **Publish › Output › Export Map** writes the map view as a PNG with labels, the scale bar and tile credits. The ribbon exports at 192 DPI; `share.exportMap` accepts `width` and `height` -in pixels and a `dpi` value (96 by default). **Print Map** opens a PDF of the map view, kept as +in pixels and a `dpi` value (96 by default). + +Export Map to a `.tif` path writes the view as a GeoTIFF instead: an RGB image placed on the +ground in the map's projection, so another GIS opens it where it belongs. It holds the layers, +tile and WMS layers included, and the labels, but not the scale bar or the credits. The credits go +into the file's Copyright tag, which holds plain ASCII (`©` is written as `(c)`, and the export +says when other characters are written as `?`); its answer gives them in full as `copyright`. `"cog": true` writes a +cloud-optimised GeoTIFF. A turned map is drawn north up over the box around the view (and says +so). A tilted map, the globe and a map of another body are refused: export a PNG of those. One +side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`. A projection +whose parameters GeoTIFF's keys can't hold (Mollweide or Robinson, for example) is refused too: +switch the map to an EPSG projection first. + +**Print Map** opens a PDF of the map view, kept as vectors as a layout's PDF is (see Layouts), in the system viewer on desktop; **Capture To Clipboard** copies a map image. **Export To 3D** writes a layer as a Wavefront OBJ or binary STL model with polygons extruded by a field (`share.export3d` writes STL when `path` ends in `.stl`). STL diff --git a/docs/user-guide/web-data.md b/docs/user-guide/web-data.md index 324e1b8eb0..eaf2ad832d 100644 --- a/docs/user-guide/web-data.md +++ b/docs/user-guide/web-data.md @@ -553,8 +553,12 @@ animation, and a layer whose only time is `current`: rustgis-cli run --cmd 'service.add={"url":"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/1.0.0/WMTSCapabilities.xml","layer":"MODIS_Terra_CorrectedReflectance_TrueColor","time":"2024-06-01"}' --cmd 'share.exportMap={"path":"gibs.png"}' rustgis-cli run --cmd 'service.add={"url":"https://wms.geo.admin.ch/?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.3.0","layer":"ch.swisstopo.pixelkarte-farbe-pk25.noscale"}' --cmd 'map.goToXY={"lon":7.4474,"lat":46.948,"scale":25000}' --cmd 'time.set={"interval":15}' --cmd 'time.export={"path":"bern.gif"}' rustgis-cli run --cmd 'service.add={"url":"https://wmts.geo.admin.ch/EPSG/3857/1.0.0/WMTSCapabilities.xml","layer":"ch.swisstopo.pixelkarte-farbe"}' --cmd 'share.exportMap={"path":"map.png"}' +rustgis-cli run --cmd 'service.add={"url":"https://wmts.geo.admin.ch/EPSG/2056/1.0.0/WMTSCapabilities.xml","layer":"ch.swisstopo.pixelkarte-farbe"}' --cmd 'map.projection={"type":"EPSG:2056"}' --cmd 'map.goToXY={"lon":7.4474,"lat":46.948,"scale":20000}' --cmd 'share.exportMap={"path":"bern-lv95.tif"}' ``` +The last writes the view as a GeoTIFF in Swiss LV95 (EPSG:2056), placed on the ground, with the +service's credits in its Copyright tag (see [Exporting](sharing.md#exporting)). + ## United States **Home › Add › Web Data › United States** holds services covering the United States: the From 3b953338c051eb18b9d306b833d27fef312075a1 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 7 Nov 2026 22:42:38 +0100 Subject: [PATCH 02/12] fix(share): a GeoTIFF of the view says its gaps; credits kept as read, changes said - The export warns about tiles still on their way, streamed layers still reading and tile layers that couldn't be drawn: on the ground a gap looks like data. - The reader keeps the Copyright text as read (scans too); the writers make it ASCII and Export Map and Export Raster say what that changed (? and spaces). - Custom GeoKeys are written with the raster type as area, as the corner tiepoint is: a system first read from a point file isn't half a pixel off. - The bands are allocated fallibly; the ribbon fits a GeoTIFF's DPI to 8192 pixels a side and says so. --- crates/data/src/raster/geotiff.rs | 55 ++++++++++++++++++++++++++++--- crates/data/src/raster/mod.rs | 12 ++++--- crates/engine/src/cmd/raster.rs | 9 +++++ crates/engine/src/cmd/share.rs | 53 +++++++++++++++++++---------- crates/engine/src/tests.rs | 30 +++++++++++++++-- crates/render/src/lib.rs | 39 +++++++++++++++++++--- crates/ui-egui/src/exportjob.rs | 40 ++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 32 ++++++++++++++++-- docs/user-guide/sharing.md | 7 ++-- 9 files changed, 239 insertions(+), 38 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index c70ea17271..92a6fcc738 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1228,11 +1228,12 @@ pub(super) fn read_limited_with_nodata( }, Err(e) => Some(super::pam::Pam::losing(format!("it doesn't decode ({e}): band and class names are left out"))), }; - // Who holds the rights to the picture, kept so an export of it says so too; one that doesn't - // read as text is left out, and said. + // 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(super::tag_text(&c)), None), + Ok(Some(Ok(c))) => (Some(c.trim().to_string()), None), Ok(Some(Err(e))) | Err(e) => (None, Some(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out"))), }; let spp = samples(&mut dec); @@ -1450,6 +1451,8 @@ pub(super) fn read_limited_with_nodata( r.georeferenced = false; r.overview = overview; r.rounded = rounded; + r.copyright = copyright.filter(|c| !c.is_empty()); + r.lost.extend(copyright_lost); r.lost.extend(table_lost); if let Some(p) = &described { r.apply_pam(p, super::pam::GDAL_METADATA); @@ -1536,7 +1539,10 @@ pub(super) fn geo_keys(r: &Raster) -> Result { Some(d) if d.geokeys.is_empty() => { return Err(err(format!("{}: a coordinate system without GeoTIFF keys can't be written", d.label))); } - Some(d) => d.geokeys.clone(), + // The tiepoint is written at the corner of the first pixel, so the raster type is area: a + // system first read from a point file (whose grid was moved to the corner on reading) is + // written as one too, or readers would place it half a pixel off. + Some(d) => as_area(&d.geokeys), None => vec![ 1, 1, @@ -1559,6 +1565,20 @@ pub(super) fn geo_keys(r: &Raster) -> Result { Ok(GeoKeys { keys, custom }) } +/// GeoKey directory `keys` with the raster type (1025) as area (1), as the writers' corner +/// tiepoint says. +fn as_area(keys: &[u16]) -> Vec { + let mut keys = keys.to_vec(); + // After the 4-short header, 4 shorts a key: its id, where its value is (0: in place), its + // count and its value. + for entry in keys.get_mut(4..).into_iter().flat_map(|k| k.as_chunks_mut::<4>().0) { + if let [1025, 0, _, value] = entry { + *value = 1; + } + } + keys +} + /// Whether band `b` is written as bytes: whole numbers within 0–255 (or no valid pixels at all), /// and a no-data value that is one too. pub(super) fn fits_bytes(r: &Raster, b: usize) -> bool { @@ -1750,12 +1770,37 @@ mod tests { assert_eq!(read(std::io::Cursor::new(write(&r, 0).unwrap()), "none").unwrap().copyright, None); r.copyright = Some("© OpenStreetMap contributors | Bundesamt für Landestopografie\0\n".into()); let want = Some("(c) OpenStreetMap contributors | Bundesamt f?r Landestopografie".to_string()); - assert_eq!(super::super::tag_text_lost(r.copyright.as_deref().unwrap()), 1); + // One written as ?; the NUL and line break at the end are trimmed, not counted. + assert_eq!(super::super::tag_text_changes(r.copyright.as_deref().unwrap()), (1, 0)); + // Inside, a line break and U+0085 (a control character outside ASCII) are spaces. + assert_eq!(super::super::tag_text_changes("a\nb\u{85}c ü"), (1, 2)); + assert_eq!(super::super::tag_text("a\nb\u{85}c ü"), "a b c ?"); + // A scan (a TIFF with no GeoTIFF tags) keeps it too. + let mut buf = std::io::Cursor::new(Vec::new()); + { + let mut enc = tiff::encoder::TiffEncoder::new(&mut buf).unwrap(); + let mut img = enc.new_image::(2, 2).unwrap(); + img.encoder().write_tag(Tag::Copyright, "(c) Scan").unwrap(); + img.write_data(&[1, 2, 3, 4]).unwrap(); + } + let scan = read(std::io::Cursor::new(buf.into_inner()), "scan").unwrap(); + assert_eq!((scan.georeferenced, scan.copyright.as_deref()), (false, Some("(c) Scan"))); assert_eq!(read(std::io::Cursor::new(write(&r, 0).unwrap()), "tif").unwrap().copyright, want); let cog = super::super::cogwrite::write(&r, 0).unwrap(); assert_eq!(read(std::io::Cursor::new(cog), "cog").unwrap().copyright, want); } + /// A user-defined system's keys are written with the raster type as area, as the corner + /// tiepoint is: one first read from a point file isn't placed half a pixel off. + #[test] + fn custom_keys_are_written_as_area() { + let point = [1u16, 1, 0, 3, 1024, 0, 1, 1, 1025, 0, 1, 2, 3072, 0, 1, 32767]; + assert_eq!(as_area(&point), [1, 1, 0, 3, 1024, 0, 1, 1, 1025, 0, 1, 1, 3072, 0, 1, 32767]); + // A key whose value is elsewhere (not in place) is left alone, as is a short directory. + assert_eq!(as_area(&[1, 1, 0, 1, 1025, 34737, 1, 2]), [1, 1, 0, 1, 1025, 34737, 1, 2]); + assert_eq!(as_area(&[1, 1]), [1, 1]); + } + #[test] fn float_colour_round_trip() { let r = small(); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index ab549acf07..fbab2406e3 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -615,7 +615,7 @@ pub(crate) fn gdal_metadata_of(r: &Raster, bands: &[usize]) -> Option { /// Text for a TIFF ASCII tag, which holds 7-bit ASCII only: control characters (a NUL would end /// it early) as spaces, `©` and `®` as `(c)` and `(R)`, any other character outside ASCII as `?` -/// ([`tag_text_lost`] counts them), trimmed. +/// ([`tag_text_changes`] counts them), trimmed. pub fn tag_text(s: &str) -> String { let mut out = String::with_capacity(s.len()); for c in s.chars() { @@ -630,9 +630,13 @@ pub fn tag_text(s: &str) -> String { out.trim().to_string() } -/// How many characters of `s` [`tag_text`] writes as `?`: for a writer to say. -pub fn tag_text_lost(s: &str) -> usize { - s.chars().filter(|c| !c.is_ascii() && !matches!(c, '©' | '®')).count() +/// How many characters of `s` [`tag_text`] writes as `?`, and how many control characters it +/// writes as spaces, line breaks and tabs among them (the trimmed ends not counted): for a +/// writer to say. +pub fn tag_text_changes(s: &str) -> (usize, usize) { + let inner = s.trim_matches(|c: char| c.is_control() || c.is_ascii_whitespace()); + let questioned = inner.chars().filter(|c| !c.is_ascii() && !c.is_control() && !matches!(c, '©' | '®')).count(); + (questioned, inner.chars().filter(|c| c.is_control()).count()) } /// How many of the names [`gdal_metadata_of`] writes for `bands` hold a character XML can't (a diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index e696b5cbe8..3c17ed3d5e 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -992,6 +992,15 @@ fn write_geotiff(r: &Raster, bi: usize, cog: bool, path: &str) -> Result 0 { + note.push_str(&format!( + "; its Copyright tag holds ASCII only, so {questioned} character(s) are written as ? and {spaced} control character(s) as spaces" + )); + } + } let spaced = raster::gdal_metadata_changed(r, &bands); if spaced > 0 { note.push_str(&format!("; {spaced} band or class name(s) held control characters, written as spaces")); diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index f328df421f..5afd6dfbc5 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -242,10 +242,11 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { /// `share.exportMap` to a GeoTIFF: the view drawn as data (its layers and labels, without the /// scale bar and credits, which sit on the screen), RGB (a drawn view is opaque), placed on the -/// ground in the map's -/// projection, the credits in its Copyright tag. A turned view is drawn north up over the box -/// around it, and says so; a tilted view, the globe and a map of another body are refused, as -/// no grid of square pixels in one coordinate system holds them. +/// ground in the map's projection, the credits in its Copyright tag. What may have left gaps in +/// it (tiles still on their way, tile layers that failed) is said: on the ground a gap looks like +/// data. A turned view is drawn north up over the box around it, and says so; a tilted view, the +/// globe and a map of another body are refused, as no grid of square pixels in one coordinate +/// system holds them. fn geotiff_work(s: &Session, path: String, view: View, cog: bool) -> Result { let m = s.map(); let crs = map_crs(m)?; @@ -287,10 +288,15 @@ fn geotiff_work(s: &Session, path: String, view: View, cog: bool) -> Result Result 0 { - let chars = if lost == 1 { - "1 character of the credits is".to_string() - } else { - format!("{lost} characters of the credits are") - }; + let (questioned, spaced) = rustgis_data::raster::tag_text_changes(c); + let count = |n: usize| if n == 1 { "1 character".to_string() } else { format!("{n} characters") }; + let changes: Vec = [(questioned, "as ?"), (spaced, "(control characters) as spaces")] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, how)| format!("{} {how}", count(n))) + .collect(); + if !changes.is_empty() { notices.push(( rustgis_data::diagnostics::Severity::Info, - format!("{path}: the Copyright tag holds ASCII only, so {chars} written as ?: {c}"), + format!( + "{path}: the Copyright tag holds ASCII only, so the credits are written with {}: {c}", + changes.join(" and ") + ), )); } } @@ -358,11 +368,15 @@ fn map_crs(m: &rustgis_map::Map) -> Result { /// The drawn view `pm` as an RGB raster placed on the ground: the view's centre at the image's /// centre, each pixel `res / pixels_per_point` map units a side. A drawn view is opaque (its -/// background is filled), so it has no alpha band. +/// background is filled), so it has no alpha band. While the bands are filled the picture is +/// held too, 16 bytes a pixel in all (about 1 GiB at 8192 a side); a machine that can't hold +/// them gets an error, not a crash. fn placed_raster(name: &str, pm: tiny_skia::Pixmap, view: &View, crs: Crs) -> Result { let (w, h) = (pm.width(), pm.height()); - let n = w as usize * h as usize; - let mut bands: Vec> = (0..3).map(|_| Vec::with_capacity(n)).collect(); + let mut bands: Vec> = (0..3) + .map(|_| rustgis_data::raster::grid::(w as usize, h as usize)) + .collect::>() + .map_err(|e| format!("{name}: {e}"))?; for px in pm.pixels() { // tiny-skia keeps colours premultiplied; a file keeps them straight. let c = px.demultiply(); @@ -373,6 +387,9 @@ fn placed_raster(name: &str, pm: tiny_skia::Pixmap, view: &View, crs: Crs) -> Re drop(pm); let cam = view.camera; let cell = cam.res / view.pixels_per_point; + // The renderer puts the centre at half the view's width in points, times the pixels per + // point, unrounded: the corner is half the view from it, whatever whole number of pixels the + // picture is. let transform = rustgis_data::raster::GeoTransform { origin_x: cam.center.x - view.width / 2.0 * cam.res, origin_y: cam.center.y + view.height / 2.0 * cam.res, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd2d80af46..b65d80721b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33229,7 +33229,9 @@ fn export_map_to_geotiff_draws_tile_layers_and_keeps_their_credits() { assert_eq!(out["copyright"], "© Röd"); let r = geotiff::read(std::io::Cursor::new(std::fs::read(&path).unwrap()), "tiles").unwrap(); assert_eq!(r.copyright.as_deref(), Some("(c) R?d")); - assert!(s.notices.iter().any(|n| n.text.contains("1 character of the credits is written as ?: © Röd")), "{:?}", s.notices); + assert!(s.notices.iter().any(|n| n.text.contains("written with 1 character as ?: © Röd")), "{:?}", s.notices); + // The tiles had all come: nothing says the picture has gaps. + assert!(!s.notices.iter().any(|n| n.text.contains("export again once")), "{:?}", s.notices); // The middle pixel is the tile's red. let i = 100 * r.width as usize + 150; let px: Vec = r.bands.iter().map(|b| b.data[i]).collect(); @@ -33238,6 +33240,30 @@ fn export_map_to_geotiff_draws_tile_layers_and_keeps_their_credits() { let n = s.notices.len(); s.map_mut().tiles[0].attribution = "© Red".into(); s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); - assert!(!s.notices[n..].iter().any(|n| n.text.contains("written as ?")), "{:?}", &s.notices[n..]); + assert!(!s.notices[n..].iter().any(|n| n.text.contains("Copyright tag")), "{:?}", &s.notices[n..]); + // A tile layer that can't be drawn (its archive gone) leaves a gap that would pass for data: + // said, as a warning. + let broken = dir.join("broken.mbtiles"); + let c = rusqlite::Connection::open(&broken).unwrap(); + c.execute_batch( + "CREATE TABLE metadata (name text, value text); CREATE TABLE tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob); + INSERT INTO metadata VALUES ('name', 'Broken'), ('format', 'png'), ('minzoom', '0'), ('maxzoom', '0'); + INSERT INTO tiles VALUES (0, 0, 0, x'00010203');", + ) + .unwrap(); + drop(c); + s.map_mut().tiles.clear(); + s.run("layer.addData", &json!({"path": broken.display().to_string()})).unwrap(); + // Its file gone before the map is drawn. + let gone = s.map().tiles[0].url.clone(); + std::fs::remove_file(&broken).unwrap(); + s.map_mut().tiles[0].url = gone.replace("broken", "gone"); + let n = s.notices.len(); + s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + assert!( + s.notices[n..].iter().any(|n| n.severity == rustgis_data::diagnostics::Severity::Warning && n.text.contains("couldn't be drawn")), + "{:?}", + &s.notices[n..] + ); std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 99884ce5b8..a9059418e5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5724,18 +5724,47 @@ pub fn render_png(map: &mut Map, view: &View) -> Result, String> { pm.into_pixmap().encode_png().map_err(|e| e.to_string()) } +/// A map drawn as data ([`render_placed`]), with what it holds besides its pixels. +pub struct Placed { + /// The pixels, premultiplied as tiny-skia keeps them. + pub pixmap: Pixmap, + /// The credits the map's tile layers ask for, for the file to keep. + pub credits: Vec, + /// Why parts of it may be empty: tiles or streamed data still on their way when the wait + /// ran out, tile layers that couldn't be drawn. In a picture placed on the ground a gap looks + /// like data, so an export says these. + pub gaps: Vec, +} + /// A map drawn as data, for an image placed on the ground (a GeoTIFF of the view): its layers /// and labels (the unplaced ones too, when the map shows them, as [`render_png`] draws them), -/// without the scale bar and the credits, which sit on the screen, not the ground. Gives back the -/// pixels (premultiplied, as tiny-skia keeps them) and the credits the map's tile layers ask for, -/// for the file to keep. Refuses what [`render_png`] refuses. -pub fn render_placed(map: &mut Map, view: &View) -> Result<(Pixmap, Vec), String> { +/// without the scale bar and the credits, which sit on the screen, not the ground. Refuses what +/// [`render_png`] refuses. +pub fn render_placed(map: &mut Map, view: &View) -> Result { let r = render_exported(map, view)?; + let mut gaps = Vec::new(); + if r.tiles_pending { + gaps.push("some tiles were still on their way when the export stopped waiting, so parts of tile layers are empty: export again once the map has drawn them".to_string()); + } + if r.data_pending { + gaps.push( + "streamed layers were still reading the view, so some features are missing: export again once the map has drawn them" + .to_string(), + ); + } + if let Some(first) = r.tile_errors.first() { + let n = r.tile_errors.len(); + gaps.push(if n == 1 { + format!("a tile layer couldn't be drawn, so its part is empty: {first}") + } else { + format!("{n} tile layers couldn't be drawn, so their parts are empty; the first: {first}") + }); + } let mut pm = Canvas::from_pixmap(r.pixmap); for l in r.unplaced.iter().chain(&r.labels) { text::draw(&mut pm, l, view.pixels_per_point as f32); } - Ok((pm.into_pixmap(), r.attribution)) + Ok(Placed { pixmap: pm.into_pixmap(), credits: r.attribution, gaps }) } /// The map drawn whole for an export, or why it can't be written: a raster read in place whose diff --git a/crates/ui-egui/src/exportjob.rs b/crates/ui-egui/src/exportjob.rs index 7c6015eccb..8f5363311c 100644 --- a/crates/ui-egui/src/exportjob.rs +++ b/crates/ui-egui/src/exportjob.rs @@ -158,4 +158,44 @@ mod tests { } let _ = std::fs::remove_dir_all(&dir); } + + /// The ribbon's Export Map to a `.tif` draws at 192 DPI where that fits a GeoTIFF's 8192 + /// pixels a side, and at the most that fits (said) where it doesn't; a PNG keeps 192. The + /// GeoTIFF is written on a thread like the PNG. + #[test] + fn export_map_to_a_geotiff_fits_its_dpi_to_the_view() { + let mut app = RustGisApp::with_sample(); + app.session.view_size = (1200.0, 800.0); + assert_eq!(app.export_map_dpi("small.tif"), 192.0); + app.session.view_size = (5000.0, 3000.0); + let n = app.session.notices.len(); + assert_eq!(app.export_map_dpi("wide.png"), 192.0); + assert_eq!(app.session.notices.len(), n); + // 8192 × 96 / 5000 = 157.3: whole DPI, down. + assert_eq!(app.export_map_dpi("wide.tif"), 157.0); + assert!(app.session.notices[n..].iter().any(|x| x.text.contains("drawn at 157 DPI")), "{:?}", &app.session.notices[n..]); + // A turned view counts its box: 3000 points square fits at 192 DPI (6000 pixels), turned + // 45° its box is 4243 points (8486 pixels), which doesn't. + app.session.view_size = (3000.0, 3000.0); + assert_eq!(app.export_map_dpi("square.tif"), 192.0); + app.session.map_mut().camera.bearing = 45.0; + assert_eq!(app.export_map_dpi("square.TIF"), 185.0); + app.session.map_mut().camera.bearing = 0.0; + + app.session.view_size = (400.0, 300.0); + let dir = std::env::temp_dir().join(format!("rustgis-export-tif-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("map.tif"); + crate::dialogs::PICKED.with(|c| *c.borrow_mut() = Some(path.display().to_string())); + assert_eq!(app.run("ui.exportMap", Value::Null).unwrap()["started"], "Export Map"); + let end = std::time::Instant::now() + std::time::Duration::from_secs(120); + while land(&mut app) { + assert!(std::time::Instant::now() < end, "Export Map never landed"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let r = rustgis_engine::data::raster::geotiff::read(std::io::Cursor::new(std::fs::read(&path).unwrap()), "map").unwrap(); + // 400 × 300 points at 192 DPI. + assert_eq!((r.width, r.height, r.bands.len()), (800, 600, 3)); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8d1e25c163..704c882ec4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1123,6 +1123,33 @@ pub struct RustGisApp { } impl RustGisApp { + /// The DPI the ribbon's Export Map draws `path` at: 192, or for a GeoTIFF of a view too large + /// for that (one side past 8192 pixels, a turned view's box counted), the most that fits, said + /// in a notice. A PNG keeps 192. + fn export_map_dpi(&mut self, path: &str) -> f64 { + const DPI: f64 = 192.0; + let tif = std::path::Path::new(path) + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("tif") || e.eq_ignore_ascii_case("tiff")); + let (vw, vh) = self.session.view_size; + let camera = self.session.map().camera; + // As the export works it out: a turned view's box, rounded up to whole points; the pixels + // rounded. + let b = camera.bearing.rem_euclid(360.0); + let turned = b.min(360.0 - b) > 1e-9; + let (bw, bh) = if turned { camera.rotated_size(vw, vh) } else { (vw, vh) }; + let side = if turned { bw.ceil().max(bh.ceil()) } else { bw.max(bh) }; + let most = f64::from(rustgis_engine::render::MAX_SIDE); + if !tif || !side.is_finite() || (side * DPI / 96.0).round() <= most { + return DPI; + } + // Whole DPI, rounded down so the side fits; the export's own limit (48) refuses smaller. + let dpi = (most * 96.0 / side).floor().max(48.0); + self.session.notify(format!("{path}: drawn at {dpi} DPI, the most a GeoTIFF of this view holds (8192 pixels a side)"), false); + dpi + } + /// The layer to export: `layer` (an id or name, as commands take it; the dialog's is checked /// against its `instance`, so a reused id isn't taken for it), else the active layer. fn export_target(&self, p: &Value) -> Result { @@ -3961,16 +3988,17 @@ impl RustGisApp { let name = format!("{}.png", self.session.map().name); // A .tif is the view placed on the ground (a GeoTIFF), without the scale bar. if let Some(path) = dialogs::pick_save(&name, &["png", "tif", "tiff"], tl!("PNG image or GeoTIFF")) { + let dpi = self.export_map_dpi(&path); // Drawn on a thread of its own, with progress and Cancel in the status bar; // here while a style added with its own view loads, as the command waits for // it to move the map there first. #[cfg(not(target_arch = "wasm32"))] if self.session.style_view.is_none() { - return exportjob::start(self, "share.exportMap", json!({"path": path, "dpi": 192})); + return exportjob::start(self, "share.exportMap", json!({"path": path, "dpi": dpi})); } #[cfg(not(target_arch = "wasm32"))] exportjob::idle(self)?; - return self.run("share.exportMap", json!({"path": path, "dpi": 192})); + return self.run("share.exportMap", json!({"path": path, "dpi": dpi})); } } "ui.exportLayer" => { diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index ba2e80ff32..4c6545bf70 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -10,10 +10,13 @@ Export Map to a `.tif` path writes the view as a GeoTIFF instead: an RGB image p ground in the map's projection, so another GIS opens it where it belongs. It holds the layers, tile and WMS layers included, and the labels, but not the scale bar or the credits. The credits go into the file's Copyright tag, which holds plain ASCII (`©` is written as `(c)`, and the export -says when other characters are written as `?`); its answer gives them in full as `copyright`. `"cog": true` writes a +says when other characters are written as `?`, or control characters as spaces); its answer gives them in full as `copyright`. `"cog": true` writes a cloud-optimised GeoTIFF. A turned map is drawn north up over the box around the view (and says so). A tilted map, the globe and a map of another body are refused: export a PNG of those. One -side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`. A projection +side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`; the ribbon +draws a GeoTIFF of a view too large for 192 DPI at the most that fits, and says so. Tiles still +on their way when the export stops waiting, streamed layers still reading the view, and tile +layers that can't be drawn leave gaps that would pass for data, so the export warns about them. The web app's Export Map downloads a PNG. A projection whose parameters GeoTIFF's keys can't hold (Mollweide or Robinson, for example) is refused too: switch the map to an EPSG projection first. From 5491b3ff6387b979ddcfa3218120e4de22803ad7 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 7 Nov 2026 23:41:49 +0100 Subject: [PATCH 03/12] =?UTF-8?q?fix(share):=20say=20=C2=A9=20written=20as?= =?UTF-8?q?=20(c),=20and=20a=20view=20cut=20to=208000=20points;=20the=20ri?= =?UTF-8?q?bbon's=20DPI=20fits=20the=20clamped=20view?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tag_text_note says each change the Copyright tag makes: (c)/(R), ?, spaces; Export Map and Export Raster share it. - Export Map says when a view past 8000 points (no size given) is cut to its middle, PNG and GeoTIFF. - The ribbon works out a GeoTIFF's DPI from the view clamped as the export clamps it, and its notice is translatable. --- crates/data/src/raster/geotiff.rs | 11 +++++-- crates/data/src/raster/mod.rs | 28 ++++++++++++++---- crates/engine/src/cmd/raster.rs | 9 ++---- crates/engine/src/cmd/share.rs | 49 ++++++++++++++++++------------- crates/engine/src/tests.rs | 26 ++++++++++++++-- crates/ui-egui/src/exportjob.rs | 3 ++ crates/ui-egui/src/lib.rs | 11 +++++-- docs/user-guide/sharing.md | 9 ++++-- 8 files changed, 103 insertions(+), 43 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 92a6fcc738..28aad8c680 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1771,9 +1771,16 @@ mod tests { r.copyright = Some("© OpenStreetMap contributors | Bundesamt für Landestopografie\0\n".into()); let want = Some("(c) OpenStreetMap contributors | Bundesamt f?r Landestopografie".to_string()); // One written as ?; the NUL and line break at the end are trimmed, not counted. - assert_eq!(super::super::tag_text_changes(r.copyright.as_deref().unwrap()), (1, 0)); + assert_eq!(super::super::tag_text_changes(r.copyright.as_deref().unwrap()), (1, 1, 0)); // Inside, a line break and U+0085 (a control character outside ASCII) are spaces. - assert_eq!(super::super::tag_text_changes("a\nb\u{85}c ü"), (1, 2)); + assert_eq!(super::super::tag_text_changes("a\nb\u{85}c ü"), (0, 1, 2)); + assert_eq!( + super::super::tag_text_note("© a\nb ü").as_deref(), + Some( + "the Copyright tag holds ASCII only, so it is written with 1 © or ® as (c) or (R), 1 character as ?, 1 control character as a space" + ) + ); + assert_eq!(super::super::tag_text_note("plain"), None); assert_eq!(super::super::tag_text("a\nb\u{85}c ü"), "a b c ?"); // A scan (a TIFF with no GeoTIFF tags) keeps it too. let mut buf = std::io::Cursor::new(Vec::new()); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index fbab2406e3..1c34642b93 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -630,13 +630,31 @@ pub fn tag_text(s: &str) -> String { out.trim().to_string() } -/// How many characters of `s` [`tag_text`] writes as `?`, and how many control characters it -/// writes as spaces, line breaks and tabs among them (the trimmed ends not counted): for a -/// writer to say. -pub fn tag_text_changes(s: &str) -> (usize, usize) { +/// What [`tag_text`] changes in `s` (the trimmed ends not counted): how many `©` and `®` it +/// writes as `(c)` and `(R)`, how many characters as `?`, and how many control characters as +/// spaces, line breaks and tabs among them. +pub fn tag_text_changes(s: &str) -> (usize, usize, usize) { let inner = s.trim_matches(|c: char| c.is_control() || c.is_ascii_whitespace()); + let symbols = inner.chars().filter(|c| matches!(c, '©' | '®')).count(); let questioned = inner.chars().filter(|c| !c.is_ascii() && !c.is_control() && !matches!(c, '©' | '®')).count(); - (questioned, inner.chars().filter(|c| c.is_control()).count()) + (symbols, questioned, inner.chars().filter(|c| c.is_control()).count()) +} + +/// What writing `s` to a TIFF ASCII tag ([`tag_text`]) changes, for an export to say: `None` +/// when it is written as it is. +pub fn tag_text_note(s: &str) -> Option { + let (symbols, questioned, spaced) = tag_text_changes(s); + let count = |n: usize, one: &str, many: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {many}") }; + let parts: Vec = [ + (symbols, count(symbols, "© or ® as (c) or (R)", "© or ® as (c) or (R)")), + (questioned, count(questioned, "character as ?", "characters as ?")), + (spaced, count(spaced, "control character as a space", "control characters as spaces")), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(_, part)| part) + .collect(); + (!parts.is_empty()).then(|| format!("the Copyright tag holds ASCII only, so it is written with {}", parts.join(", "))) } /// How many of the names [`gdal_metadata_of`] writes for `bands` hold a character XML can't (a diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 3c17ed3d5e..0c670b2184 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -993,13 +993,8 @@ fn write_geotiff(r: &Raster, bi: usize, cog: bool, path: &str) -> Result 0 { - note.push_str(&format!( - "; its Copyright tag holds ASCII only, so {questioned} character(s) are written as ? and {spaced} control character(s) as spaces" - )); - } + if let Some(said) = r.copyright.as_deref().and_then(raster::tag_text_note) { + note.push_str(&format!("; {said}")); } let spaced = raster::gdal_metadata_changed(r, &bands); if spaced > 0 { diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 5afd6dfbc5..adaa7fe5d2 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -166,6 +166,9 @@ fn png_of( rustgis_render::render_png(map, &view) } +/// The most points a side an export of the map draws; a larger view is cut to its middle. +pub const MOST_POINTS: f64 = 8000.0; + /// The view an export of the map at `camera` draws, in a view of `(vw, vh)` points: a requested /// size keeps the same ground extent, and `dpi` sets the pixels per point. fn export_view( @@ -178,8 +181,8 @@ fn export_view( // NaN would pass through `clamp`; non-finite values fall back to the defaults. let fin = |v: Option| v.filter(|x| x.is_finite()); let (width, height, dpi) = (fin(width), fin(height), fin(dpi)); - let w = width.unwrap_or(vw).clamp(16.0, 8000.0); - let h = height.unwrap_or(vh).clamp(16.0, 8000.0); + let w = width.unwrap_or(vw).clamp(16.0, MOST_POINTS); + let h = height.unwrap_or(vh).clamp(16.0, MOST_POINTS); let ppp = (dpi.unwrap_or(96.0) / 96.0).clamp(0.5, 6.0); let mut camera = camera; // Keep the same ground extent when the size differs from the view. @@ -222,8 +225,19 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { None | Some(Value::Null) => false, Some(v) => v.as_bool().ok_or("cog must be true or false")?, }; + // A view past the most an export draws (and no size given) is cut to its middle: said. + let (vw, vh) = s.view_size; + let cut = (width.is_none() && vw > MOST_POINTS) || (height.is_none() && vh > MOST_POINTS); + let cut = cut.then(|| { + ( + rustgis_data::diagnostics::Severity::Info, + format!( + "{path}: the view is {vw:.0} × {vh:.0} points, more than the {MOST_POINTS:.0} a side an export holds, so it is cut to its middle: give a width and height to fit it whole" + ), + ) + }); if matches!(ext.as_str(), "tif" | "tiff") { - return geotiff_work(s, path, export_view(s.map().camera, s.view_size, width, height, dpi), cog); + return geotiff_work(s, path, export_view(s.map().camera, s.view_size, width, height, dpi), cog, cut); } if cog { return Err("cog is for a GeoTIFF (.tif) export".into()); @@ -236,7 +250,7 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { rustgis_data::io::write_atomic(Path::new(&path), &png).map_err(|e| format!("{path}: {e}"))?; Ok(json!({"path": path, "bytes": png.len()})) })(); - super::exports::drawn(std::slice::from_ref(&map), Vec::new(), written, path) + super::exports::drawn(std::slice::from_ref(&map), cut.into_iter().collect(), written, path) })) } @@ -247,7 +261,13 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { /// data. A turned view is drawn north up over the box around it, and says so; a tilted view, the /// globe and a map of another body are refused, as no grid of square pixels in one coordinate /// system holds them. -fn geotiff_work(s: &Session, path: String, view: View, cog: bool) -> Result { +fn geotiff_work( + s: &Session, + path: String, + view: View, + cog: bool, + cut: Option<(rustgis_data::diagnostics::Severity, String)>, +) -> Result { let m = s.map(); let crs = map_crs(m)?; if view.camera.pitch.abs() > 1e-6 { @@ -257,7 +277,7 @@ fn geotiff_work(s: &Session, path: String, view: View, cog: bool) -> Result = cut.into_iter().collect(); let bearing = view.camera.bearing; let turned = bearing.rem_euclid(360.0).min(360.0 - bearing.rem_euclid(360.0)) > 1e-9; if turned { @@ -311,21 +331,8 @@ fn geotiff_work(s: &Session, path: String, view: View, cog: bool) -> Result = [(questioned, "as ?"), (spaced, "(control characters) as spaces")] - .into_iter() - .filter(|(n, _)| *n > 0) - .map(|(n, how)| format!("{} {how}", count(n))) - .collect(); - if !changes.is_empty() { - notices.push(( - rustgis_data::diagnostics::Severity::Info, - format!( - "{path}: the Copyright tag holds ASCII only, so the credits are written with {}: {c}", - changes.join(" and ") - ), - )); + if let Some(note) = rustgis_data::raster::tag_text_note(c) { + notices.push((rustgis_data::diagnostics::Severity::Info, format!("{path}: {note} (the credits: {c})"))); } } Ok(out) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b65d80721b..aa79684797 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33144,6 +33144,18 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { assert!(e.contains("cog is for a GeoTIFF"), "{e}"); let e = s.run("share.exportMap", &json!({"path": cog.display().to_string(), "cog": "yes"})).unwrap_err(); assert!(e.contains("cog must be true or false"), "{e}"); + // A view past 8000 points (no size given) is cut to its middle, and says so, as a PNG does; + // one that fits says nothing. + let n = s.notices.len(); + s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + assert!(!s.notices[n..].iter().any(|x| x.text.contains("cut to its middle"))); + s.view_size = (9000.0, 300.0); + for file in ["wide.tif", "wide.png"] { + let n = s.notices.len(); + s.run("share.exportMap", &json!({"path": dir.join(file).display().to_string()})).unwrap(); + assert!(s.notices[n..].iter().any(|x| x.text.contains("9000 × 300 points") && x.text.contains("cut to its middle")), "{file}"); + } + s.view_size = (400.0, 300.0); // Too many pixels a side is refused, saying how many. let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 8000, "dpi": 192})).unwrap_err(); assert!(e.contains("16000") && e.contains("8192") && !e.contains("turned"), "{e}"); @@ -33229,18 +33241,26 @@ fn export_map_to_geotiff_draws_tile_layers_and_keeps_their_credits() { assert_eq!(out["copyright"], "© Röd"); let r = geotiff::read(std::io::Cursor::new(std::fs::read(&path).unwrap()), "tiles").unwrap(); assert_eq!(r.copyright.as_deref(), Some("(c) R?d")); - assert!(s.notices.iter().any(|n| n.text.contains("written with 1 character as ?: © Röd")), "{:?}", s.notices); + assert!( + s.notices.iter().any(|n| n.text.contains("written with 1 © or ® as (c) or (R), 1 character as ? (the credits: © Röd)")), + "{:?}", + s.notices + ); // The tiles had all come: nothing says the picture has gaps. assert!(!s.notices.iter().any(|n| n.text.contains("export again once")), "{:?}", s.notices); // The middle pixel is the tile's red. let i = 100 * r.width as usize + 150; let px: Vec = r.bands.iter().map(|b| b.data[i]).collect(); assert_eq!(px, [255.0, 0.0, 0.0]); - // Credits that are ASCII but for © say nothing. + // ASCII credits say nothing; a © alone says it is written as (c). let n = s.notices.len(); - s.map_mut().tiles[0].attribution = "© Red".into(); + s.map_mut().tiles[0].attribution = "(c) Red".into(); s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); assert!(!s.notices[n..].iter().any(|n| n.text.contains("Copyright tag")), "{:?}", &s.notices[n..]); + let n = s.notices.len(); + s.map_mut().tiles[0].attribution = "© Red".into(); + s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + assert!(s.notices[n..].iter().any(|n| n.text.contains("written with 1 © or ® as (c) or (R) (the credits")), "{:?}", &s.notices[n..]); // A tile layer that can't be drawn (its archive gone) leaves a gap that would pass for data: // said, as a warning. let broken = dir.join("broken.mbtiles"); diff --git a/crates/ui-egui/src/exportjob.rs b/crates/ui-egui/src/exportjob.rs index 8f5363311c..1970525ca7 100644 --- a/crates/ui-egui/src/exportjob.rs +++ b/crates/ui-egui/src/exportjob.rs @@ -174,6 +174,9 @@ mod tests { // 8192 × 96 / 5000 = 157.3: whole DPI, down. assert_eq!(app.export_map_dpi("wide.tif"), 157.0); assert!(app.session.notices[n..].iter().any(|x| x.text.contains("drawn at 157 DPI")), "{:?}", &app.session.notices[n..]); + // A view past 8000 points is clamped as the export clamps it: 16000 wide fits 98 DPI. + app.session.view_size = (16000.0, 3000.0); + assert_eq!(app.export_map_dpi("huge.tif"), 98.0); // A turned view counts its box: 3000 points square fits at 192 DPI (6000 pixels), turned // 45° its box is 4243 points (8486 pixels), which doesn't. app.session.view_size = (3000.0, 3000.0); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 704c882ec4..94b9f7b27a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1132,7 +1132,9 @@ impl RustGisApp { .extension() .and_then(|e| e.to_str()) .is_some_and(|e| e.eq_ignore_ascii_case("tif") || e.eq_ignore_ascii_case("tiff")); - let (vw, vh) = self.session.view_size; + // As the export clamps it. + let most_points = rustgis_engine::cmd::share::MOST_POINTS; + let (vw, vh) = (self.session.view_size.0.clamp(16.0, most_points), self.session.view_size.1.clamp(16.0, most_points)); let camera = self.session.map().camera; // As the export works it out: a turned view's box, rounded up to whole points; the pixels // rounded. @@ -1146,7 +1148,12 @@ impl RustGisApp { } // Whole DPI, rounded down so the side fits; the export's own limit (48) refuses smaller. let dpi = (most * 96.0 / side).floor().max(48.0); - self.session.notify(format!("{path}: drawn at {dpi} DPI, the most a GeoTIFF of this view holds (8192 pixels a side)"), false); + let shown = dpi.to_string(); + let note = crate::i18n::fmt( + "{path}: drawn at {dpi} DPI, the most a GeoTIFF of this view holds (8192 pixels a side)", + &[("path", path), ("dpi", &shown)], + ); + self.session.notify(note, false); dpi } diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index 4c6545bf70..5ea1f7975b 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -9,12 +9,15 @@ in pixels and a `dpi` value (96 by default). Export Map to a `.tif` path writes the view as a GeoTIFF instead: an RGB image placed on the ground in the map's projection, so another GIS opens it where it belongs. It holds the layers, tile and WMS layers included, and the labels, but not the scale bar or the credits. The credits go -into the file's Copyright tag, which holds plain ASCII (`©` is written as `(c)`, and the export -says when other characters are written as `?`, or control characters as spaces); its answer gives them in full as `copyright`. `"cog": true` writes a +into the file's Copyright tag, which holds plain ASCII: `©` and `®` are written as `(c)` and `(R)`, +other characters as `?` and control characters as spaces, and the export says which. Its answer +gives them in full as `copyright`. `"cog": true` writes a cloud-optimised GeoTIFF. A turned map is drawn north up over the box around the view (and says so). A tilted map, the globe and a map of another body are refused: export a PNG of those. One side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`; the ribbon -draws a GeoTIFF of a view too large for 192 DPI at the most that fits, and says so. Tiles still +draws a GeoTIFF of a view too large for 192 DPI at the most that fits, and says so. A view wider +or taller than 8000 points, PNG or GeoTIFF, is cut to its middle unless `width` and `height` are +given, and the export says so. Tiles still on their way when the export stops waiting, streamed layers still reading the view, and tile layers that can't be drawn leave gaps that would pass for data, so the export warns about them. The web app's Export Map downloads a PNG. A projection whose parameters GeoTIFF's keys can't hold (Mollweide or Robinson, for example) is refused too: From e35fbe414e459fdac92383983c8bf53ab53fd0f8 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 8 Nov 2026 00:40:00 +0100 Subject: [PATCH 04/12] fix(share): say when a size past 8000 points is drawn at 8000, and when credits leave no tag - size_notes: with no size, a view past 8000 points is cut to its middle (and the advice is a width or height of at most 8000); a width or height past 8000 is drawn at 8000 over the same ground. PNG and GeoTIFF. - Credits with nothing a tag can hold write no Copyright tag, and say so. - The gap test takes either warning a missing archive gives. --- crates/engine/src/cmd/share.rs | 55 ++++++++++++++++++++++++---------- crates/engine/src/tests.rs | 18 ++++++++++- docs/user-guide/sharing.md | 7 +++-- 3 files changed, 61 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index adaa7fe5d2..a3176975c5 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -169,6 +169,34 @@ fn png_of( /// The most points a side an export of the map draws; a larger view is cut to its middle. pub const MOST_POINTS: f64 = 8000.0; +/// What [`export_view`]'s limit of [`MOST_POINTS`] a side does to an export to `path` of a view +/// of `(vw, vh)` points, for it to say: with no size given, a larger view is cut to its middle; +/// a size given past the limit is drawn at the limit, over the same ground. +fn size_notes( + path: &str, + (vw, vh): (f64, f64), + width: Option, + height: Option, +) -> Vec<(rustgis_data::diagnostics::Severity, String)> { + let fin = |v: Option| v.filter(|x| x.is_finite()); + let (width, height) = (fin(width), fin(height)); + let mut notes = Vec::new(); + let note = |text: String| (rustgis_data::diagnostics::Severity::Info, format!("{path}: {text}")); + if width.is_none() && height.is_none() && (vw > MOST_POINTS || vh > MOST_POINTS) { + notes.push(note(format!( + "the view is {vw:.0} × {vh:.0} points, more than the {MOST_POINTS:.0} a side an export holds, so it is cut to its middle: give a width or height of at most {MOST_POINTS:.0} to draw it whole" + ))); + } + for (name, v) in [("width", width), ("height", height)] { + if let Some(v) = v.filter(|v| *v > MOST_POINTS) { + notes.push(note(format!( + "a {name} of {v:.0} points is more than the {MOST_POINTS:.0} an export holds, so it is drawn at {MOST_POINTS:.0} over the same ground: a higher dpi gives more pixels" + ))); + } + } + notes +} + /// The view an export of the map at `camera` draws, in a view of `(vw, vh)` points: a requested /// size keeps the same ground extent, and `dpi` sets the pixels per point. fn export_view( @@ -225,19 +253,9 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { None | Some(Value::Null) => false, Some(v) => v.as_bool().ok_or("cog must be true or false")?, }; - // A view past the most an export draws (and no size given) is cut to its middle: said. - let (vw, vh) = s.view_size; - let cut = (width.is_none() && vw > MOST_POINTS) || (height.is_none() && vh > MOST_POINTS); - let cut = cut.then(|| { - ( - rustgis_data::diagnostics::Severity::Info, - format!( - "{path}: the view is {vw:.0} × {vh:.0} points, more than the {MOST_POINTS:.0} a side an export holds, so it is cut to its middle: give a width and height to fit it whole" - ), - ) - }); + let sized = size_notes(&path, s.view_size, width, height); if matches!(ext.as_str(), "tif" | "tiff") { - return geotiff_work(s, path, export_view(s.map().camera, s.view_size, width, height, dpi), cog, cut); + return geotiff_work(s, path, export_view(s.map().camera, s.view_size, width, height, dpi), cog, sized); } if cog { return Err("cog is for a GeoTIFF (.tif) export".into()); @@ -250,7 +268,7 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { rustgis_data::io::write_atomic(Path::new(&path), &png).map_err(|e| format!("{path}: {e}"))?; Ok(json!({"path": path, "bytes": png.len()})) })(); - super::exports::drawn(std::slice::from_ref(&map), cut.into_iter().collect(), written, path) + super::exports::drawn(std::slice::from_ref(&map), sized, written, path) })) } @@ -266,7 +284,7 @@ fn geotiff_work( path: String, view: View, cog: bool, - cut: Option<(rustgis_data::diagnostics::Severity, String)>, + sized: Vec<(rustgis_data::diagnostics::Severity, String)>, ) -> Result { let m = s.map(); let crs = map_crs(m)?; @@ -277,7 +295,7 @@ fn geotiff_work( )); } let mut view = view; - let mut notices: Vec<_> = cut.into_iter().collect(); + let mut notices = sized; let bearing = view.camera.bearing; let turned = bearing.rem_euclid(360.0).min(360.0 - bearing.rem_euclid(360.0)) > 1e-9; if turned { @@ -331,6 +349,13 @@ fn geotiff_work( let mut out = json!({"path": path, "width": r.width, "height": r.height, "crs": crs.label(), "bytes": bytes}); if let Some(c) = &r.copyright { out["copyright"] = json!(c); + // Credits with nothing a tag can hold (control characters only) write no tag. + if rustgis_data::raster::tag_text(c).is_empty() { + notices.push(( + rustgis_data::diagnostics::Severity::Info, + format!("{path}: the credits hold nothing a Copyright tag can, so the file has none: {c:?}"), + )); + } if let Some(note) = rustgis_data::raster::tag_text_note(c) { notices.push((rustgis_data::diagnostics::Severity::Info, format!("{path}: {note} (the credits: {c})"))); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index aa79684797..802b7a143e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33155,7 +33155,21 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { s.run("share.exportMap", &json!({"path": dir.join(file).display().to_string()})).unwrap(); assert!(s.notices[n..].iter().any(|x| x.text.contains("9000 × 300 points") && x.text.contains("cut to its middle")), "{file}"); } + // A size given draws the whole view, so nothing is cut. + let n = s.notices.len(); + s.run("share.exportMap", &json!({"path": dir.join("fit.tif").display().to_string(), "width": 4000})).unwrap(); + assert!(!s.notices[n..].iter().any(|x| x.text.contains("cut to its middle") || x.text.contains("points is more than"))); s.view_size = (400.0, 300.0); + // A size given past the limit is drawn at the limit, and says so. + let n = s.notices.len(); + let out = s.run("share.exportMap", &json!({"path": dir.join("big.tif").display().to_string(), "width": 9000, "height": 150})).unwrap(); + assert_eq!(out["width"], 8000); + assert!( + s.notices[n..].iter().any(|x| x.text.contains("a width of 9000 points") && x.text.contains("drawn at 8000")), + "{:?}", + &s.notices[n..] + ); + assert!(!s.notices[n..].iter().any(|x| x.text.contains("height of"))); // Too many pixels a side is refused, saying how many. let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 8000, "dpi": 192})).unwrap_err(); assert!(e.contains("16000") && e.contains("8192") && !e.contains("turned"), "{e}"); @@ -33280,8 +33294,10 @@ fn export_map_to_geotiff_draws_tile_layers_and_keeps_their_credits() { s.map_mut().tiles[0].url = gone.replace("broken", "gone"); let n = s.notices.len(); s.run("share.exportMap", &json!({"path": path.display().to_string()})).unwrap(); + // Said as a tile layer that couldn't be drawn, or (where the reader is slower to give up) + // tiles still on their way: either way a warning that parts are empty. assert!( - s.notices[n..].iter().any(|n| n.severity == rustgis_data::diagnostics::Severity::Warning && n.text.contains("couldn't be drawn")), + s.notices[n..].iter().any(|n| n.severity == rustgis_data::diagnostics::Severity::Warning && n.text.contains("empty")), "{:?}", &s.notices[n..] ); diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index 5ea1f7975b..b491d0ff0d 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -15,9 +15,10 @@ gives them in full as `copyright`. `"cog": true` writes a cloud-optimised GeoTIFF. A turned map is drawn north up over the box around the view (and says so). A tilted map, the globe and a map of another body are refused: export a PNG of those. One side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`; the ribbon -draws a GeoTIFF of a view too large for 192 DPI at the most that fits, and says so. A view wider -or taller than 8000 points, PNG or GeoTIFF, is cut to its middle unless `width` and `height` are -given, and the export says so. Tiles still +draws a GeoTIFF of a view too large for 192 DPI at the most that fits, and says so. An export holds +at most 8000 points a side, PNG or GeoTIFF: with no `width` or `height`, a larger view is cut to +its middle; a `width` or `height` past 8000 is drawn at 8000 over the same ground. Either way the +export says so. Tiles still on their way when the export stops waiting, streamed layers still reading the view, and tile layers that can't be drawn leave gaps that would pass for data, so the export warns about them. The web app's Export Map downloads a PNG. A projection whose parameters GeoTIFF's keys can't hold (Mollweide or Robinson, for example) is refused too: From 9e2aead8c69145bef6961ac7be72e99d899c7d3e Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 8 Nov 2026 01:16:07 +0100 Subject: [PATCH 05/12] fix(share): a size past 8000 points holds less ground, said only of a file written; width and height are points - The clamp notice says the image holds less ground than asked (the whole view still fits), and comes only when the file is written. - tag_text_note says when credits leave no tag; tests for that and for a Copyright tag that isn't text. - The fit test checks the footprint; width and height are documented as points, with the DPI conversion. --- crates/data/src/raster/geotiff.rs | 20 ++++++++++++++++++++ crates/data/src/raster/mod.rs | 6 +++++- crates/engine/src/cmd/share.rs | 22 +++++++++++----------- crates/engine/src/tests.rs | 8 +++++++- docs/user-guide/sharing.md | 6 ++++-- 5 files changed, 47 insertions(+), 15 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 28aad8c680..2e1c8c25de 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1781,6 +1781,26 @@ mod tests { ) ); assert_eq!(super::super::tag_text_note("plain"), None); + assert_eq!(super::super::tag_text_note(""), None); + // Nothing a tag can hold: no tag is written, and that is said. + assert_eq!( + super::super::tag_text_note("\0\n").as_deref(), + Some("the credits hold nothing a Copyright tag can, so the file has none") + ); + let mut blank = small(); + blank.copyright = Some("\0\n".into()); + assert_eq!(read(std::io::Cursor::new(write(&blank, 0).unwrap()), "none").unwrap().copyright, None); + // A Copyright tag that isn't text (bytes, not ASCII) is left out, and said. + let mut buf = std::io::Cursor::new(Vec::new()); + { + let mut enc = tiff::encoder::TiffEncoder::new(&mut buf).unwrap(); + let mut img = enc.new_image::(2, 2).unwrap(); + img.encoder().write_tag(Tag::Copyright, &[0xA9u8, 0x20, 0x58][..]).unwrap(); + img.write_data(&[1, 2, 3, 4]).unwrap(); + } + let odd = read(std::io::Cursor::new(buf.into_inner()), "odd").unwrap(); + assert_eq!(odd.copyright, None); + assert!(odd.lost.iter().any(|l| l.starts_with("its Copyright tag: it isn't ASCII text")), "{:?}", odd.lost); assert_eq!(super::super::tag_text("a\nb\u{85}c ü"), "a b c ?"); // A scan (a TIFF with no GeoTIFF tags) keeps it too. let mut buf = std::io::Cursor::new(Vec::new()); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 1c34642b93..bc662ae49d 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -641,8 +641,12 @@ pub fn tag_text_changes(s: &str) -> (usize, usize, usize) { } /// What writing `s` to a TIFF ASCII tag ([`tag_text`]) changes, for an export to say: `None` -/// when it is written as it is. +/// when it is written as it is (or is empty); that no tag is written when nothing of it is left. pub fn tag_text_note(s: &str) -> Option { + // Nothing a tag can hold (control characters only): the writers write no tag. + if tag_text(s).is_empty() { + return (!s.is_empty()).then(|| "the credits hold nothing a Copyright tag can, so the file has none".to_string()); + } let (symbols, questioned, spaced) = tag_text_changes(s); let count = |n: usize, one: &str, many: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {many}") }; let parts: Vec = [ diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index a3176975c5..8c59271e19 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -26,7 +26,7 @@ pub fn commands() -> Vec { super::exports::write_here(s, p, "share.exportMap") }).inputs(map_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() - .params(r#"{"path": "*.png|*.tif|*.tiff", "width"?: px, "height"?: px, "dpi"?: 96..600, "cog"?: "true for a cloud-optimised GeoTIFF"}"#), + .params(r#"{"path": "*.png|*.tif|*.tiff", "width"?: "points (pixels at 96 dpi), the view fitted in it", "height"?: points, "dpi"?: 96..600, "cog"?: "true for a cloud-optimised GeoTIFF"}"#), C::new("share.exportLayer", "Export Features", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportLayer")).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_layer) @@ -171,7 +171,8 @@ pub const MOST_POINTS: f64 = 8000.0; /// What [`export_view`]'s limit of [`MOST_POINTS`] a side does to an export to `path` of a view /// of `(vw, vh)` points, for it to say: with no size given, a larger view is cut to its middle; -/// a size given past the limit is drawn at the limit, over the same ground. +/// a size given past the limit is drawn at the limit: the view still fits whole, with less ground +/// around it than the size asked for. fn size_notes( path: &str, (vw, vh): (f64, f64), @@ -190,7 +191,7 @@ fn size_notes( for (name, v) in [("width", width), ("height", height)] { if let Some(v) = v.filter(|v| *v > MOST_POINTS) { notes.push(note(format!( - "a {name} of {v:.0} points is more than the {MOST_POINTS:.0} an export holds, so it is drawn at {MOST_POINTS:.0} over the same ground: a higher dpi gives more pixels" + "a {name} of {v:.0} points is more than the {MOST_POINTS:.0} an export holds, so it is drawn at {MOST_POINTS:.0}, holding less ground than asked (the whole view still fits): a higher dpi gives more pixels" ))); } } @@ -268,6 +269,8 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { rustgis_data::io::write_atomic(Path::new(&path), &png).map_err(|e| format!("{path}: {e}"))?; Ok(json!({"path": path, "bytes": png.len()})) })(); + // What the size limit did is said of a file written. + let sized = if written.is_ok() { sized } else { Vec::new() }; super::exports::drawn(std::slice::from_ref(&map), sized, written, path) })) } @@ -295,7 +298,7 @@ fn geotiff_work( )); } let mut view = view; - let mut notices = sized; + let mut notices = Vec::new(); let bearing = view.camera.bearing; let turned = bearing.rem_euclid(360.0).min(360.0 - bearing.rem_euclid(360.0)) > 1e-9; if turned { @@ -349,19 +352,16 @@ fn geotiff_work( let mut out = json!({"path": path, "width": r.width, "height": r.height, "crs": crs.label(), "bytes": bytes}); if let Some(c) = &r.copyright { out["copyright"] = json!(c); - // Credits with nothing a tag can hold (control characters only) write no tag. - if rustgis_data::raster::tag_text(c).is_empty() { - notices.push(( - rustgis_data::diagnostics::Severity::Info, - format!("{path}: the credits hold nothing a Copyright tag can, so the file has none: {c:?}"), - )); - } if let Some(note) = rustgis_data::raster::tag_text_note(c) { notices.push((rustgis_data::diagnostics::Severity::Info, format!("{path}: {note} (the credits: {c})"))); } } Ok(out) })(); + // What the size limit did is said of a file written, first. + if written.is_ok() { + notices.splice(0..0, sized); + } super::exports::drawn(std::slice::from_ref(&map), notices, written, path) })) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 802b7a143e..dbd6811aa4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33086,7 +33086,7 @@ fn topology_refuses_latitudes_past_the_poles() { } /// `share.exportMap` to a `.tif` writes the view placed on the ground (#1561): in the map's -/// projection, each pixel where the view drew it, RGBA; a turned view north up over its box, and +/// projection, each pixel where the view drew it, RGB; a turned view north up over its box, and /// says so; a tilted view, the globe and junk refused. #[test] fn export_map_to_geotiff_places_the_view_on_the_ground() { @@ -33159,6 +33159,12 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { let n = s.notices.len(); s.run("share.exportMap", &json!({"path": dir.join("fit.tif").display().to_string(), "width": 4000})).unwrap(); assert!(!s.notices[n..].iter().any(|x| x.text.contains("cut to its middle") || x.text.contains("points is more than"))); + // The whole 9000-point view in 4000 points: each pixel 2.25 of the camera's, the same centre. + let fit = read(&dir.join("fit.tif")); + let cam = s.map().camera; + assert_eq!((fit.width, fit.height), (4000, 300)); + assert!((fit.transform.pixel_width - 2.25 * cam.res).abs() < 1e-6 * cam.res, "{:?}", fit.transform); + assert!((fit.transform.origin_x + 2000.0 * fit.transform.pixel_width - cam.center.x).abs() < 1e-3); s.view_size = (400.0, 300.0); // A size given past the limit is drawn at the limit, and says so. let n = s.notices.len(); diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index b491d0ff0d..7b24f12115 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -4,7 +4,8 @@ **Publish › Output › Export Map** writes the map view as a PNG with labels, the scale bar and tile credits. The ribbon exports at 192 DPI; `share.exportMap` accepts `width` and `height` -in pixels and a `dpi` value (96 by default). +in points, with the whole view fitted in them, and a `dpi` value (96 by default). A point is a +pixel at 96 DPI, so `"width": 400` at 192 DPI is an image 800 pixels wide. Export Map to a `.tif` path writes the view as a GeoTIFF instead: an RGB image placed on the ground in the map's projection, so another GIS opens it where it belongs. It holds the layers, @@ -17,7 +18,8 @@ so). A tilted map, the globe and a map of another body are refused: export a PNG side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`; the ribbon draws a GeoTIFF of a view too large for 192 DPI at the most that fits, and says so. An export holds at most 8000 points a side, PNG or GeoTIFF: with no `width` or `height`, a larger view is cut to -its middle; a `width` or `height` past 8000 is drawn at 8000 over the same ground. Either way the +its middle; a `width` or `height` past 8000 is drawn at 8000, holding less ground than asked (the whole +view still fits). Either way the export says so. Tiles still on their way when the export stops waiting, streamed layers still reading the view, and tile layers that can't be drawn leave gaps that would pass for data, so the export warns about them. The web app's Export Map downloads a PNG. A projection From 7ed947fa40411e18ff24e38920808cf047589ffd Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 8 Nov 2026 02:14:14 +0100 Subject: [PATCH 06/12] fix(share): credits in a notice are quoted and cut short; a turned box is covered in whole pixels - The notice shows the credits debug-quoted (control characters escaped) and at most 200 characters; the answer keeps them whole. - A Copyright tag that can't be read says so, apart from one that isn't text. - A turned view's box is sized so its rounded pixels cover it at any DPI. - The guide says the gap warnings are a GeoTIFF's. --- crates/data/src/raster/geotiff.rs | 3 ++- crates/engine/src/cmd/share.rs | 15 ++++++++++++--- crates/engine/src/tests.rs | 14 +++++++++++++- docs/user-guide/sharing.md | 7 ++++--- 4 files changed, 31 insertions(+), 8 deletions(-) diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 2e1c8c25de..f150e8af33 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1234,7 +1234,8 @@ pub(super) fn read_limited_with_nodata( 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))) | Err(e) => (None, Some(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out"))), + 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 spp = samples(&mut dec); let bytes = sample_bytes(&mut dec); diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 8c59271e19..b61e25cfc7 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -166,6 +166,9 @@ fn png_of( rustgis_render::render_png(map, &view) } +/// The most characters of the credits a GeoTIFF export's notice shows; its answer has them all. +const CREDITS_SHOWN: usize = 200; + /// The most points a side an export of the map draws; a larger view is cut to its middle. pub const MOST_POINTS: f64 = 8000.0; @@ -304,9 +307,11 @@ fn geotiff_work( if turned { // North up over the box around the turned view: everything it shows, and more at the // corners. + // In points whose pixels, once rounded, still cover the box. let (bw, bh) = view.camera.rotated_size(view.width, view.height); - view.width = bw.ceil(); - view.height = bh.ceil(); + let ppp = view.pixels_per_point; + view.width = (bw * ppp).ceil() / ppp; + view.height = (bh * ppp).ceil() / ppp; view.camera.bearing = 0.0; notices.push(( rustgis_data::diagnostics::Severity::Info, @@ -353,7 +358,11 @@ fn geotiff_work( if let Some(c) = &r.copyright { out["copyright"] = json!(c); if let Some(note) = rustgis_data::raster::tag_text_note(c) { - notices.push((rustgis_data::diagnostics::Severity::Info, format!("{path}: {note} (the credits: {c})"))); + // Quoted (control characters escaped, so a service's credits can't reach a + // terminal raw) and cut short: the answer holds them whole. + let shown: String = c.chars().take(CREDITS_SHOWN).collect(); + let more = if c.chars().count() > CREDITS_SHOWN { "…" } else { "" }; + notices.push((rustgis_data::diagnostics::Severity::Info, format!("{path}: {note} (the credits: {shown:?}{more})"))); } } Ok(out) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index dbd6811aa4..99dd9bdec3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33133,6 +33133,18 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { // North up over the box: the same place lands on the same ground. assert_eq!(at(&r2, 10.0, 50.0), land); assert!((r2.transform.pixel_width - cam.res).abs() < 1e-6 * cam.res); + // At 100 DPI the box isn't a whole number of pixels: the picture still covers all of it. + let at100 = dir.join("turned-100.tif"); + s.run("share.exportMap", &json!({"path": at100.display().to_string(), "width": 400, "height": 300, "dpi": 100})).unwrap(); + let r3 = read(&at100); + let (bw, bh) = s.map().camera.rotated_size(400.0, 300.0); + let cell = r3.transform.pixel_width; + assert!( + f64::from(r3.width) * cell >= bw * cam.res - 1e-6 && f64::from(r3.height) * cell >= bh * cam.res - 1e-6, + "{} × {}", + r3.width, + r3.height + ); s.run("map.setBearing", &json!({"bearing": 0})).unwrap(); // `cog` writes a cloud-optimised one; it's for a GeoTIFF only. let cog = dir.join("view-cog.tif"); @@ -33262,7 +33274,7 @@ fn export_map_to_geotiff_draws_tile_layers_and_keeps_their_credits() { let r = geotiff::read(std::io::Cursor::new(std::fs::read(&path).unwrap()), "tiles").unwrap(); assert_eq!(r.copyright.as_deref(), Some("(c) R?d")); assert!( - s.notices.iter().any(|n| n.text.contains("written with 1 © or ® as (c) or (R), 1 character as ? (the credits: © Röd)")), + s.notices.iter().any(|n| n.text.contains("written with 1 © or ® as (c) or (R), 1 character as ? (the credits: \"© Röd\")")), "{:?}", s.notices ); diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index 7b24f12115..66ae078f1e 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -20,9 +20,10 @@ draws a GeoTIFF of a view too large for 192 DPI at the most that fits, and says at most 8000 points a side, PNG or GeoTIFF: with no `width` or `height`, a larger view is cut to its middle; a `width` or `height` past 8000 is drawn at 8000, holding less ground than asked (the whole view still fits). Either way the -export says so. Tiles still -on their way when the export stops waiting, streamed layers still reading the view, and tile -layers that can't be drawn leave gaps that would pass for data, so the export warns about them. The web app's Export Map downloads a PNG. A projection +export says so. In a GeoTIFF, +tiles still on their way when the export stops waiting, streamed layers still reading the view, +and tile layers that can't be drawn leave gaps that would pass for data, so its export warns +about them. The web app's Export Map downloads a PNG. A projection whose parameters GeoTIFF's keys can't hold (Mollweide or Robinson, for example) is refused too: switch the map to an EPSG projection first. From d327ac1a0df76321e7dd8d48efb250b0aeb50c27 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 8 Nov 2026 03:16:18 +0100 Subject: [PATCH 07/12] fix(share): a PNG past 8192 pixels a side is refused, not cut off; 600 DPI is 600 - png_of checks the canvas limit as the GeoTIFF path does (fits_pixels), so a wide view at 192 DPI is refused with how many pixels it would be instead of being cropped at its top left; the ribbon fits the DPI for a PNG too. - export_view takes dpi up to 600 (6.25 pixels a point), as the command says. - Doc and wording nits. --- crates/data/src/raster/mod.rs | 2 +- crates/engine/src/cmd/share.rs | 36 ++++++++++++++++++++------------- crates/engine/src/tests.rs | 7 +++++++ crates/ui-egui/src/exportjob.rs | 9 +++++++-- crates/ui-egui/src/lib.rs | 13 ++++++------ docs/user-guide/sharing.md | 5 +++-- 6 files changed, 47 insertions(+), 25 deletions(-) diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index bc662ae49d..76053e3ce5 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -650,7 +650,7 @@ pub fn tag_text_note(s: &str) -> Option { let (symbols, questioned, spaced) = tag_text_changes(s); let count = |n: usize, one: &str, many: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {many}") }; let parts: Vec = [ - (symbols, count(symbols, "© or ® as (c) or (R)", "© or ® as (c) or (R)")), + (symbols, count(symbols, "© or ® as (c) or (R)", "©s or ®s as (c) or (R)")), (questioned, count(questioned, "character as ?", "characters as ?")), (spaced, count(spaced, "control character as a space", "control characters as spaces")), ] diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index b61e25cfc7..347bfa4ba5 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -163,9 +163,24 @@ fn png_of( dpi: Option, ) -> Result, String> { let view = export_view(map.camera, view_size, width, height, dpi); + // Past the canvas's limit the picture would be cut off at its top left: refused instead. + fits_pixels(&view, false)?; rustgis_render::render_png(map, &view) } +/// Refuses an export of `view` with a side past the [`rustgis_render::MAX_SIDE`] pixels a canvas +/// holds, saying how many it would be (and, for the box around a `turned` view, that the box is +/// why). +fn fits_pixels(view: &View, turned: bool) -> Result<(), String> { + let (pw, ph) = ((view.width * view.pixels_per_point).round(), (view.height * view.pixels_per_point).round()); + let most = f64::from(rustgis_render::MAX_SIDE); + if pw <= most && ph <= most { + return Ok(()); + } + let why = if turned { " (the box around the turned view; or set the bearing to 0)" } else { "" }; + Err(format!("{pw} × {ph} pixels{why} is more than the {most} a side an export draws: give a smaller width, height or dpi")) +} + /// The most characters of the credits a GeoTIFF export's notice shows; its answer has them all. const CREDITS_SHOWN: usize = 200; @@ -215,7 +230,8 @@ fn export_view( let (width, height, dpi) = (fin(width), fin(height), fin(dpi)); let w = width.unwrap_or(vw).clamp(16.0, MOST_POINTS); let h = height.unwrap_or(vh).clamp(16.0, MOST_POINTS); - let ppp = (dpi.unwrap_or(96.0) / 96.0).clamp(0.5, 6.0); + // 48 to 600 DPI, as the command says. + let ppp = (dpi.unwrap_or(96.0) / 96.0).clamp(0.5, 6.25); let mut camera = camera; // Keep the same ground extent when the size differs from the view. if width.is_some() || height.is_some() { @@ -247,7 +263,8 @@ pub fn map_pdf(s: &mut Session, dpi: f64) -> Result, String> { Ok(rustgis_render::pdf::write(&[page], &s.map().name)) } -/// `share.exportMap`: draws the active map as it is now to a PNG. It draws a copy of the map, so +/// `share.exportMap`: draws the active map as it is now to a PNG, or a GeoTIFF for a `.tif` or +/// `.tiff` path ([`geotiff_work`]). It draws a copy of the map, so /// the map can move meanwhile; a cancelled export stops waiting for tiles and writes nothing. pub(crate) fn map_work(s: &Session, p: &Value) -> Result { let path = ps(p, "path").ok_or("path is required")?.to_string(); @@ -262,7 +279,7 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { return geotiff_work(s, path, export_view(s.map().camera, s.view_size, width, height, dpi), cog, sized); } if cog { - return Err("cog is for a GeoTIFF (.tif) export".into()); + return Err("cog is for a GeoTIFF (.tif or .tiff) export".into()); } let (mut map, view_size) = (s.map().detached(), s.view_size); Ok(Box::new(move || { @@ -318,17 +335,8 @@ fn geotiff_work( format!("{path}: the map is turned {bearing:.0}°, so the GeoTIFF is drawn north up over the box around the view"), )); } - let (pw, ph) = (view.width * view.pixels_per_point, view.height * view.pixels_per_point); - let most = f64::from(rustgis_render::MAX_SIDE); - if pw.round() > most || ph.round() > most { - // A turned view's box is larger than the view: say so, as the fix differs. - let turned = if turned { " (the box around the turned view; or set the bearing to 0)" } else { "" }; - return Err(format!( - "{} × {} pixels{turned} is more than the {most} a side an export draws: give a smaller width, height or dpi", - pw.round(), - ph.round() - )); - } + // A turned view's box is larger than the view: said, as the fix differs. + fits_pixels(&view, turned)?; let name = m.name.clone(); let mut map = m.detached(); Ok(Box::new(move || { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 99dd9bdec3..27f161195d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33188,6 +33188,13 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { &s.notices[n..] ); assert!(!s.notices[n..].iter().any(|x| x.text.contains("height of"))); + // 600 DPI is 6.25 pixels a point, as the command says, not cut to 576. + let fine = dir.join("fine.tif"); + let out = s.run("share.exportMap", &json!({"path": fine.display().to_string(), "width": 100, "height": 100, "dpi": 600})).unwrap(); + assert_eq!((out["width"].as_u64(), out["height"].as_u64()), (Some(625), Some(625))); + // A PNG past the canvas's 8192 pixels a side is refused too, not cut off at its top left. + let e = s.run("share.exportMap", &json!({"path": dir.join("big.png").display().to_string(), "width": 5000, "dpi": 192})).unwrap_err(); + assert!(e.contains("10000") && e.contains("8192"), "{e}"); // Too many pixels a side is refused, saying how many. let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "width": 8000, "dpi": 192})).unwrap_err(); assert!(e.contains("16000") && e.contains("8192") && !e.contains("turned"), "{e}"); diff --git a/crates/ui-egui/src/exportjob.rs b/crates/ui-egui/src/exportjob.rs index 1970525ca7..36ae78070e 100644 --- a/crates/ui-egui/src/exportjob.rs +++ b/crates/ui-egui/src/exportjob.rs @@ -167,10 +167,13 @@ mod tests { let mut app = RustGisApp::with_sample(); app.session.view_size = (1200.0, 800.0); assert_eq!(app.export_map_dpi("small.tif"), 192.0); + assert_eq!(app.export_map_dpi("small.png"), 192.0); app.session.view_size = (5000.0, 3000.0); let n = app.session.notices.len(); - assert_eq!(app.export_map_dpi("wide.png"), 192.0); - assert_eq!(app.session.notices.len(), n); + // A PNG too: 10000 pixels wouldn't fit either. + assert_eq!(app.export_map_dpi("wide.png"), 157.0); + assert!(app.session.notices[n..].iter().any(|x| x.text.contains("drawn at 157 DPI"))); + let n = app.session.notices.len(); // 8192 × 96 / 5000 = 157.3: whole DPI, down. assert_eq!(app.export_map_dpi("wide.tif"), 157.0); assert!(app.session.notices[n..].iter().any(|x| x.text.contains("drawn at 157 DPI")), "{:?}", &app.session.notices[n..]); @@ -183,6 +186,8 @@ mod tests { assert_eq!(app.export_map_dpi("square.tif"), 192.0); app.session.map_mut().camera.bearing = 45.0; assert_eq!(app.export_map_dpi("square.TIF"), 185.0); + // A PNG of it is drawn turned in the view's own size, which fits. + assert_eq!(app.export_map_dpi("square.png"), 192.0); app.session.map_mut().camera.bearing = 0.0; app.session.view_size = (400.0, 300.0); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 94b9f7b27a..63d48fe56b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1123,9 +1123,9 @@ pub struct RustGisApp { } impl RustGisApp { - /// The DPI the ribbon's Export Map draws `path` at: 192, or for a GeoTIFF of a view too large - /// for that (one side past 8192 pixels, a turned view's box counted), the most that fits, said - /// in a notice. A PNG keeps 192. + /// The DPI the ribbon's Export Map draws `path` at: 192, or for a view too large for that (one + /// side past 8192 pixels; a GeoTIFF of a turned view counts the box around it), the most that + /// fits, said in a notice. fn export_map_dpi(&mut self, path: &str) -> f64 { const DPI: f64 = 192.0; let tif = std::path::Path::new(path) @@ -1141,16 +1141,17 @@ impl RustGisApp { let b = camera.bearing.rem_euclid(360.0); let turned = b.min(360.0 - b) > 1e-9; let (bw, bh) = if turned { camera.rotated_size(vw, vh) } else { (vw, vh) }; - let side = if turned { bw.ceil().max(bh.ceil()) } else { bw.max(bh) }; + // A PNG is drawn turned in the view's own size; a GeoTIFF north up over the box. + let side = if turned && tif { bw.ceil().max(bh.ceil()) } else { vw.max(vh) }; let most = f64::from(rustgis_engine::render::MAX_SIDE); - if !tif || !side.is_finite() || (side * DPI / 96.0).round() <= most { + if !side.is_finite() || (side * DPI / 96.0).round() <= most { return DPI; } // Whole DPI, rounded down so the side fits; the export's own limit (48) refuses smaller. let dpi = (most * 96.0 / side).floor().max(48.0); let shown = dpi.to_string(); let note = crate::i18n::fmt( - "{path}: drawn at {dpi} DPI, the most a GeoTIFF of this view holds (8192 pixels a side)", + "{path}: drawn at {dpi} DPI, the most an export of this view holds (8192 pixels a side)", &[("path", path), ("dpi", &shown)], ); self.session.notify(note, false); diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index 66ae078f1e..24fe478e4d 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -15,8 +15,9 @@ other characters as `?` and control characters as spaces, and the export says wh gives them in full as `copyright`. `"cog": true` writes a cloud-optimised GeoTIFF. A turned map is drawn north up over the box around the view (and says so). A tilted map, the globe and a map of another body are refused: export a PNG of those. One -side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`; the ribbon -draws a GeoTIFF of a view too large for 192 DPI at the most that fits, and says so. An export holds +side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`; this holds for a +PNG too, which is refused past it rather than cut off. The ribbon draws a view too large for +192 DPI at the most that fits, and says so. An export holds at most 8000 points a side, PNG or GeoTIFF: with no `width` or `height`, a larger view is cut to its middle; a `width` or `height` past 8000 is drawn at 8000, holding less ground than asked (the whole view still fits). Either way the From 7acb5bfdc4d9fd649d06a0c22ba88f3cd7e4de58 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 8 Nov 2026 04:16:02 +0100 Subject: [PATCH 08/12] fix(share): the DPI fit is the engine's ("fit"), said once the file is written; lower limits said - share.exportMap {"fit": true} lowers the dpi to the most that fits 8192 pixels a side (a GeoTIFF of a turned view counting its box), and says so with the other size notes, only when the file is written. The ribbon sends it instead of working the limits out itself. - A width or height below 16 points, and a dpi outside 48 to 600, are drawn at the limit and said. --- crates/engine/src/cmd/share.rs | 76 +++++++++++++++++++++++++++++---- crates/engine/src/tests.rs | 40 +++++++++++++++++ crates/ui-egui/src/exportjob.rs | 32 ++------------ crates/ui-egui/src/lib.rs | 42 ++---------------- docs/user-guide/sharing.md | 6 ++- 5 files changed, 119 insertions(+), 77 deletions(-) diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 347bfa4ba5..ab8e6f324d 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -26,7 +26,7 @@ pub fn commands() -> Vec { super::exports::write_here(s, p, "share.exportMap") }).inputs(map_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() - .params(r#"{"path": "*.png|*.tif|*.tiff", "width"?: "points (pixels at 96 dpi), the view fitted in it", "height"?: points, "dpi"?: 96..600, "cog"?: "true for a cloud-optimised GeoTIFF"}"#), + .params(r#"{"path": "*.png|*.tif|*.tiff", "width"?: "points (pixels at 96 dpi), the view fitted in it", "height"?: points, "dpi"?: "48..600 (default 96)", "fit"?: "true to lower the dpi until a side fits 8192 pixels, saying so", "cog"?: "true for a cloud-optimised GeoTIFF"}"#), C::new("share.exportLayer", "Export Features", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportLayer")).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_layer) @@ -212,10 +212,53 @@ fn size_notes( "a {name} of {v:.0} points is more than the {MOST_POINTS:.0} an export holds, so it is drawn at {MOST_POINTS:.0}, holding less ground than asked (the whole view still fits): a higher dpi gives more pixels" ))); } + if let Some(v) = v.filter(|v| *v < LEAST_POINTS) { + notes.push(note(format!( + "a {name} of {v} points is less than the {LEAST_POINTS:.0} an export draws, so it is drawn at {LEAST_POINTS:.0}" + ))); + } } notes } +/// The fewest points a side an export of the map draws. +const LEAST_POINTS: f64 = 16.0; +/// The DPI an export of the map draws at, at least and at most. +const DPI_RANGE: (f64, f64) = (48.0, 600.0); + +/// What the DPI range does to an export to `path` asked at `dpi`, for it to say. +fn dpi_note(path: &str, dpi: Option) -> Option<(rustgis_data::diagnostics::Severity, String)> { + let dpi = dpi.filter(|d| d.is_finite())?; + let (least, most) = DPI_RANGE; + let drawn = dpi.clamp(least, most); + (drawn != dpi).then(|| { + ( + rustgis_data::diagnostics::Severity::Info, + format!("{path}: a dpi of {dpi} is outside {least:.0} to {most:.0}, so it is drawn at {drawn:.0}"), + ) + }) +} + +/// With `fit`, the DPI an export of the view (at `dpi`) is lowered to so that no side passes the +/// [`rustgis_render::MAX_SIDE`] pixels a canvas holds, a GeoTIFF of a turned view counting the +/// box around it: the most whole DPI that fits, `None` when `dpi` already does. +fn fitted_dpi(view: &View, dpi: f64, tif: bool) -> Option { + let (w, h) = + if tif && is_turned(view.camera.bearing) { view.camera.rotated_size(view.width, view.height) } else { (view.width, view.height) }; + let side = w.max(h); + let most = f64::from(rustgis_render::MAX_SIDE); + if !side.is_finite() || side <= 0.0 || (side * view.pixels_per_point).round() <= most { + return None; + } + Some((most * 96.0 / side).floor().clamp(DPI_RANGE.0, dpi)) +} + +/// Whether a view at `bearing` is turned (not north up). +fn is_turned(bearing: f64) -> bool { + let b = bearing.rem_euclid(360.0); + b.min(360.0 - b) > 1e-9 +} + /// The view an export of the map at `camera` draws, in a view of `(vw, vh)` points: a requested /// size keeps the same ground extent, and `dpi` sets the pixels per point. fn export_view( @@ -228,10 +271,9 @@ fn export_view( // NaN would pass through `clamp`; non-finite values fall back to the defaults. let fin = |v: Option| v.filter(|x| x.is_finite()); let (width, height, dpi) = (fin(width), fin(height), fin(dpi)); - let w = width.unwrap_or(vw).clamp(16.0, MOST_POINTS); - let h = height.unwrap_or(vh).clamp(16.0, MOST_POINTS); - // 48 to 600 DPI, as the command says. - let ppp = (dpi.unwrap_or(96.0) / 96.0).clamp(0.5, 6.25); + let w = width.unwrap_or(vw).clamp(LEAST_POINTS, MOST_POINTS); + let h = height.unwrap_or(vh).clamp(LEAST_POINTS, MOST_POINTS); + let ppp = dpi.unwrap_or(96.0).clamp(DPI_RANGE.0, DPI_RANGE.1) / 96.0; let mut camera = camera; // Keep the same ground extent when the size differs from the view. if width.is_some() || height.is_some() { @@ -274,8 +316,26 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { None | Some(Value::Null) => false, Some(v) => v.as_bool().ok_or("cog must be true or false")?, }; - let sized = size_notes(&path, s.view_size, width, height); - if matches!(ext.as_str(), "tif" | "tiff") { + let tif = matches!(ext.as_str(), "tif" | "tiff"); + let fit = match p.get("fit") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or("fit must be true or false")?, + }; + let mut sized = size_notes(&path, s.view_size, width, height); + sized.extend(dpi_note(&path, dpi)); + // `fit`: a view too large for the DPI asked is drawn at the most that fits, and says so. + let asked = dpi.filter(|d| d.is_finite()).unwrap_or(96.0).clamp(DPI_RANGE.0, DPI_RANGE.1); + let dpi = match fit.then(|| fitted_dpi(&export_view(s.map().camera, s.view_size, width, height, Some(asked)), asked, tif)).flatten() { + Some(lower) => { + sized.push(( + rustgis_data::diagnostics::Severity::Info, + format!("{path}: drawn at {lower} DPI, the most an export of this view holds ({} pixels a side)", rustgis_render::MAX_SIDE), + )); + Some(lower) + } + None => dpi, + }; + if tif { return geotiff_work(s, path, export_view(s.map().camera, s.view_size, width, height, dpi), cog, sized); } if cog { @@ -320,7 +380,7 @@ fn geotiff_work( let mut view = view; let mut notices = Vec::new(); let bearing = view.camera.bearing; - let turned = bearing.rem_euclid(360.0).min(360.0 - bearing.rem_euclid(360.0)) > 1e-9; + let turned = is_turned(bearing); if turned { // North up over the box around the turned view: everything it shows, and more at the // corners. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 27f161195d..c8f217b783 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33188,6 +33188,46 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { &s.notices[n..] ); assert!(!s.notices[n..].iter().any(|x| x.text.contains("height of"))); + // `fit` lowers the DPI to what fits 8192 pixels a side, and says so; one that fits stays. + let fitted = |s: &mut Session, file: &str| { + let n = s.notices.len(); + let out = s.run("share.exportMap", &json!({"path": dir.join(file).display().to_string(), "dpi": 192, "fit": true})).unwrap(); + let said = + s.notices[n..].iter().find_map(|x| x.text.split("drawn at ").nth(1).and_then(|t| t.split(' ').next()).map(str::to_string)); + (out, said) + }; + s.view_size = (1200.0, 800.0); + assert_eq!(fitted(&mut s, "small.tif").1, None); + assert_eq!(fitted(&mut s, "small.png").1, None); + s.view_size = (5000.0, 3000.0); + // 8192 × 96 / 5000 = 157.3: whole DPI, down. + let (out, said) = fitted(&mut s, "wide.tif"); + assert_eq!((said.as_deref(), out["width"].as_u64()), (Some("157"), Some(8177))); + assert_eq!(fitted(&mut s, "wide.png").1.as_deref(), Some("157")); + // Past 8000 points the view is clamped first: 16000 wide fits 98 DPI. + s.view_size = (16000.0, 3000.0); + assert_eq!(fitted(&mut s, "huge.tif").1.as_deref(), Some("98")); + // A GeoTIFF of a turned view counts its box (3000 points square turned 45° is 4243); a PNG + // is drawn turned in the view's own size. + s.view_size = (3000.0, 3000.0); + assert_eq!(fitted(&mut s, "square.tif").1, None); + s.run("map.setBearing", &json!({"bearing": 45})).unwrap(); + assert_eq!(fitted(&mut s, "square-turned.tif").1.as_deref(), Some("185")); + assert_eq!(fitted(&mut s, "square-turned.png").1, None); + s.run("map.setBearing", &json!({"bearing": 0})).unwrap(); + s.view_size = (400.0, 300.0); + let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "fit": "yes"})).unwrap_err(); + assert!(e.contains("fit must be true or false"), "{e}"); + // A size below 16 points, and a dpi outside 48 to 600, are drawn at the limit, and say so. + let n = s.notices.len(); + let out = s + .run("share.exportMap", &json!({"path": dir.join("tiny.tif").display().to_string(), "width": 5, "height": 100, "dpi": 30})) + .unwrap(); + assert_eq!(out["width"], 8); + let said: Vec<&str> = s.notices[n..].iter().map(|x| x.text.as_str()).collect(); + assert!(said.iter().any(|t| t.contains("a width of 5 points is less than the 16")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("a dpi of 30 is outside 48 to 600, so it is drawn at 48")), "{said:?}"); + assert!(!said.iter().any(|t| t.contains("height of")), "{said:?}"); // 600 DPI is 6.25 pixels a point, as the command says, not cut to 576. let fine = dir.join("fine.tif"); let out = s.run("share.exportMap", &json!({"path": fine.display().to_string(), "width": 100, "height": 100, "dpi": 600})).unwrap(); diff --git a/crates/ui-egui/src/exportjob.rs b/crates/ui-egui/src/exportjob.rs index 36ae78070e..fdf13b81c9 100644 --- a/crates/ui-egui/src/exportjob.rs +++ b/crates/ui-egui/src/exportjob.rs @@ -159,37 +159,11 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - /// The ribbon's Export Map to a `.tif` draws at 192 DPI where that fits a GeoTIFF's 8192 - /// pixels a side, and at the most that fits (said) where it doesn't; a PNG keeps 192. The - /// GeoTIFF is written on a thread like the PNG. + /// The ribbon's Export Map to a `.tif` writes a GeoTIFF on a thread like the PNG, at 192 DPI + /// where that fits (the engine's `fit`). #[test] - fn export_map_to_a_geotiff_fits_its_dpi_to_the_view() { + fn export_map_to_a_geotiff_runs_on_a_thread() { let mut app = RustGisApp::with_sample(); - app.session.view_size = (1200.0, 800.0); - assert_eq!(app.export_map_dpi("small.tif"), 192.0); - assert_eq!(app.export_map_dpi("small.png"), 192.0); - app.session.view_size = (5000.0, 3000.0); - let n = app.session.notices.len(); - // A PNG too: 10000 pixels wouldn't fit either. - assert_eq!(app.export_map_dpi("wide.png"), 157.0); - assert!(app.session.notices[n..].iter().any(|x| x.text.contains("drawn at 157 DPI"))); - let n = app.session.notices.len(); - // 8192 × 96 / 5000 = 157.3: whole DPI, down. - assert_eq!(app.export_map_dpi("wide.tif"), 157.0); - assert!(app.session.notices[n..].iter().any(|x| x.text.contains("drawn at 157 DPI")), "{:?}", &app.session.notices[n..]); - // A view past 8000 points is clamped as the export clamps it: 16000 wide fits 98 DPI. - app.session.view_size = (16000.0, 3000.0); - assert_eq!(app.export_map_dpi("huge.tif"), 98.0); - // A turned view counts its box: 3000 points square fits at 192 DPI (6000 pixels), turned - // 45° its box is 4243 points (8486 pixels), which doesn't. - app.session.view_size = (3000.0, 3000.0); - assert_eq!(app.export_map_dpi("square.tif"), 192.0); - app.session.map_mut().camera.bearing = 45.0; - assert_eq!(app.export_map_dpi("square.TIF"), 185.0); - // A PNG of it is drawn turned in the view's own size, which fits. - assert_eq!(app.export_map_dpi("square.png"), 192.0); - app.session.map_mut().camera.bearing = 0.0; - app.session.view_size = (400.0, 300.0); let dir = std::env::temp_dir().join(format!("rustgis-export-tif-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 63d48fe56b..d69d88261f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1123,41 +1123,6 @@ pub struct RustGisApp { } impl RustGisApp { - /// The DPI the ribbon's Export Map draws `path` at: 192, or for a view too large for that (one - /// side past 8192 pixels; a GeoTIFF of a turned view counts the box around it), the most that - /// fits, said in a notice. - fn export_map_dpi(&mut self, path: &str) -> f64 { - const DPI: f64 = 192.0; - let tif = std::path::Path::new(path) - .extension() - .and_then(|e| e.to_str()) - .is_some_and(|e| e.eq_ignore_ascii_case("tif") || e.eq_ignore_ascii_case("tiff")); - // As the export clamps it. - let most_points = rustgis_engine::cmd::share::MOST_POINTS; - let (vw, vh) = (self.session.view_size.0.clamp(16.0, most_points), self.session.view_size.1.clamp(16.0, most_points)); - let camera = self.session.map().camera; - // As the export works it out: a turned view's box, rounded up to whole points; the pixels - // rounded. - let b = camera.bearing.rem_euclid(360.0); - let turned = b.min(360.0 - b) > 1e-9; - let (bw, bh) = if turned { camera.rotated_size(vw, vh) } else { (vw, vh) }; - // A PNG is drawn turned in the view's own size; a GeoTIFF north up over the box. - let side = if turned && tif { bw.ceil().max(bh.ceil()) } else { vw.max(vh) }; - let most = f64::from(rustgis_engine::render::MAX_SIDE); - if !side.is_finite() || (side * DPI / 96.0).round() <= most { - return DPI; - } - // Whole DPI, rounded down so the side fits; the export's own limit (48) refuses smaller. - let dpi = (most * 96.0 / side).floor().max(48.0); - let shown = dpi.to_string(); - let note = crate::i18n::fmt( - "{path}: drawn at {dpi} DPI, the most an export of this view holds (8192 pixels a side)", - &[("path", path), ("dpi", &shown)], - ); - self.session.notify(note, false); - dpi - } - /// The layer to export: `layer` (an id or name, as commands take it; the dialog's is checked /// against its `instance`, so a reused id isn't taken for it), else the active layer. fn export_target(&self, p: &Value) -> Result { @@ -3996,17 +3961,18 @@ impl RustGisApp { let name = format!("{}.png", self.session.map().name); // A .tif is the view placed on the ground (a GeoTIFF), without the scale bar. if let Some(path) = dialogs::pick_save(&name, &["png", "tif", "tiff"], tl!("PNG image or GeoTIFF")) { - let dpi = self.export_map_dpi(&path); + // 192 DPI, or the most a view too large for it holds (the export says so). + let args = json!({"path": path, "dpi": 192, "fit": true}); // Drawn on a thread of its own, with progress and Cancel in the status bar; // here while a style added with its own view loads, as the command waits for // it to move the map there first. #[cfg(not(target_arch = "wasm32"))] if self.session.style_view.is_none() { - return exportjob::start(self, "share.exportMap", json!({"path": path, "dpi": dpi})); + return exportjob::start(self, "share.exportMap", args); } #[cfg(not(target_arch = "wasm32"))] exportjob::idle(self)?; - return self.run("share.exportMap", json!({"path": path, "dpi": dpi})); + return self.run("share.exportMap", args); } } "ui.exportLayer" => { diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index 24fe478e4d..f54d6dc4b7 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -16,8 +16,10 @@ gives them in full as `copyright`. `"cog": true` writes a cloud-optimised GeoTIFF. A turned map is drawn north up over the box around the view (and says so). A tilted map, the globe and a map of another body are refused: export a PNG of those. One side holds at most 8192 pixels, so a large `width` or `height` needs a lower `dpi`; this holds for a -PNG too, which is refused past it rather than cut off. The ribbon draws a view too large for -192 DPI at the most that fits, and says so. An export holds +PNG too, which is refused past it rather than cut off. With `"fit": true` an export too large for +its `dpi` is drawn at the most that fits, and says so; the ribbon exports that way, at 192 DPI. +`dpi` runs from 48 to 600 and a side from 16 points; a value outside is drawn at the limit, and +said. An export holds at most 8000 points a side, PNG or GeoTIFF: with no `width` or `height`, a larger view is cut to its middle; a `width` or `height` past 8000 is drawn at 8000, holding less ground than asked (the whole view still fits). Either way the From 9ced23e76e2db7513e93ad4ff050ae59353e6b11 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 8 Nov 2026 05:18:04 +0100 Subject: [PATCH 09/12] fix(share): fit rounds a turned GeoTIFF's box out, as its canvas is; the app's download and clipboard copy fit too - fitted_dpi checks a turned GeoTIFF's box rounded up, so a box just past 8192 pixels gets a lower DPI instead of being refused. - map_png_fitted: the web app's Export Map download and Capture To Clipboard draw a view too large for 192 DPI at the most that fits, and say so, instead of being refused. --- crates/engine/src/cmd/share.rs | 21 ++++++++++++++++++++- crates/engine/src/tests.rs | 16 ++++++++++++++++ crates/ui-egui/src/lib.rs | 14 ++++++-------- 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index ab8e6f324d..4fb06cd4b7 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -148,6 +148,22 @@ fn report_table(s: &mut Session, path: &str, gpkg: &GpkgTable, table: Option Result, String> { + let view = export_view(s.map().camera, s.view_size, None, None, Some(dpi)); + let fitted = fitted_dpi(&view, dpi, false); + let png = map_png(s, None, None, Some(fitted.unwrap_or(dpi)))?; + if let Some(lower) = fitted { + s.notify( + format!("The map is drawn at {lower} DPI, the most an image of this view holds ({} pixels a side)", rustgis_render::MAX_SIDE), + false, + ); + } + Ok(png) +} + /// Renders the active map at the current view (or a requested size) to PNG bytes. pub fn map_png(s: &mut Session, width: Option, height: Option, dpi: Option) -> Result, String> { let view_size = s.view_size; @@ -247,7 +263,10 @@ fn fitted_dpi(view: &View, dpi: f64, tif: bool) -> Option { if tif && is_turned(view.camera.bearing) { view.camera.rotated_size(view.width, view.height) } else { (view.width, view.height) }; let side = w.max(h); let most = f64::from(rustgis_render::MAX_SIDE); - if !side.is_finite() || side <= 0.0 || (side * view.pixels_per_point).round() <= most { + // As the export sizes its canvas: a turned GeoTIFF's box rounded out, else rounded. + let px = side * view.pixels_per_point; + let px = if tif && is_turned(view.camera.bearing) { px.ceil() } else { px.round() }; + if !side.is_finite() || side <= 0.0 || px <= most { return None; } Some((most * 96.0 / side).floor().clamp(DPI_RANGE.0, dpi)) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c8f217b783..3b6c3dc208 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33214,8 +33214,24 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { s.run("map.setBearing", &json!({"bearing": 45})).unwrap(); assert_eq!(fitted(&mut s, "square-turned.tif").1.as_deref(), Some("185")); assert_eq!(fitted(&mut s, "square-turned.png").1, None); + // A box just past 8192 pixels (8192.2) is rounded out, as the GeoTIFF's canvas is: lowered to + // 95 DPI, and written. + s.view_size = (5792.76, 5792.76); + let n = s.notices.len(); + let out = s.run("share.exportMap", &json!({"path": dir.join("edge.tif").display().to_string(), "dpi": 96, "fit": true})).unwrap(); + assert!(s.notices[n..].iter().any(|x| x.text.contains("drawn at 95 DPI")), "{out}"); s.run("map.setBearing", &json!({"bearing": 0})).unwrap(); + // The app's download and clipboard copy (no size given) fit too: 5000 points at 192 DPI is + // drawn at 157, and said. + s.view_size = (5000.0, 3000.0); + let n = s.notices.len(); + let png = crate::cmd::share::map_png_fitted(&mut s, 192.0).unwrap(); + assert_eq!(rustgis_render::decode_png(&png).map(|p| p.width()), Some(8177)); + assert!(s.notices[n..].iter().any(|x| x.text.contains("drawn at 157 DPI"))); + let n = s.notices.len(); s.view_size = (400.0, 300.0); + crate::cmd::share::map_png_fitted(&mut s, 192.0).unwrap(); + assert!(!s.notices[n..].iter().any(|x| x.text.contains("DPI"))); let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "fit": "yes"})).unwrap_err(); assert!(e.contains("fit must be true or false"), "{e}"); // A size below 16 points, and a dpi outside 48 to 600, are drawn at the limit, and say so. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d69d88261f..aba70cf030 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3543,10 +3543,9 @@ impl RustGisApp { } "ui.captureMap" => { let session = &mut self.session; - let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::share::map_png(session, None, None, Some(192.0)) - })) - .unwrap_or_else(|_| Err("the capture failed unexpectedly".into()))?; + let png = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_png_fitted(session, 192.0))) + .unwrap_or_else(|_| Err("the capture failed unexpectedly".into()))?; let pm = rustgis_engine::render::decode_png(&png).ok_or("could not draw the map")?; let size = [pm.width() as usize, pm.height() as usize]; self.ui.copy_image = Some(egui::ColorImage::from_rgba_premultiplied(size, pm.data())); @@ -3871,10 +3870,9 @@ impl RustGisApp { "ui.exportMap" if self.services.download.is_some() => { // The same last-resort panic guard `Session::run` gives commands. let session = &mut self.session; - let png = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::share::map_png(session, None, None, Some(192.0)) - })) - .unwrap_or_else(|_| Err("Export Map failed unexpectedly".into())); + let png = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_png_fitted(session, 192.0))) + .unwrap_or_else(|_| Err("Export Map failed unexpectedly".into())); let png = match png { Ok(p) => p, Err(e) => { From 486992e1e57122da889c449f069a110f1deb19f3 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 8 Nov 2026 06:39:31 +0100 Subject: [PATCH 10/12] fix(share): the app's download and clipboard copy say a view cut to 8000 points; a COG export gives its tiling - map_png_fitted says when a view past 8000 points is cut to its middle, as Export Map does. - A GeoTIFF export with cog gives its overviews and BigTIFF in the answer, as Export Raster does; the test checks it. - The guide no longer names Robinson as refused: GeoTIFF keys hold it now. --- crates/engine/src/cmd/share.rs | 16 ++++++++++++---- crates/engine/src/tests.rs | 10 +++++++++- docs/user-guide/sharing.md | 2 +- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 4fb06cd4b7..1c9f3c926c 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -155,6 +155,10 @@ pub fn map_png_fitted(s: &mut Session, dpi: f64) -> Result, String> { let view = export_view(s.map().camera, s.view_size, None, None, Some(dpi)); let fitted = fitted_dpi(&view, dpi, false); let png = map_png(s, None, None, Some(fitted.unwrap_or(dpi)))?; + // A view past 8000 points is cut to its middle, as Export Map's is: said too. + for (_, note) in size_notes("The map image", s.view_size, None, None) { + s.notify(note, false); + } if let Some(lower) = fitted { s.notify( format!("The map is drawn at {lower} DPI, the most an image of this view holds ({} pixels a side)", rustgis_render::MAX_SIDE), @@ -432,16 +436,20 @@ fn geotiff_work( let mut r = placed_raster(&name, placed.pixmap, &view, crs)?; r.copyright = (!credits.is_empty()).then(|| credits.join(" | ")); rustgis_data::progress::check().map_err(|e| e.to_string())?; - let bytes = if cog { - // Tiles go to the file as they are made. + let (bytes, tiled) = if cog { + // Tiles go to the file as they are made; its tiling is in the answer, as Export + // Raster gives it. let c = rustgis_data::raster::cogwrite::write_file(&r, 0, Path::new(&path)).map_err(|e| format!("{path}: {e}"))?; - c.bytes + (c.bytes, Some(json!({"overviews": c.levels.len().saturating_sub(1), "bigTiff": c.big}))) } else { let bytes = rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| format!("{path}: {e}"))?; rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; - bytes.len() as u64 + (bytes.len() as u64, None) }; let mut out = json!({"path": path, "width": r.width, "height": r.height, "crs": crs.label(), "bytes": bytes}); + if let Some(t) = tiled { + out["cog"] = t; + } if let Some(c) = &r.copyright { out["copyright"] = json!(c); if let Some(note) = rustgis_data::raster::tag_text_note(c) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3b6c3dc208..3289d424e1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33150,6 +33150,8 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { let cog = dir.join("view-cog.tif"); let out = s.run("share.exportMap", &json!({"path": cog.display().to_string(), "width": 400, "height": 300, "cog": true})).unwrap(); assert!(out["bytes"].as_u64().unwrap() > 0); + // Written by the tiled writer: its tiling is in the answer, as Export Raster gives it. + assert!(out["cog"]["overviews"].is_u64(), "{out}"); assert_eq!(read(&cog).width, 400); let png = dir.join("view.png"); let e = s.run("share.exportMap", &json!({"path": png.display().to_string(), "cog": true})).unwrap_err(); @@ -33231,7 +33233,13 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { let n = s.notices.len(); s.view_size = (400.0, 300.0); crate::cmd::share::map_png_fitted(&mut s, 192.0).unwrap(); - assert!(!s.notices[n..].iter().any(|x| x.text.contains("DPI"))); + assert!(!s.notices[n..].iter().any(|x| x.text.contains("DPI") || x.text.contains("cut"))); + // A view past 8000 points is cut to its middle, and said. + s.view_size = (9000.0, 300.0); + let n = s.notices.len(); + crate::cmd::share::map_png_fitted(&mut s, 96.0).unwrap(); + assert!(s.notices[n..].iter().any(|x| x.text.contains("cut to its middle")), "{:?}", &s.notices[n..]); + s.view_size = (400.0, 300.0); let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "fit": "yes"})).unwrap_err(); assert!(e.contains("fit must be true or false"), "{e}"); // A size below 16 points, and a dpi outside 48 to 600, are drawn at the limit, and say so. diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index f54d6dc4b7..1d4b3c3e5b 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -27,7 +27,7 @@ export says so. In a GeoTIFF, tiles still on their way when the export stops waiting, streamed layers still reading the view, and tile layers that can't be drawn leave gaps that would pass for data, so its export warns about them. The web app's Export Map downloads a PNG. A projection -whose parameters GeoTIFF's keys can't hold (Mollweide or Robinson, for example) is refused too: +whose parameters GeoTIFF's keys can't hold (Mollweide, for example) is refused too: switch the map to an EPSG projection first. **Print Map** opens a PDF of the map view, kept as From 7f9b471550d794c0cc5b214fb91e2ed4bb94e8a9 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 8 Nov 2026 07:38:34 +0100 Subject: [PATCH 11/12] fix(share): the fit keeps its bounds in order; the image's cut notice names Export Map for a size MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - fitted_dpi's upper bound is at least 48, so clamp can't panic for a caller asking below it. - map_png_fitted's notice names share.exportMap as where a width or height can be given; the test checks the cut image is 8000 × 300. - The COG test checks bigTiff. --- crates/engine/src/cmd/share.rs | 17 +++++++++++++---- crates/engine/src/tests.rs | 14 +++++++++++--- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 1c9f3c926c..85be749aa3 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -155,9 +155,16 @@ pub fn map_png_fitted(s: &mut Session, dpi: f64) -> Result, String> { let view = export_view(s.map().camera, s.view_size, None, None, Some(dpi)); let fitted = fitted_dpi(&view, dpi, false); let png = map_png(s, None, None, Some(fitted.unwrap_or(dpi)))?; - // A view past 8000 points is cut to its middle, as Export Map's is: said too. - for (_, note) in size_notes("The map image", s.view_size, None, None) { - s.notify(note, false); + // A view past 8000 points is cut to its middle, as Export Map's is: said too, with where a + // size can be given (this image takes none). + let (vw, vh) = s.view_size; + if vw > MOST_POINTS || vh > MOST_POINTS { + s.notify( + format!( + "The map image: the view is {vw:.0} × {vh:.0} points, more than the {MOST_POINTS:.0} a side an image holds, so it is cut to its middle: Export Map (share.exportMap) with a width or height of at most {MOST_POINTS:.0} draws it whole" + ), + false, + ); } if let Some(lower) = fitted { s.notify( @@ -273,7 +280,9 @@ fn fitted_dpi(view: &View, dpi: f64, tif: bool) -> Option { if !side.is_finite() || side <= 0.0 || px <= most { return None; } - Some((most * 96.0 / side).floor().clamp(DPI_RANGE.0, dpi)) + // Never above the DPI asked, nor below the least: `max` keeps the bounds in order (clamp + // panics otherwise) for a caller asking below it. + Some((most * 96.0 / side).floor().clamp(DPI_RANGE.0, dpi.max(DPI_RANGE.0))) } /// Whether a view at `bearing` is turned (not north up). diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3289d424e1..318f518c0f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33151,7 +33151,7 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { let out = s.run("share.exportMap", &json!({"path": cog.display().to_string(), "width": 400, "height": 300, "cog": true})).unwrap(); assert!(out["bytes"].as_u64().unwrap() > 0); // Written by the tiled writer: its tiling is in the answer, as Export Raster gives it. - assert!(out["cog"]["overviews"].is_u64(), "{out}"); + assert!(out["cog"]["overviews"].is_u64() && out["cog"]["bigTiff"] == false, "{out}"); assert_eq!(read(&cog).width, 400); let png = dir.join("view.png"); let e = s.run("share.exportMap", &json!({"path": png.display().to_string(), "cog": true})).unwrap_err(); @@ -33237,8 +33237,16 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { // A view past 8000 points is cut to its middle, and said. s.view_size = (9000.0, 300.0); let n = s.notices.len(); - crate::cmd::share::map_png_fitted(&mut s, 96.0).unwrap(); - assert!(s.notices[n..].iter().any(|x| x.text.contains("cut to its middle")), "{:?}", &s.notices[n..]); + let png = crate::cmd::share::map_png_fitted(&mut s, 96.0).unwrap(); + assert_eq!(rustgis_render::decode_png(&png).map(|p| (p.width(), p.height())), Some((8000, 300))); + assert!( + s.notices[n..].iter().any(|x| x.text.contains("cut to its middle") && x.text.contains("share.exportMap")), + "{:?}", + &s.notices[n..] + ); + // A DPI below the least is drawn at 48 (export_view clamps it before the fit looks at it). + s.view_size = (6000.0, 300.0); + crate::cmd::share::map_png_fitted(&mut s, 30.0).unwrap(); s.view_size = (400.0, 300.0); let e = s.run("share.exportMap", &json!({"path": path.display().to_string(), "fit": "yes"})).unwrap_err(); assert!(e.contains("fit must be true or false"), "{e}"); From d530ef5b62b26beb814e9f92f841cf16d5824a8d Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 8 Nov 2026 08:29:37 +0100 Subject: [PATCH 12/12] test(share): the fitted GeoTIFF's pixels are square and its centre is the camera's down the middle too --- crates/engine/src/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 318f518c0f..cd31710330 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -33179,6 +33179,9 @@ fn export_map_to_geotiff_places_the_view_on_the_ground() { assert_eq!((fit.width, fit.height), (4000, 300)); assert!((fit.transform.pixel_width - 2.25 * cam.res).abs() < 1e-6 * cam.res, "{:?}", fit.transform); assert!((fit.transform.origin_x + 2000.0 * fit.transform.pixel_width - cam.center.x).abs() < 1e-3); + // Square pixels, and the centre down the middle too. + assert!((fit.transform.pixel_height + fit.transform.pixel_width).abs() < 1e-9 * cam.res, "{:?}", fit.transform); + assert!((fit.transform.origin_y + 150.0 * fit.transform.pixel_height - cam.center.y).abs() < 1e-3); s.view_size = (400.0, 300.0); // A size given past the limit is drawn at the limit, and says so. let n = s.notices.len();