diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 4a8d098e26..8467669a03 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -464,9 +464,11 @@ pub struct Service { /// Most layers or collections `service.layers` lists from one document. An OGC API collection /// can make up to three layers (features, map tiles, vector tiles), so its listing can pass this -/// many layers. The others are still read ([`Service::listed`]), so that they can be added by -/// name: which ones come first is up to the server, and some change their order between answers -/// (#1519). +/// many layers. In an OGC document the others are still read ([`Service::listed`]), so that they +/// can be added by name: which ones come first is up to the server, and some change their order +/// between answers (#1519). Reading stops at [`MAX_READ_LAYERS`], or sooner when the layers' +/// request addresses are long ([`read_limit`], [`MAX_COPIED_ADDRESS_BYTES`]); past that none is +/// read. An ArcGIS list is read only as far as it is listed. const MAX_LISTED_LAYERS: usize = 2_000; /// Most layers or collections read from one document, which is hostile input. const MAX_READ_LAYERS: usize = if cfg!(test) { 3_000 } else { 100_000 }; diff --git a/crates/engine/src/cmd/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index 1114f4f2e8..ee6ce21fd0 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -148,13 +148,15 @@ fn add(s: &mut Session, p: &Value) -> CmdResult { }); // Its header read first, so its bands are known; the layer is framed only when it is the // map's first content (no "zoom" is passed, so add_cog defaults it to that). In the - // browser nothing may wait, and it is read as the map draws. + // browser nothing may wait, nor may a plugin's command in the app (it runs on the + // frame): it is read as the map draws. + let probe = cfg!(not(target_arch = "wasm32")) && !s.leave_downloads; #[cfg(not(target_arch = "wasm32"))] - if !crate::render::rustgis_tiles::cog::probe_blocking(file)? { + if probe && !crate::render::rustgis_tiles::cog::probe_blocking(file)? { return Err(format!("{file}: not a cloud-optimised GeoTIFF")); } let look = crate::render::rustgis_tiles::cog::with_look(file, &look); - super::layer::add_cog(s, &json!({"name": name}), &look, cfg!(not(target_arch = "wasm32"))) + super::layer::add_cog(s, &json!({"name": name}), &look, probe) } "earth-index" => add_points(s, p, name), _ => add_tessera(s, p, d, name), @@ -313,6 +315,26 @@ mod tests { assert_eq!(band_label([1, 16, 9]), "2, 17, 10"); } + /// A plugin's command in the app (`leave_downloads`) doesn't read an AlphaEarth tile's header + /// on the frame: the layer is added and read as the map draws. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn alphaearth_added_without_waiting_when_downloads_are_left() { + let url = "https://127.0.0.1:9/annual/2024/10N/x.tiff"; + let mut s = Session::new(Project::default()); + s.leave_downloads = true; + let r = s.run("embeddings.add", &json!({"dataset": "alphaearth", "url": url})); + assert!(r.is_ok(), "{r:?}"); + // The tile is added with its AlphaEarth look. + let tile = s.map().tiles.last().map(|t| t.url.clone()).unwrap_or_default(); + let (file, look) = crate::render::rustgis_tiles::cog::split(&tile); + assert_eq!(file, url); + assert!(look.aef, "{tile}"); + // Elsewhere its header is read first, so an unreadable tile is refused. + let mut t = Session::new(Project::default()); + assert!(t.run("embeddings.add", &json!({"dataset": "alphaearth", "url": url})).is_err()); + } + #[test] fn points_coloured_by_their_components() { let mut s = Session::new(Project::default()); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 03d0580c60..0ef6ef7767 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -45,7 +45,7 @@ pub fn commands() -> Vec { r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, ), C::new("raster.rasterize", "Polygons to Raster", "Analyze › Alignment", rasterize).inputs(rasterize_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the polygons' bounds), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, + r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, ), // A fit is a measurement of the points, not a project change: no undo step. C::new("raster.gcpFit", "Control Point Fit", "Analyze › Alignment", gcp_fit).roles(&[]).effects(crate::policy::Effects::NONE).view().params( diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index d02c142706..7bd3eb2747 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -422,7 +422,7 @@ fn embedded_map(m: &Map, budget: &mut u64) -> Map { /// Adds maps from a map file, project or package. fn import_maps(s: &mut Session, p: &Value) -> CmdResult { let text = read_text(p)?; - crate::project::check_format(&text, "map file or project")?; + crate::project::check_format(&text, "map file, project or package")?; let dir = ps(p, "path").and_then(|path| std::path::absolute(path).ok()).and_then(|p| p.parent().map(Path::to_path_buf)); super::connections::clear_active(); let maps: Vec = match serde_json::from_str::(&text) { @@ -451,7 +451,7 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult { } Err(error) => { super::connections::restore_active(s); - return Err(error); + return Err(not_a(error, "map file, project or package")); } }, }; @@ -487,6 +487,16 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"maps": names})) } +/// A project read's refusal for an import that also takes `kinds`: text that is none of them is +/// said to be none of them, not only a failed project. Other refusals (such as "Update RustGIS") +/// are kept as they are. +fn not_a(error: String, kinds: &str) -> String { + match error.strip_prefix("not a RustGIS project: ") { + Some(why) => format!("not a RustGIS {kinds}: {why}"), + None => error, + } +} + fn add_style(s: &mut Session, mut item: StyleItem) { item.name = item.name.trim().chars().take(200).collect(); if item.name.is_empty() { @@ -515,7 +525,7 @@ fn import_styles(s: &mut Session, p: &Value) -> CmdResult { super::connections::clear_active(); let project = Project::from_import_json(&text, None); super::connections::restore_active(s); - let mut project = project?; + let mut project = project.map_err(|e| not_a(e, "layer file, map file or project"))?; for notice in std::mem::take(&mut project.label_read_notices) { s.notify(notice, false); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 939c624031..32ff9fbf3f 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -1763,7 +1763,8 @@ fn ground_overlays(s: &mut Session, file_name: &str, bytes: &[u8]) -> Vec<(Strin let dir = Path::new(file_name).parent().filter(|d| d.is_absolute()); for (g, picture) in found { let href = g.href.trim(); - let picture = picture.or_else(|| { + // `Err(None)`: not in the file or beside it; `Err(Some(why))`: beside it but unreadable. + let picture = picture.ok_or(None::).or_else(|_| { // Beside the document: no web addresses, absolute paths or climbing out of its folder. let rel = Path::new(href); let safe = !href.contains("://") @@ -1772,14 +1773,29 @@ fn ground_overlays(s: &mut Session, file_name: &str, bytes: &[u8]) -> Vec<(Strin // Windows too (`C:x`, `\\x`). && rel.components().all(|c| matches!(c, std::path::Component::Normal(_) | std::path::Component::CurDir)); if !safe { - return None; + return Err(None); } - let p = dir?.join(rel); - crate::project::read_file(&p, (256 << 20) - 1).ok() + let p = dir.ok_or(None)?.join(rel); + // Only a missing picture isn't beside it; one that can't be looked at says why. + // (Followed as the read follows it: a link to nothing is missing too.) + match std::fs::metadata(&p) { + Ok(_) => {} + // (A file named as a folder on its way, `a.png/b.png`, isn't beside it either.) + Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory) => return Err(None), + Err(e) => return Err(Some(e.to_string())), + } + crate::project::read_file(&p, (256 << 20) - 1).map_err(Some) }); - let Some(picture) = picture else { - notes.push(format!("{} (its picture {href} isn't in the file or beside it)", g.name)); - continue; + let picture = match picture { + Ok(p) => p, + Err(None) => { + notes.push(format!("{} (its picture {href} isn't in the file or beside it)", g.name)); + continue; + } + Err(Some(why)) => { + notes.push(format!("{} (its picture {href} can't be read: {why})", g.name)); + continue; + } }; match rustgis_data::raster::from_image(&g.name, &picture, g.bbox, g.rotation) { Ok(r) => out.push((g.name.clone(), r)), diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index f7fc9b8796..6b449aea70 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -3479,11 +3479,9 @@ fn series_page(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"page": page, "pages": n, "name": name})) } -/// Renders a layout to PNG or PDF bytes. `all` renders every map series page (PDF only). /// What an export of a layout whose texts name installed families is told while the app is still /// indexing the fonts (its first seconds; the app's exports don't wait for them): those texts -/// are drawn in their fallbacks. A script or the command line indexes them at -/// once. +/// are drawn in their fallbacks. A script or the command line indexes them at once. fn named_fonts_unread(layout: &Layout) -> Option<&'static str> { let named = layout.elements.iter().any(|e| matches!(&e.kind, ElementKind::Text { font_name: Some(_), .. })); (named && rustgis_render::families::available().is_none()).then_some( diff --git a/crates/engine/src/cmd/search.rs b/crates/engine/src/cmd/search.rs index cf838e4181..952f66737d 100644 --- a/crates/engine/src/cmd/search.rs +++ b/crates/engine/src/cmd/search.rs @@ -398,15 +398,17 @@ fn search_cmd(s: &mut Session, p: &Value) -> CmdResult { /// A place typed as an MGRS reference (the centre of the square it names) or a UTM position, in /// the forms [`rustgis_geom::parse_mgrs`] and [`rustgis_geom::parse_utm`] accept; `None` for /// anything else, an ambiguous UTM zone letter or a reference that names no place. +#[cfg(test)] pub fn parse_grid_reference(text: &str) -> Option { read_grid_reference(text).ok() } -/// As [`parse_grid_reference`], with why a reference was refused: [`GridError::Syntax`] for text -/// written as neither form, otherwise the reason of the form it was written in. A 100 km square -/// alone written with spaces (`5 Ave`, `4K TV`) is a number and a word as often as a reference, -/// so one that names no square is [`GridError::Syntax`] too; written as one word (`38TMJ`), it -/// says why. +/// A place typed as an MGRS reference (the centre of the square it names) or a UTM position, in +/// the forms [`rustgis_geom::parse_mgrs`] and [`rustgis_geom::parse_utm`] accept, or why it was +/// refused: [`GridError::Syntax`] for text written as neither form, otherwise the reason of the +/// form it was written in. A 100 km square alone written with spaces (`5 Ave`, `4K TV`) is a +/// number and a word as often as a reference, so one that names no square is +/// [`GridError::Syntax`] too; written as one word (`38TMJ`), it says why. pub fn read_grid_reference(text: &str) -> Result { match rustgis_geom::parse_mgrs(text) { Ok(m) => m.centre(), diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 460a8d11d5..f17cc3092e 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -412,6 +412,9 @@ fn checked_template(service: &str, t: &str) -> Result { struct AdvertisedTemplate { template: Option, crossed_origin: bool, + /// Why the standard tile address is used instead, when a template was looked for and not + /// found: the notice to give. + fallback: Option, } /// Compares canonical origins without treating a runtime login wrapper as part of the origin. @@ -437,20 +440,41 @@ fn advertised_template_with( mut read: impl FnMut(&str) -> Result, String>, ) -> AdvertisedTemplate { use rustgis_data::ogc::{TilesStep, resolve_tiles}; - let mut out = AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list) }; + let mut out = AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None }; let mut doc = list.to_string(); + // Each fallback is said, as [`left_template`] says it. for _ in 0..2 { - if crate::render::rustgis_tiles::address::check(&doc, Some(list)).is_err() { - break; + let shown = crate::sources::redact(&doc); + if let Err(e) = crate::render::rustgis_tiles::address::check(&doc, Some(list)) { + let e = crate::sources::redact_text(&e); + out.fallback = Some(format!("{shown}: this tile set document was refused, so the standard tile address is used: {e}")); + return out; } - let Ok(body) = read(&doc) else { break }; - let Some(resolved) = resolve_tiles(list, &doc, &body, vector) else { break }; + let body = match read(&doc) { + Ok(body) => body, + Err(e) => { + let e = crate::sources::redact_text(&e); + out.fallback = Some(format!("{shown}: its tile sets couldn't be read, so the standard tile address is used: {e}")); + return out; + } + }; + let Some(resolved) = resolve_tiles(list, &doc, &body, vector) else { + out.fallback = Some(format!("{shown}: it names no tiles of this layer, so the standard tile address is used")); + return out; + }; *withheld = withheld.saturating_add(resolved.withheld_addresses); match resolved.step { TilesStep::Template(t) => { out.crossed_origin |= crosses_origin(&doc, &t); - out.template = checked_template(list, &t).ok(); - break; + match checked_template(list, &t) { + Ok(t) => out.template = Some(t), + // (Its error names the template, which may carry keys.) + Err(e) => { + let e = crate::sources::redact_text(&e); + out.fallback = Some(format!("{shown}: its tile template was refused, so the standard tile address is used: {e}")); + } + } + return out; } TilesStep::Next(next) => { out.crossed_origin |= crosses_origin(&doc, &next); @@ -459,6 +483,8 @@ fn advertised_template_with( } } } + out.fallback = + Some(format!("{}: its tile sets lead on past two documents, so the standard tile address is used", crate::sources::redact(list))); out } @@ -474,7 +500,7 @@ enum LeftTemplate { /// back to the standard tile address. Every fallback to that address is said. fn left_template(s: &mut Session, source: &str, list: &str, vector: bool, withheld: &mut u32) -> Result { use rustgis_data::ogc::{TilesStep, resolve_tiles}; - let mut out = AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list) }; + let mut out = AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None }; let mut doc = list.to_string(); for _ in 0..2 { let shown = crate::sources::redact(&doc); @@ -526,7 +552,7 @@ fn left_template(s: &mut Session, source: &str, list: &str, vector: bool, withhe /// In the browser nothing waits: the app reads the template itself and passes it as `"tiles"`. #[cfg(target_arch = "wasm32")] fn advertised_template(source: &str, list: &str, _: bool, _: &mut u32) -> AdvertisedTemplate { - AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list) } + AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None } } /// Adds a template resolved off the command thread through the ordinary admitted command. @@ -826,6 +852,7 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis (Some(list), Some(t)) => AdvertisedTemplate { template: Some(checked_template(source, t)?), crossed_origin: crosses_origin(source, list) || crosses_origin(list, t), + fallback: None, }, (Some(list), None) if leaving => { match left_template(s, source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld)? { @@ -833,7 +860,13 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis LeftTemplate::Waiting(doc) => return waiting_for(s, &doc), } } - (Some(list), None) => advertised_template(source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld), + (Some(list), None) => { + let advertised = advertised_template(source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld); + if let Some(note) = &advertised.fallback { + s.notify(note.clone(), false); + } + advertised + } _ => AdvertisedTemplate::default(), }; match &layer.offer { @@ -1320,6 +1353,21 @@ mod tests { ); } + /// The blocking read of an advertised template says each fallback to the standard address. + #[test] + fn advertised_template_fallbacks_are_said() { + let list = "https://tiles-fallback.example.invalid/tiles?f=json"; + let mut withheld = 0; + let none = advertised_template_with(list, list, false, &mut withheld, |_| Ok(b"{}".to_vec())); + assert!(none.template.is_none()); + assert!(none.fallback.as_ref().is_some_and(|n| n.contains("names no tiles")), "{:?}", none.fallback); + let refused = advertised_template_with(list, "file:///etc/tiles", false, &mut withheld, |_| Ok(b"{}".to_vec())); + assert!(refused.fallback.as_ref().is_some_and(|n| n.contains("was refused")), "{:?}", refused.fallback); + let next = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","links":[{"rel":"self","href":"https://tiles-fallback.example.invalid/next"}]}]}); + let far = advertised_template_with(list, list, false, &mut withheld, |_| Ok(serde_json::to_vec(&next).unwrap_or_default())); + assert!(far.fallback.as_ref().is_some_and(|n| n.contains("past two documents")), "{:?}", far.fallback); + } + #[test] fn foreign_tileset_hops_stay_anonymous_on_return_and_fallback() { use crate::{Project, render::rustgis_tiles as tiles, service_logins as web}; @@ -1362,6 +1410,9 @@ mod tests { assert_eq!(reads, [format!("{list_origin}/tiles?f=json"), format!("{next}?f=json")]); assert!(resolved.crossed_origin); assert_eq!(withheld, 0); + // A tile set that couldn't be read is said; one read gives no notice. + assert_eq!(resolved.fallback.as_ref().is_some_and(|n| n.contains("couldn't be read")), fail, "{:?}", resolved.fallback); + assert!(fail || resolved.fallback.is_none(), "{:?}", resolved.fallback); let chosen = resolved.template.unwrap_or_else(|| tiles::logins::inherit(&source, &template)); if !fail { assert_eq!(chosen, template, "returning to A must not recover its binding"); diff --git a/crates/engine/src/model.rs b/crates/engine/src/model.rs index f681df673a..44ce2f61c6 100644 --- a/crates/engine/src/model.rs +++ b/crates/engine/src/model.rs @@ -824,12 +824,23 @@ struct ImportItem { /// Missing versions are legacy files. The stricter field checks apply only to file import. pub(crate) fn check_file(v: &Value) -> Result<(), String> { let graph = v.get("graph"); + // A model by its schema, a web tool by its format, even when a newer RustGIS changed what it + // holds: told to update. + let model = graph.is_some() || v.get("$schema").and_then(Value::as_str) == Some(SCHEMA); + let tool = v.get("steps").is_some() || v.get("format").and_then(Value::as_str) == Some("RustGIS web tool"); + // Some other file (GeoJSON, a project) is said to be one, not told to update RustGIS. + if !model && !tool { + return Err("not a RustGIS model or web tool (no graph or steps)".into()); + } if let Some(version) = v.get("version") { - let supported = if graph.is_some() { version.as_str() == Some(FILE_VERSION) } else { version.as_u64() == Some(WEB_TOOL_VERSION) }; + let supported = if model { version.as_str() == Some(FILE_VERSION) } else { version.as_u64() == Some(WEB_TOOL_VERSION) }; if !supported { return Err("this model or web tool has an unsupported version. Update RustGIS to import it.".into()); } } + if graph.is_none() && v.get("steps").is_none() { + return Err("not a RustGIS model or web tool (no graph or steps)".into()); + } if graph.is_some() && v.get("steps").is_some() { return Err("a model file cannot contain both a graph and steps. Choose one representation before importing it.".into()); } @@ -888,7 +899,7 @@ pub(crate) fn check_file(v: &Value) -> Result<(), String> { let lost_edges = edges.len().saturating_sub(normalized.edges.len()); if lost_nodes > 0 || lost_edges > 0 { return Err(format!( - "this model would discard {lost_nodes} node(s) and {lost_edges} connection(s). Fix empty or duplicate node IDs and invalid connections before importing it." + "this model would discard {lost_nodes} node(s) and {lost_edges} connection(s): empty or duplicate node IDs, repeated connections into a single-input port, or invalid connections. Fix them before importing it." )); } let by_id: HashMap<&str, &ModelNode> = normalized.nodes.iter().map(|n| (n.id.as_str(), n)).collect(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fa711a6926..9be8093b66 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -15150,14 +15150,28 @@ fn kml_ground_overlays_become_rasters() { std::fs::create_dir_all(&dir).unwrap(); let only = r#"Far../secret.png1010 Webhttps://example.com/x.png1010 -Herered.png1010"#; +Herered.png1010 +Folderfolder.png1010 +Gonegone.png1010 +Throughred.png/x.png1010"#; std::fs::write(dir.join("o.kml"), only).unwrap(); + std::fs::create_dir_all(dir.join("folder.png")).unwrap(); std::fs::write(dir.join("red.png"), red.encode_png().unwrap()).unwrap(); let mut u = Session::new(Project::default()); u.run("layer.addData", &json!({"path": dir.join("o.kml").display().to_string()})).unwrap(); assert!(u.map().layer_by_name("Here").is_some()); assert!(u.map().layer_by_name("Far").is_none() && u.map().layer_by_name("Web").is_none()); assert!(u.notices.iter().any(|n| n.text.contains("Far (its picture ../secret.png isn't in the file or beside it)"))); + for name in ["Folder", "Gone", "Through"] { + assert!(u.map().layer_by_name(name).is_none(), "{name}"); + } + // A picture beside it that can't be read says why, not that it's missing. + assert!(u.notices.iter().any(|n| n.text.contains("Folder (its picture folder.png can't be read:") && n.text.contains("isn't a file"))); + assert!(!u.notices.iter().any(|n| n.text.contains("folder.png isn't in the file"))); + // One missing beside it (or under a file named as a folder) is said to be missing. + for name in ["Gone (its picture gone.png", "Through (its picture red.png/x.png"] { + assert!(u.notices.iter().any(|n| n.text.contains(&format!("{name} isn't in the file or beside it)"))), "{name}: {:?}", u.notices); + } let _ = std::fs::remove_dir_all(dir); } @@ -33268,6 +33282,49 @@ fn topology_refuses_latitudes_past_the_poles() { } } +#[test] +fn importing_a_file_that_is_neither_map_nor_project_says_so() { + // Neither a map nor a project: the refusal names what the import takes, not a failed project. + let mut s = world(); + let e = s.run("map.import", &json!({"text": r#"{"name": 5, "layers": 3}"#})).unwrap_err(); + assert!(e.contains("not a RustGIS map file, project or package"), "{e}"); + // Text that isn't JSON at all is said to be none of them the same way. + let e = s.run("map.import", &json!({"text": "not json"})).unwrap_err(); + assert!(e.contains("not a RustGIS map file, project or package"), "{e}"); + assert!(!e.contains("not a RustGIS project"), "{e}"); + let e = s.run("style.import", &json!({"text": r#"{"name": 5, "layers": 3}"#})).unwrap_err(); + assert!(e.contains("not a RustGIS layer file, map file or project"), "{e}"); + let e = s.run("style.import", &json!({"text": "not json"})).unwrap_err(); + assert!(e.contains("not a RustGIS layer file, map file or project"), "{e}"); + // A project from a newer RustGIS keeps its advice. + let e = s.run("map.import", &json!({"text": r#"{"format": 99999, "maps": 3}"#})).unwrap_err(); + assert!(e.contains("Update RustGIS"), "{e}"); +} + +#[test] +fn model_import_refusals_name_their_cause() { + let mut s = world(); + // A file that is no model or web tool is said to be one, not told to update RustGIS. + for text in [r#"{"type": "FeatureCollection", "features": []}"#, r#"{"version": 99, "name": "x"}"#] { + let e = s.run("model.import", &json!({"text": text})).unwrap_err(); + assert!(e.contains("not a RustGIS model or web tool (no graph or steps)"), "{e}"); + } + // A model by its schema, or a web tool by its format, from a newer RustGIS that holds + // something else is told to update. + for text in [ + json!({"$schema": crate::model::SCHEMA, "version": "2.0.0", "name": "New", "nodes": []}), + json!({"format": "RustGIS web tool", "version": 2, "name": "New"}), + ] { + let e = s.run("model.import", &json!({"text": text.to_string()})).unwrap_err(); + assert!(e.contains("Update RustGIS"), "{e}"); + } + // A model whose nodes would be dropped says the causes it may have. + let graph = json!({"nodes": [{"id": "a", "kind": "input", "layer": "Cities"}, {"id": "a", "kind": "input", "layer": "Countries"}], "edges": []}); + let text = json!({"$schema": crate::model::SCHEMA, "version": "1.0.0", "name": "Dup", "graph": graph}).to_string(); + let e = s.run("model.import", &json!({"text": text})).unwrap_err(); + assert!(e.contains("would discard 1 node(s)") && e.contains("repeated connections into a single-input port"), "{e}"); +} + /// `analysis.interpolate` says how many features it leaves out, and why: those with no place to /// stand for and those whose value isn't a number. A layer it reads whole says nothing. #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 4306d5cef3..91b7b0d2fe 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1305,8 +1305,10 @@ their name. has that tool and those after it run again as the results are added, and so does a tool that writes a file, a plugin tool or a GeoLibre tool, with those after it. Those run as a model always has, holding the window until they finish, with the work limits of a run that can't - be cancelled. A file a tool reads by its path isn't compared: one changed during the run - gives the result from what was read. A model run from a script in the Script pane is worked + be cancelled. The tools worked out in the background take no work limit, as a run that can + be stopped takes none. Tools that run holding the window or from the command line keep it, so + the same model can finish in the background and stop at the limit there. A file a tool reads + by its path isn't compared: one changed during the run gives the result from what was read. A model run from a script in the Script pane is worked out in the background with the script; one run from the command line or the assistant runs where the command runs. - **Save** keeps the model in the project; **Export** writes it as a `*.model.json` file, which