diff --git a/crates/data/src/address.rs b/crates/data/src/address.rs index fb55afbd60..148680e07f 100644 --- a/crates/data/src/address.rs +++ b/crates/data/src/address.rs @@ -75,6 +75,29 @@ pub fn percent_decode(s: &str) -> String { String::from_utf8_lossy(&decode_pass(s.as_bytes(), DecodeMode::Value)).into_owned() } +/// Decodes a local file URI once without changing ordinary paths or replacing invalid UTF-8. +/// A URI's extra slash before a Windows drive is removed; callers still validate local access. +pub fn local_file_path(address: &str) -> Result { + let Some(path) = address.strip_prefix("file://") else { + return Ok(address.to_string()); + }; + let decoded = + String::from_utf8(decode_pass(path.as_bytes(), DecodeMode::Value)).map_err(|_| "the file address contains invalid UTF-8")?; + let path = decoded.strip_prefix('/').unwrap_or(&decoded); + let drive = path.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) + && path.as_bytes().get(1) == Some(&b':') + && matches!(path.as_bytes().get(2), Some(b'/' | b'\\')); + if path.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) && path.as_bytes().get(1) == Some(&b':') && !drive { + return Err("a file address must use the drive's full rooted path"); + } + // Reject an authority before removing the URI prefix, including encoded network shares. + let sep = |b: Option<&u8>| matches!(b, Some(b'/' | b'\\')); + if !decoded.starts_with('/') || (sep(decoded.as_bytes().first()) && sep(decoded.as_bytes().get(1))) { + return Err("a file address must name a file on this computer, not a network share"); + } + Ok(if drive { path.to_string() } else { decoded }) +} + /// [`percent_decode`] for a query string or form body, where `+` is a space. pub fn form_decode(s: &str) -> String { String::from_utf8_lossy(&decode_pass(s.as_bytes(), DecodeMode::FormValue)).into_owned() diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 38d8446506..b13f879ecc 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -217,13 +217,13 @@ fn build_package( }; let mut entries: Vec<(String, Vec)> = Vec::new(); let mut budget = most_unpacked() / 2; - // Each local archive goes in beside the project, its layer reading it from there. + // Each local tile source goes in beside the project, its layer reading it from there. let (mut online, mut unread, mut uploaded) = (Vec::new(), Vec::new(), Vec::new()); let mut taken = std::collections::HashSet::new(); progress::begin(map.tiles.len()); for t in &mut map.tiles { progress::step(1).map_err(|e| e.to_string())?; - let Some(file) = t.archive_file().map(str::to_string) else { + let Some(file) = t.local_file().map(str::to_string) else { // An archive added to the web app lives in its memory, not in a file to put in. if t.url.starts_with(rustgis_map::tiles::UPLOAD) { uploaded.push(t.name.clone()); @@ -232,6 +232,10 @@ fn build_package( } continue; }; + if rustgis_map::paths::is_project_relative(&file) { + unread.push(format!("{} ({})", t.name, rustgis_map::paths::unknown_folder(&file))); + continue; + } match crate::project::read_file(Path::new(&file), budget) { Ok(bytes) => { budget = budget.saturating_sub(bytes.len() as u64); @@ -247,6 +251,7 @@ fn build_package( .collect() }, ); + let stem = plain_name(&stem); let mut name = stem.clone(); for n in 2.. { if taken.insert(name.to_ascii_lowercase()) { @@ -256,6 +261,9 @@ fn build_package( } t.url = format!("{BASEMAPS}/{name}"); entries.push((t.url.clone(), bytes)); + if t.kind == rustgis_map::tiles::TileKind::Style { + online.push(t.name.clone()); + } } Err(e) => unread.push(format!("{} ({e})", t.name)), } @@ -278,7 +286,7 @@ fn build_package( ); } if !unread.is_empty() { - archive_error(s, format!("{} tile archive(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); + archive_error(s, format!("{} tile source file(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); } // The photos the features name go with them: going out, those named here, the features // naming them as before (the phone points them at the unpacked files); coming back, those @@ -2328,6 +2336,65 @@ mod tests { assert!(into.join("basemaps/site.mbtiles").is_file() && again.join("basemaps/site.mbtiles").is_file()); } + /// The phone receives the style document; its web sources still need a connection. + #[test] + fn field_package_carries_a_local_style_file() { + for (file_name, packed_name) in [ + ("style.json", "style.json"), + // Unix can create a name that Windows cannot unpack unchanged. + #[cfg(unix)] + ("CON.json", "_CON.json"), + ] { + let temp = Temp::new("local-style"); + let file = temp.path().join(file_name); + let doc = br#"{"version":8,"sources":{},"layers":[]}"#; + std::fs::write(&file, doc).unwrap(); + let mut s = sample(); + s.map_mut().tiles.push(TileLayer::new("Local style", TileKind::Style, file.display().to_string())); + let mark = s.notice_mark(); + let (_, bytes) = package(&mut s, &json!({"name":"Survey", "extent":[-20,-40,60,40]})).unwrap(); + let entries = rustgis_data::zip::read(&bytes).unwrap(); + let packaged = format!("basemaps/{packed_name}"); + assert_eq!(entries.iter().find(|(name, _)| name == &packaged).unwrap().1, doc); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("Local style") && n.text.contains("online"))); + assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("tile source file(s) couldn't"))); + let into = temp.path().join("unpacked"); + let text = unpack_into(&bytes, &into).unwrap().0; + let project = project_in(&text, &into).unwrap(); + let tile = project.maps[0].tiles.iter().find(|t| t.name == "Local style").unwrap(); + assert_eq!(Path::new(&tile.url), into.join(packaged)); + } + } + + /// An unbound project path must not pick up a same-named source in the process directory. + #[test] + fn field_package_leaves_unbound_relative_tile_sources_out_and_names_them() { + let serial = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let folder = format!("rustgis-field-relative-{}-{serial}", std::process::id()); + // Keep the process directory unchanged: other tests may be reading files concurrently. + let temp = Temp(std::env::current_dir().unwrap().join(&folder)); + std::fs::create_dir(temp.path()).unwrap(); + let mut s = sample(); + s.map_mut().tiles.clear(); + for (name, kind, file) in [ + ("Style", TileKind::Style, "style.json"), + ("PMTiles", TileKind::PmTiles, "map.pmtiles"), + ("MBTiles", TileKind::MbTiles, "map.mbtiles"), + ] { + std::fs::write(temp.path().join(file), br#"{"version":8,"sources":{},"layers":[]}"#).unwrap(); + s.map_mut().tiles.push(TileLayer::new(name, kind, format!("{folder}/{file}"))); + } + let mut s = Session::new(Project::from_json(&serde_json::to_string(&s.project).unwrap()).unwrap()); + assert!(s.map().tiles.iter().all(|t| t.error.as_ref().is_some_and(|e| e.contains("folder")))); + let mark = s.notice_mark(); + let (_, bytes) = package(&mut s, &json!({"name":"Survey", "extent":[-20,-40,60,40]})).unwrap(); + let entries = rustgis_data::zip::read(&bytes).unwrap(); + assert!(entries.iter().all(|(name, _)| !name.starts_with("basemaps/")), "no source is read from the process directory"); + let notice = s.notices_since(mark).iter().find(|n| n.text.starts_with("3 tile source file(s) couldn't")).unwrap(); + assert!(notice.text.contains("Style") && notice.text.contains("PMTiles") && notice.text.contains("MBTiles")); + assert!(notice.text.contains("folder, which isn't known")); + } + #[test] fn field_package_carries_streamed_features_after_the_source_is_gone() { let temp = Temp::new("stream"); diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index e9ef743a27..e552078298 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -534,7 +534,7 @@ fn left_linked<'a>(what: &str, maps: impl IntoIterator) -> Optio let (mut names, mut edited) = (Vec::new(), Vec::new()); for m in maps { names.extend(m.layers.iter().filter(|l| l.linked_file().is_some()).map(|l| l.name.as_str())); - names.extend(m.tiles.iter().filter(|t| t.archive_file().is_some()).map(|t| t.name.as_str())); + names.extend(m.tiles.iter().filter(|t| t.local_file().is_some()).map(|t| t.name.as_str())); edited.extend(m.layers.iter().filter(|l| l.edits_saved_outside()).map(|l| l.name.as_str())); } linked_said(what, "the package", &names, &edited) @@ -2226,3 +2226,22 @@ pub(crate) fn project_inputs(input: &super::InputContext<'_>, _: &Value) -> Resu inputs.tables.extend(s.project.tables.iter().map(|t| t.id)); Ok(inputs) } + +#[cfg(test)] +mod local_style_tests { + use super::*; + + #[test] + fn packages_name_local_style_files_left_outside_and_web_styles_need_no_notice() { + let mut map = Map::new("Map"); + map.tiles.push(rustgis_map::tiles::TileLayer::new("Local style", rustgis_map::tiles::TileKind::Style, "/data/maps/style.json")); + let notice = left_linked("Package Project", [&map]).unwrap(); + assert!(notice.contains("1 layer(s)"), "{notice}"); + assert!(notice.contains("Local style"), "{notice}"); + let paths = map.file_paths_mut(); + assert_eq!(paths.len(), 1); + assert_eq!(paths[0].0, "/data/maps/style.json"); + map.tiles[0].url = "https://example.test/style.json".into(); + assert!(left_linked("Package Project", [&map]).is_none()); + } +} diff --git a/crates/engine/src/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index 1e228fd7b9..78c169133b 100644 --- a/crates/engine/src/cmd/tiles.rs +++ b/crates/engine/src/cmd/tiles.rs @@ -17,7 +17,7 @@ const TILE_ROLES: &[crate::ParamRole] = &[crate::ParamRole { key: "legend", role pub fn commands() -> Vec { vec![ C::new("map.addTiles", "Add Tile Layer", "Home › Add", add).roles(TILE_ROLES).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/{z}/{x}/{y}.png" | vector tiles ".pbf" or TileJSON | MapLibre style.json | a PMTiles archive (web address or file path) | an MBTiles file path, "kind"?: "raster"|"vector"|"style"|"pmtiles"|"mbtiles" (guessed from the url), "name"?: text, "bounds"?: [west, south, east, north] (longitude/latitude coverage, when known), "attribution"?: text, "minZoom"?: number, "maxZoom"?: number, "tileSize"?: 256|512 (1024 too for a WMS or map service asked for in Web Mercator by its tiles' box: their pictures are asked for that size), "singleImage"?: bool (a WMS or map service: one picture of the view instead of tiles, so symbols and labels aren't cut at tile edges; tiles on the globe, a tilted map or a projection the service doesn't offer; by default on for one, unless tileSize is given), "tms"?: bool, "subdomains"?: [text], "layers"?: [vector tile layer names, drawn in colours of their own], "styleLayers"?: [MapLibre style layers drawing vector tiles instead (their source is the tiles')], "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference" (how it combines with what is beneath), "resampling"?: "nearest"|"bilinear" (picture tiles drawn at a size other than their own: each pixel a block, or blended, the default; a PMTiles or MBTiles archive whose header isn't read yet, as a web one's usually isn't, is refused it here: add it without resampling and set it through map.setTiles once it shows), "overlay"?: bool (on top of the map's layers, as every new layer goes; without it a basemap, under them; one with the same address and role is replaced when it has the same name or the same look), "top"?: bool (on top of the map's layers, as a layer added as data goes; by default an overlay's place), "replace"?: bool (removes the other tile basemaps, not overlays), "id"?: catalog id, "view"?: bool (a MapLibre style: go to the place, zoom, bearing and pitch its root properties give, once it loads), "start"?, "end"?: dates a url with date placeholders ({date:YYYY-MM-DD}, {YYYY}) spans, turning the time slider on (or, when it is on, setting its span), "unit"?, "interval"?, "dates"?: its steps (as in time.set), "legend"?: "the web address of its legend picture (PNG or JPEG)" | [address | {"url": address, "minScale"?: scale denominator, "maxScale"?: one (the scales it is for, from minScale up to below maxScale)}] (at most 16; the Layers pane shows the one for the map's scale under the layer; service.add gives a WMS or WMTS layer its service's), "connection"?: "the id of the saved web-service connection it comes from (as service.add): the tile layer records it, and its tiles are read with its login", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials: the tile layer is marked so and never takes a login)}"#, + r#"{"url": "https://…/{z}/{x}/{y}.png" | vector tiles ".pbf" or TileJSON | MapLibre style.json (web address or .json file path) | a PMTiles archive (web address or file path) | an MBTiles file path, "kind"?: "raster"|"vector"|"style"|"pmtiles"|"mbtiles" (guessed from the url), "name"?: text, "bounds"?: [west, south, east, north] (longitude/latitude coverage, when known), "attribution"?: text, "minZoom"?: number, "maxZoom"?: number, "tileSize"?: 256|512 (1024 too for a WMS or map service asked for in Web Mercator by its tiles' box: their pictures are asked for that size), "singleImage"?: bool (a WMS or map service: one picture of the view instead of tiles, so symbols and labels aren't cut at tile edges; tiles on the globe, a tilted map or a projection the service doesn't offer; by default on for one, unless tileSize is given), "tms"?: bool, "subdomains"?: [text], "layers"?: [vector tile layer names, drawn in colours of their own], "styleLayers"?: [MapLibre style layers drawing vector tiles instead (their source is the tiles')], "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference" (how it combines with what is beneath), "resampling"?: "nearest"|"bilinear" (picture tiles drawn at a size other than their own: each pixel a block, or blended, the default; a PMTiles or MBTiles archive whose header isn't read yet, as a web one's usually isn't, is refused it here: add it without resampling and set it through map.setTiles once it shows), "overlay"?: bool (on top of the map's layers, as every new layer goes; without it a basemap, under them; one with the same address and role is replaced when it has the same name or the same look), "top"?: bool (on top of the map's layers, as a layer added as data goes; by default an overlay's place), "replace"?: bool (removes the other tile basemaps, not overlays), "id"?: catalog id, "view"?: bool (a MapLibre style: go to the place, zoom, bearing and pitch its root properties give, once it loads), "start"?, "end"?: dates a url with date placeholders ({date:YYYY-MM-DD}, {YYYY}) spans, turning the time slider on (or, when it is on, setting its span), "unit"?, "interval"?, "dates"?: its steps (as in time.set), "legend"?: "the web address of its legend picture (PNG or JPEG)" | [address | {"url": address, "minScale"?: scale denominator, "maxScale"?: one (the scales it is for, from minScale up to below maxScale)}] (at most 16; the Layers pane shows the one for the map's scale under the layer; service.add gives a WMS or WMTS layer its service's), "connection"?: "the id of the saved web-service connection it comes from (as service.add): the tile layer records it, and its tiles are read with its login", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials: the tile layer is marked so and never takes a login)}"#, ), C::new("map.removeTiles", "Remove Tile Layer", "Home › Add", remove).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name"?: text, "index"?: number, "id"?: catalog id} (removes every tile layer when none is given)"#), @@ -160,7 +160,7 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { } /// The executor and its source-reach selector accept the same explicit or guessed kind. -fn add_kind(p: &Value, url: &str) -> Result { +pub(crate) fn add_kind(p: &Value, url: &str) -> Result { match ps(p, "kind") { Some(k) => TileKind::from_code(k).ok_or_else(|| format!("unknown kind '{k}' (raster, vector, style, pmtiles or mbtiles)")), None => Ok(TileKind::guess(url)), @@ -172,6 +172,7 @@ pub(crate) fn add_reach(p: &Value) -> crate::policy::Effects { let Some(url) = ps(p, "url").map(str::trim) else { return crate::policy::Effects::NONE }; match add_kind(p, url) { Ok(kind @ (TileKind::PmTiles | TileKind::MbTiles)) => tile_source_reach(&TileLayer::new("", kind, url)), + Ok(TileKind::Style) if rustgis_map::tiles::is_local_style(url) => crate::policy::Effects::NONE.with(crate::policy::Effect::Files), _ => crate::policy::Effects::NONE, } } @@ -577,6 +578,9 @@ pub(crate) fn tile_source_reach(t: &TileLayer) -> crate::policy::Effects { use rustgis_render::rustgis_tiles::{mbtiles, s3}; if t.kind == TileKind::MbTiles && mbtiles::is_upload(&t.url) { Effects::NONE + } else if t.kind == TileKind::Style && rustgis_map::tiles::is_local_style(&t.url) { + // A style file on this computer (#2388) is read, and the tiles it names fetched. + Effects::NONE.with(Effect::Files).with(Effect::Network) } else if matches!(t.kind, TileKind::PmTiles | TileKind::MbTiles) && !s3::split_anonymous(&t.url).1 && rustgis_map::tiles::is_local_archive(&t.url) diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 7c6e997a00..38a0970824 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -88,6 +88,7 @@ pub const CAPABILITIES: &[&str] = &[ "terrain-block-walls-top", "shaded-relief-effects", "normalized-legend-urls", + "tile-style-file", "field-origin", "slope-percent", "shaded-relief-light", @@ -1762,7 +1763,7 @@ impl Project { // The time slider's window and dated tile addresses, before the addresses are checked. m.apply_time(); for t in &mut m.tiles { - if let Some(f) = t.archive_file().filter(|f| rustgis_map::paths::is_project_relative(f)) { + if let Some(f) = t.local_file().filter(|f| rustgis_map::paths::is_project_relative(f)) { t.error = Some(rustgis_map::paths::unknown_folder(f)); } } diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index e817be5fff..9a2bf790f0 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -210,6 +210,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layer-raster-mask", command_masks_by_raster), (UNIQUE_KEEP_ORDER, command_adds_kept_class_order), ("tile-resampling", command_resamples_tiles), + ("tile-style-file", command_adds_style_file), ("layout-page-color", command_colours_the_page), ("layout-text-statistics", command_uses_text_statistics), ("layout-publication-parts", command_sets_publication_parts), @@ -469,6 +470,38 @@ fn command_removes_duplicate_labels(id: &str, params: &Value) -> bool { } } +/// An older reader cannot keep a local style added directly, or opened from a saved inline map +/// or project. Read imports' data-before-text choice as the command does; paths have file headers. +fn command_adds_style_file(id: &str, params: &Value) -> bool { + match id { + "map.addTiles" => params.get("url").and_then(Value::as_str).map(str::trim).is_some_and(|url| { + rustgis_map::tiles::is_local_style(url) && crate::cmd::tiles::add_kind(params, url) == Ok(rustgis_map::tiles::TileKind::Style) + }), + "map.import" | "project.fromTemplate" => { + crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|text| text_uses_style_file(&text)) + } + // This command reads only `text`, even when the step also holds `data`. + "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_uses_style_file), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_adds_style_file)), + _ => false, + } +} + +/// A headerless inline project still needs its maps' and replayable steps' capabilities. A map +/// needs only tile metadata, skipping its feature payload; Project's default fields could +/// otherwise hide a map's top-level tile layers. +fn text_uses_style_file(text: &str) -> bool { + #[derive(Deserialize)] + struct InlineTiles { + maps: Option, + #[serde(default)] + tiles: Vec, + } + let Ok(document) = serde_json::from_str::(text) else { return false }; + document.tiles.iter().any(|tile| tile.kind == rustgis_map::tiles::TileKind::Style && tile.local_file().is_some()) + || (document.maps.is_some() && inline_project_requires(text, "tile-style-file").unwrap_or(false)) +} + /// A saved `map.addTiles` or `map.setTiles` drawing a tile layer's pictures nearest (#2804), read as /// the command reads it: an older reader runs it without the key, saying nothing, so the layer would /// stay blended. `bilinear` is what an older reader keeps. @@ -1835,7 +1868,9 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static let mut obstructing = false; let (mut crisp, mut bed, mut walls_top, mut soft, mut aerial, mut terrain_type, mut flats, mut generalize) = (false, false, false, false, false, false, false, false); + let mut style_file = false; for map in maps { + style_file |= map.tiles.iter().any(|t| t.kind == rustgis_map::tiles::TileKind::Style && t.local_file().is_some()); offline_area_id |= map.offline_area_id.is_some(); // A blank basemap's paper colour (#2532), which an older reader would draw and save white. paper |= map.paper.is_some(); @@ -1919,6 +1954,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (cleared, "label-clearance"), (deduped, "label-duplicates"), (crisp, "tile-resampling"), + (style_file, "tile-style-file"), (offline_area_id, "offline-map-area-id"), (paper, "blank-paper"), (native, super::NATIVE_COORDINATES), @@ -2315,6 +2351,69 @@ mod tests { serde_json::from_slice(bytes).unwrap() } + /// A local style needs a capable reader; a web style remains readable by older versions. + #[test] + fn local_style_fixture_requires_a_reader_that_keeps_its_layer() { + let fixture = Project::from_json(include_str!("../../../schema/fixtures/tile_style_file.rgis")).unwrap(); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["tile-style-file"])); + let reopened = Project::from_json(&saved.to_string()).unwrap(); + assert_eq!(reopened.maps[0].tiles[0].url, "/data/maps/style.json"); + let mut plain = fixture; + plain.maps[0].tiles[0].url = "https://example.test/style.json".into(); + assert!(serde_json::to_value(&plain).unwrap().get("requires").is_none()); + assert!(command_adds_style_file("map.addTiles", &json!({"url": "/data/maps/style.json"}))); + assert!(!command_adds_style_file("map.addTiles", &json!({"url": "/data/maps/archive.pmtiles"}))); + for kind in ["Style", "maplibre"] { + assert!(command_adds_style_file("map.addTiles", &json!({"url": " /data/maps/style.json ", "kind": kind}))); + } + let mut relative = saved; + relative["maps"][0]["tiles"][0]["url"] = json!("styles/topo.json"); + let opened = Project::from_json(&relative.to_string()).unwrap(); + assert_eq!(opened.maps[0].tiles.len(), 1); + assert!(opened.maps[0].tiles[0].error.as_ref().is_some_and(|e| e.contains("folder"))); + assert_eq!(serde_json::to_value(&opened).unwrap()["maps"][0]["tiles"][0]["url"], "styles/topo.json"); + } + + /// The outer saved task protects headerless inline documents, including base64 imports and + /// a project whose own task opens another project. Web-only styles need no new capability. + #[test] + fn saved_inline_local_styles_require_a_reader_that_keeps_them() { + use base64::Engine; + let mut local: Value = serde_json::from_str(include_str!("../../../schema/fixtures/tile_style_file.rgis")).unwrap(); + local.as_object_mut().unwrap().remove("requires"); + let mut web = local.clone(); + web["maps"][0]["tiles"][0]["url"] = json!("https://example.test/style.json"); + let needs = |id: &str, params: Value| { + let mut outer = serde_json::to_value(Project::default()).unwrap(); + outer["tasks"] = json!([{"name":"Open", "steps":[{"title":"Open", "command":id, "params":params}]}]); + let project = Project::from_json(&outer.to_string()).unwrap(); + serde_json::to_value(project).unwrap().get("requires").cloned().unwrap_or(json!([])) + }; + for (id, local, web) in [ + ("project.openText", local.to_string(), web.to_string()), + ("map.import", local["maps"][0].to_string(), web["maps"][0].to_string()), + ("map.import", local.to_string(), web.to_string()), + ("project.fromTemplate", local.to_string(), web.to_string()), + ] { + assert_eq!(needs(id, json!({"text":local})), json!(["tile-style-file"]), "{id}"); + assert_eq!(needs(id, json!({"text":web})), json!([]), "{id}"); + let (local_data, web_data) = + (base64::engine::general_purpose::STANDARD.encode(&local), base64::engine::general_purpose::STANDARD.encode(&web)); + let text_wins = id == "project.openText"; + assert_eq!(needs(id, json!({"text":local,"data":web_data})), if text_wins { json!(["tile-style-file"]) } else { json!([]) }); + assert_eq!(needs(id, json!({"text":web,"data":local_data})), if text_wins { json!([]) } else { json!(["tile-style-file"]) }); + } + let mut nested = web; + nested["tasks"] = + json!([{"name":"Inner", "steps":[{"title":"Open", "command":"project.openText", "params":{"text":local.to_string()}}]}]); + assert_eq!(needs("project.openText", json!({"text":nested.to_string()})), json!(["tile-style-file"])); + assert_eq!( + needs("script.run", json!({"script":format!("project.openText {}", json!({"text":local.to_string()}))})), + json!(["tile-style-file"]) + ); + } + /// A tile layer drawn nearest (#2804) reads back as it was and saving names `tile-resampling`; /// one drawn blended, as an older reader would, names nothing. So does a saved step setting it. #[test] @@ -2635,6 +2734,7 @@ mod tests { (&["label-clearance"], "labels.placement", json!({"clearance": 9})), (&["label-duplicates"], "labels.placement", json!({"removeDuplicates": 20})), (&["tile-resampling"], "map.addTiles", json!({"resampling": "nearest"})), + (&["tile-style-file"], "map.addTiles", json!({"url": "/data/maps/style.json"})), (&["layout-page-color"], "layout.page", json!({"color": "#0B1B2B"})), (&["layout-text-statistics"], "layout.addElement", json!({"kind": "text", "text": "{count:Cities}"})), (&["layout-publication-parts"], "layout.publication", json!({"grid": "none"})), diff --git a/crates/engine/src/tests/permission_policy.rs b/crates/engine/src/tests/permission_policy.rs index 571e117f6c..1b915ca693 100644 --- a/crates/engine/src/tests/permission_policy.rs +++ b/crates/engine/src/tests/permission_policy.rs @@ -25,6 +25,24 @@ fn pending(s: &Session, scope: &Scope, call: &Call) -> Pending { } } +/// A MapLibre style file on this computer (#2388) is a file read as well as the network reach +/// every tile layer has; a style by its web address is not. +#[test] +fn permission_policy_a_local_style_file_reads_files() { + use crate::policy::{Effect, command_effects}; + let s = Session::new(Project::default()); + let spec = s.registry.get("map.addTiles").unwrap(); + for (params, files) in [ + (json!({"url":"/home/me/maps/topo.json","kind":"style"}), true), + (json!({"url":"C:\\Maps\\topo.json"}), true), + (json!({"url":"https://maps.invalid/style.json"}), false), + ] { + let effects = command_effects(spec, ¶ms); + assert_eq!(effects.contains(Effect::Files), files, "{params}"); + assert!(effects.contains(Effect::Network), "{params}"); + } +} + /// Reload's implicit local-file access uses the same grants as explicit file commands. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 40007fc1f2..9adfd38217 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -2498,7 +2498,7 @@ impl Map { pub fn file_paths_mut(&mut self) -> Vec<(&mut String, bool)> { let mut paths = Vec::new(); for tile in &mut self.tiles { - if tile.archive_file().is_some() { + if tile.local_file().is_some() { paths.push((&mut tile.url, false)); } } diff --git a/crates/map/src/tiles.rs b/crates/map/src/tiles.rs index d3c4b34ae7..4111b46140 100644 --- a/crates/map/src/tiles.rs +++ b/crates/map/src/tiles.rs @@ -74,6 +74,10 @@ impl TileKind { /// The kind an address most likely is, from how it looks. pub fn guess(url: &str) -> TileKind { let url = rustgis_data::login_address::inner(url); + // A file's name is the whole path: `#` and `?` are characters of it, not a fragment or query. + if is_local_style(url) && style_file_path(url).is_ok_and(|p| p.to_ascii_lowercase().ends_with(".json")) { + return TileKind::Style; + } let path = url.split(['?', '#']).next().unwrap_or(url).to_ascii_lowercase(); if path.ends_with(".pmtiles") { TileKind::PmTiles @@ -396,6 +400,11 @@ pub struct TileRepairs { } impl TileLayer { + /// A tile layer whose source document or archive stays in a local file. + pub fn local_file(&self) -> Option<&str> { + self.archive_file().or_else(|| (self.kind == TileKind::Style && is_local_archive(&self.url)).then_some(self.url.as_str())) + } + /// The local archive that Repair Data Source replaces. pub fn archive_file(&self) -> Option<&str> { (matches!(self.kind, TileKind::PmTiles | TileKind::MbTiles) && is_local_archive(&self.url) && !self.url.starts_with(UPLOAD)) @@ -554,11 +563,18 @@ impl TileLayer { self.time_urls.dedup_by(|a, b| a.0 == b.0); self.time_urls.truncate(MAX_TIME_URLS); repairs.addresses = dated - self.time_urls.len() - usize::from(self.time_url.is_some()); - let local = matches!(self.kind, TileKind::PmTiles | TileKind::MbTiles) && is_local_archive(&self.url); + let style_file = self.kind == TileKind::Style && is_local_archive(&self.url); + let local = style_file || (matches!(self.kind, TileKind::PmTiles | TileKind::MbTiles) && is_local_archive(&self.url)); if let Some(name) = self.url.strip_prefix(UPLOAD).filter(|_| self.kind == TileKind::MbTiles) { if name.is_empty() || name.len() > 512 || name.chars().any(char::is_control) { return Err("an uploaded MBTiles file needs a name".into()); } + } else if style_file { + if self.error.is_none() { + let decoded = style_file_path(&self.url).map_err(str::to_string)?; + check_path(&decoded, "json")?; + self.url = decoded; + } } else if local { if self.error.is_none() { check_path(&self.url, if self.kind == TileKind::MbTiles { "mbtiles" } else { "pmtiles" })?; @@ -570,10 +586,14 @@ impl TileLayer { self.name = self.name.trim().chars().take(120).collect(); if self.name.is_empty() { let file = || { - std::path::Path::new(self.url.trim_start_matches(UPLOAD).trim_start_matches("file://")) - .file_stem() - .and_then(|s| s.to_str()) - .map(str::to_string) + std::path::Path::new(&if style_file { + style_file_path(&self.url).ok()? + } else { + self.url.trim_start_matches(UPLOAD).trim_start_matches("file://").to_string() + }) + .file_stem() + .and_then(|s| s.to_str()) + .map(str::to_string) }; self.name = if local { file() } else { host_of(&self.url).map(str::to_string) }.unwrap_or_else(|| "Tiles".into()); } @@ -633,10 +653,27 @@ pub fn is_local_archive(url: &str) -> bool { !(lower.starts_with("https://") || lower.starts_with("http://") || lower.starts_with("s3://")) } -/// Whether an archive's file path may be read: absolute, a `.` file (`pmtiles`, -/// `mbtiles`), no longer than 4096 bytes. The same rules as the tile reader's -/// (`rustgis_tiles::pmtiles::check_local_prefix`, a crate this one can't depend on), so a layer -/// accepted here isn't refused when it draws. +/// Whether a MapLibre style's address is a file on this computer (#2388): a path from the root +/// or a drive, or a `file://` address, rather than a web address. Anything else is judged as a web +/// address, and refused as one. +pub fn is_local_style(url: &str) -> bool { + if !is_local_archive(url) { + return false; + } + let p = url.strip_prefix("file://").unwrap_or(url); + let drive = p.as_bytes().get(1) == Some(&b':') && p.as_bytes().first().is_some_and(u8::is_ascii_alphabetic); + url.starts_with("file://") || p.starts_with('/') || p.starts_with('\\') || drive +} + +/// The path a style file's address names for its checks: a `file://` address is percent-decoded +/// as its reader opens it (RFC 8089), so `file:///maps/topo%2Ejson` checks as `topo.json`; any +/// other address is its own text. +fn style_file_path(url: &str) -> Result { + rustgis_data::address::local_file_path(url) +} + +/// Whether an archive's or style's file path may be read: absolute, a `.` file (`pmtiles`, +/// `mbtiles`, `json`), no longer than 4096 bytes. pub fn check_path(path: &str, ext: &str) -> Result<(), String> { let (file_url, p) = match path.strip_prefix("file://") { Some(p) => (true, p), @@ -748,7 +785,7 @@ impl TileLayer { headers_shown: _, } = self; use crate::TileRole as R; - let mut out = vec![(R::Url, url.as_str(), self.archive_file().is_some())]; + let mut out = vec![(R::Url, url.as_str(), self.local_file().is_some())]; if let Some(v) = time_url { out.push((R::TimeUrl, v.as_str(), false)); } @@ -813,6 +850,43 @@ mod tests { } } + /// A MapLibre style may be a `.json` file on this computer (#2388), given by its full path: + /// it is kept as a style, named after the file; a relative path, a network share or another + /// kind of file is refused. + #[test] + fn a_style_file_on_this_computer_is_kept_by_its_path() { + // A `#` or `?` in a file's name is part of it, not a web address's fragment or query. + assert_eq!(TileKind::guess("/home/me/maps/day#night.json"), TileKind::Style); + assert_eq!(TileKind::guess("C:\\Maps\\what?.json"), TileKind::Style); + for path in ["/home/me/maps/topo.json", "C:\\Maps\\topo.json", "file:///home/me/maps/topo.json"] { + assert!(is_local_style(path), "{path}"); + assert_eq!(TileKind::guess(path), TileKind::Style, "{path}"); + let mut t = TileLayer::new("", TileKind::Style, path); + t.repair().unwrap(); + assert_eq!(t.url, style_file_path(path).unwrap()); + // (A path's separators are this system's: a Windows path is named on Windows.) + if !path.starts_with("C:") || cfg!(windows) { + assert_eq!(t.name, "topo", "{path}"); + } + } + for path in ["https://maps.test/style.json", "maps/topo.json", "rustgis-login:broken"] { + assert!(!is_local_style(path), "{path}"); + } + // Windows reads mixed separators as a share too, and `C:topo.json` from the drive's current folder. + for path in [ + "\\\\server\\share\\topo.json", + "//server/share/topo.json", + "/\\server\\share\\topo.json", + "\\/server/share/topo.json", + "file:///\\server\\share\\topo.json", + "C:topo.json", + "/home/me/maps/topo.txt", + ] { + assert!(TileLayer::new("", TileKind::Style, path).repair().is_err(), "{path}"); + } + assert!(TileLayer::new("", TileKind::Style, "maps/topo.json").repair().unwrap_err().contains("full path")); + } + #[test] fn runtime_bound_tile_and_legend_addresses_are_web_addresses() { let bound = rustgis_data::login_address::bind("0123456789abcdef", "https://maps.test", "https://maps.test/style.json").unwrap(); @@ -918,6 +992,23 @@ mod tests { } } + /// A style file's encoded `file://` address is checked as the file it names, so it is added + /// and guessed as a style like its decoded form, while a share or a non-`.json` name written + /// encoded is still refused. + #[test] + fn an_encoded_style_file_address_is_checked_as_decoded() { + assert!(style_file_path("file:///maps/%FF.json").is_err()); + assert!(style_file_path("file:///C:topo.json").is_err()); + assert!(style_file_path("file://server/share/topo.json").is_err()); + + assert_eq!(TileKind::guess("file:///maps/topo%2Ejson"), TileKind::Style); + let mut t = TileLayer::new("Topo", TileKind::Style, "file:///maps/topo%2Ejson"); + assert!(t.repair().is_ok(), "{:?}", t.url); + for bad in ["file:///%2F%2Fserver%2Fshare%2Ftopo.json", "file:///maps/topo%2Etxt"] { + assert!(TileLayer::new("Topo", TileKind::Style, bad).repair().is_err(), "{bad}"); + } + } + /// Spaces round a name or an address are trimmed without counting as text shortened; a name /// cut to its limit is counted. #[test] diff --git a/crates/tiles/src/source.rs b/crates/tiles/src/source.rs index 6ed80c1212..af5d9fb5cc 100644 --- a/crates/tiles/src/source.rs +++ b/crates/tiles/src/source.rs @@ -6,6 +6,9 @@ //! step fetches through the cache, so resolving answers [`Resolve::Pending`] until the //! documents have arrived, then the same resolved style every time. +#[cfg(not(target_arch = "wasm32"))] +mod local_style; + use std::collections::HashMap; use std::sync::{Arc, Mutex, OnceLock}; @@ -151,6 +154,8 @@ const MAX_RESOLVED: usize = 64; /// Forgets the resolved styles, so their documents are read again (with [`crate::cache::clear`]). pub(crate) fn forget() { + #[cfg(not(target_arch = "wasm32"))] + local_style::forget(); resolved().lock().unwrap_or_else(|e| e.into_inner()).clear(); } @@ -161,6 +166,19 @@ pub(crate) fn forget_archive(archive: &str) { resolved().lock().unwrap_or_else(|e| e.into_inner()).retain(|key, _| !key.starts_with(&pm) && !key.starts_with(&mb)); } +/// Only desktop local styles periodically reread their backing file. +fn local_style_expired(style: &Resolved) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + style.made.lock().unwrap_or_else(|e| e.into_inner()).elapsed() >= local_style::REFRESH + } + #[cfg(target_arch = "wasm32")] + { + let _ = style; + false + } +} + /// The built-in style for vector tiles without one: it knows the OpenMapTiles, Protomaps and /// Shortbread layer names, and draws water, land use, parks, buildings, roads, boundaries and /// place names from whichever of them the tiles have. @@ -179,6 +197,10 @@ pub fn resolve(spec: &Spec) -> Resolve { mbtiles::check(&spec.url) } else if local { pmtiles::check_local(&spec.url) + } else if spec.kind == Kind::Style && is_local_style(&spec.url) { + // The decoded path: an address writes its own text encoded, so file:///maps/topo%2Ejson + // names the same `.json` file that the reading below opens. + local_path(&spec.url).and_then(|p| pmtiles::check_local_path(&p, "a style file", &["json"])) } else { address::check(&spec.url, None) }; @@ -186,7 +208,9 @@ pub fn resolve(spec: &Spec) -> Resolve { return Resolve::Failed(e); } let cached = resolved().lock().unwrap_or_else(|e| e.into_inner()).get(&key).cloned(); - if let Some(r) = cached.as_ref().filter(|r| r.current()) { + if let Some(r) = + cached.as_ref().filter(|r| r.current() && !(spec.kind == Kind::Style && is_local_style(&spec.url) && local_style_expired(r))) + { return Resolve::Ready(r.clone()); } let anew = resolve_anew(spec, key.clone(), epoch); @@ -225,78 +249,94 @@ fn settle_failure_log(url: &str, err: &str) -> String { /// Reads `spec`'s style and resolves its sources, keeping the result under `key`. fn resolve_anew(spec: &Spec, key: String, epoch: u64) -> Resolve { let mut base = address::Origin::named(&spec.url); - let doc = match spec.kind { - Kind::Raster => raster_style(spec), - Kind::Vector => match vector_style(spec) { - Some(d) => d, - None => return Resolve::Failed("the built-in vector style could not be read".into()), - }, - Kind::Style => match fetch_json(&spec.url, None) { - Ok(Some((d, reached))) => { - base = reached; - d - } + let local = spec.kind == Kind::Style && is_local_style(&spec.url); + let mut style = if local { + #[cfg(not(target_arch = "wasm32"))] + { + base = address::Origin { url: spec.url.clone(), reach: address::Reach::Public }; + } + #[cfg(target_arch = "wasm32")] + return Resolve::Failed("style files on this computer open in the desktop app; give the style's web address here".into()); + #[cfg(not(target_arch = "wasm32"))] + match local_style::get(&spec.url) { + Ok(Some(style)) => (*style).clone(), Ok(None) => return Resolve::Pending, Err(e) => return Resolve::Failed(e), - }, - Kind::PmTiles => match pmtiles::info(&spec.url) { - Ok(Some(info)) => { - let archive = Archive { - tiles: pmtiles::template(&spec.url), - vector: info.tile_type.is_vector(), - min_zoom: info.min_zoom, - max_zoom: info.max_zoom, - attribution: info.attribution(), - layers: info.vector_layers().to_vec(), - }; - match archive_style(spec, archive) { - Some(d) => d, - None => return Resolve::Failed("the built-in vector style could not be read".into()), + } + } else { + let doc = match spec.kind { + Kind::Raster => raster_style(spec), + Kind::Vector => match vector_style(spec) { + Some(d) => d, + None => return Resolve::Failed("the built-in vector style could not be read".into()), + }, + Kind::Style => match fetch_json(&spec.url, None) { + Ok(Some((d, reached))) => { + base = reached; + d } - } - Ok(None) => return Resolve::Pending, - Err(e) => return Resolve::Failed(crate::logins::scrub(&rustgis_data::diagnostics::message_with_address(&spec.url, &e))), - }, - Kind::Cog => match cog::info(&spec.url) { - Ok(Some(info)) => { - let archive = Archive { - tiles: cog::template(&spec.url), - vector: false, - min_zoom: info.min_zoom, - max_zoom: info.max_zoom, - attribution: String::new(), - layers: Vec::new(), - }; - match archive_style(spec, archive) { - Some(d) => d, - None => return Resolve::Failed("the raster style could not be made".into()), + Ok(None) => return Resolve::Pending, + Err(e) => return Resolve::Failed(e), + }, + Kind::PmTiles => match pmtiles::info(&spec.url) { + Ok(Some(info)) => { + let archive = Archive { + tiles: pmtiles::template(&spec.url), + vector: info.tile_type.is_vector(), + min_zoom: info.min_zoom, + max_zoom: info.max_zoom, + attribution: info.attribution(), + layers: info.vector_layers().to_vec(), + }; + match archive_style(spec, archive) { + Some(d) => d, + None => return Resolve::Failed("the built-in vector style could not be read".into()), + } } - } - Ok(None) => return Resolve::Pending, - Err(e) => return Resolve::Failed(e), - }, - Kind::MbTiles => match mbtiles::info_ready(&spec.url, web_time::Duration::ZERO) { - Ok(Some(info)) => { - let archive = Archive { - tiles: mbtiles::template(&spec.url), - vector: info.format.is_vector(), - min_zoom: info.min_zoom, - max_zoom: info.max_zoom, - attribution: info.attribution.clone(), - layers: info.vector_layers().to_vec(), - }; - match archive_style(spec, archive) { - Some(d) => d, - None => return Resolve::Failed("the built-in vector style could not be read".into()), + Ok(None) => return Resolve::Pending, + Err(e) => return Resolve::Failed(crate::logins::scrub(&rustgis_data::diagnostics::message_with_address(&spec.url, &e))), + }, + Kind::Cog => match cog::info(&spec.url) { + Ok(Some(info)) => { + let archive = Archive { + tiles: cog::template(&spec.url), + vector: false, + min_zoom: info.min_zoom, + max_zoom: info.max_zoom, + attribution: String::new(), + layers: Vec::new(), + }; + match archive_style(spec, archive) { + Some(d) => d, + None => return Resolve::Failed("the raster style could not be made".into()), + } } - } - Ok(None) => return Resolve::Pending, - Err(e) => return Resolve::Failed(e), - }, - }; - let mut style = match Style::parse(&doc) { - Ok(s) => s, - Err(e) => return Resolve::Failed(crate::logins::scrub(&rustgis_data::diagnostics::message_with_address(&spec.url, &e))), + Ok(None) => return Resolve::Pending, + Err(e) => return Resolve::Failed(e), + }, + Kind::MbTiles => match mbtiles::info_ready(&spec.url, web_time::Duration::ZERO) { + Ok(Some(info)) => { + let archive = Archive { + tiles: mbtiles::template(&spec.url), + vector: info.format.is_vector(), + min_zoom: info.min_zoom, + max_zoom: info.max_zoom, + attribution: info.attribution.clone(), + layers: info.vector_layers().to_vec(), + }; + match archive_style(spec, archive) { + Some(d) => d, + None => return Resolve::Failed("the built-in vector style could not be read".into()), + } + } + Ok(None) => return Resolve::Pending, + Err(e) => return Resolve::Failed(e), + }, + }; + match Style::parse(&doc) { + Ok(s) => s, + Err(e) => return Resolve::Failed(crate::logins::scrub(&rustgis_data::diagnostics::message_with_address(&spec.url, &e))), + } }; if !spec.hidden_layers.is_empty() { style.layers.retain(|l| l.source_layer.as_ref().is_none_or(|s| !spec.hidden_layers.contains(s))); @@ -610,6 +650,55 @@ pub fn archive_holds_vectors(kind: Kind, url: &str) -> Result, Stri } } +/// The largest style document read from a file: far more than any published style. +#[cfg(not(target_arch = "wasm32"))] +const MAX_LOCAL_STYLE: u64 = 32 << 20; + +/// Whether a style's address is a file on this computer rather than a web address (as +/// `rustgis_map::tiles::is_local_style` decides it, which a layer's address went through). +pub fn is_local_style(url: &str) -> bool { + if !pmtiles::is_local(url) { + return false; + } + let p = url.strip_prefix("file://").unwrap_or(url); + let drive = p.as_bytes().get(1) == Some(&b':') && p.as_bytes().first().is_some_and(u8::is_ascii_alphabetic); + url.starts_with("file://") || p.starts_with('/') || p.starts_with('\\') || drive +} + +/// The path a style's address names on this computer. A `file://` address is percent-decoded, as +/// RFC 8089 writes a file name's spaces and the like encoded, so `file:///maps/topo%20style.json` +/// reads `/maps/topo style.json`; a path the user typed is its own text, `%` and all. The slash a +/// `file://` address puts before a Windows drive isn't part of the path (as +/// `rustgis_map::paths::local_path` has it). +fn local_path(url: &str) -> Result { + rustgis_data::address::local_file_path(url).map_err(str::to_string) +} + +/// Reads a bounded `.json` document on the style worker. One OS read and JSON parse cannot +/// be interrupted; the worker checks cancellation before reading and after parsing. +#[cfg(not(target_arch = "wasm32"))] +fn read_local_style(path: &str) -> Result { + let p = local_path(path)?; + pmtiles::check_local_path(&p, "a style file", &["json"])?; + let too_big = || format!("{p}: a style file is at most {} MB", MAX_LOCAL_STYLE >> 20); + let len = std::fs::metadata(&p).map_err(|e| format!("{p}: {e}"))?.len(); + if len > MAX_LOCAL_STYLE { + return Err(too_big()); + } + // Read no more than the limit allows, however large the file has grown since it was measured. + let mut text = Vec::new(); + let file = std::fs::File::open(&p).map_err(|e| format!("{p}: {e}"))?; + std::io::Read::read_to_end(&mut std::io::Read::take(file, MAX_LOCAL_STYLE + 1), &mut text).map_err(|e| format!("{p}: {e}"))?; + if text.len() as u64 > MAX_LOCAL_STYLE { + return Err(too_big()); + } + let doc: Value = serde_json::from_slice(&text).map_err(|e| format!("{p}: not a JSON document ({e})"))?; + if !doc.is_object() { + return Err(format!("{p}: a MapLibre style is a JSON object")); + } + Ok(doc) +} + /// The document at `url`: `Ok(None)` while it is on its way. fn fetch_json(url: &str, from: Option<&address::Origin>) -> Result, String> { match cache::document(url, from) { @@ -934,6 +1023,139 @@ mod tests { } } + /// A MapLibre style saved on this computer (#2388) is read from its file, without a web + /// server, and its sources' web addresses are fetched as a web style's are. A file that + /// isn't there, isn't a style or isn't given by its full path says why. + #[test] + fn a_style_file_on_this_computer_resolves_its_web_sources() { + /// Waits on counted I/O, matching the export path rather than assuming an immediate read. + fn settled(spec: &Spec) -> Resolve { + for _ in 0..4 { + match super::resolve(spec) { + Resolve::Pending => cache::wait(std::time::Duration::from_secs(2)), + result => return result, + } + } + panic!("local style did not settle after counted reads"); + } + + let _turn = cache::turn(); + let tilejson = "https://local-style.example/tiles.json"; + cache::set_fetcher(move |url, done| { + done(Ok(if url == tilejson { + json!({"tiles": ["https://local-style.example/{z}/{x}/{y}.pbf"], "attribution": "Basemap"}) + } else { + json!({}) + } + .to_string() + .into_bytes())); + }); + let dir = std::env::temp_dir().join(format!("rustgis-local-style-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // A `#` in the name is part of it, not a fragment of an address. + let file = dir.join("topo #50k.json"); + let style = json!({ + "version": 8, + "sources": {"v": {"type": "vector", "url": tilejson}}, + "layers": [ + {"id": "bg", "type": "background", "paint": {"background-color": "#fff"}}, + {"id": "roads", "type": "line", "source": "v", "source-layer": "roads"} + ] + }); + std::fs::write(&file, style.to_string()).unwrap(); + let path = file.display().to_string(); + assert!(is_local_style(&path), "{path}"); + let mut ready = None; + for _ in 0..3 { + match resolve(&spec(Kind::Style, &path)) { + Resolve::Ready(r) => { + ready = Some(r); + break; + } + Resolve::Pending => cache::wait(std::time::Duration::from_secs(2)), + Resolve::Failed(e) => panic!("{path}: {e}"), + } + } + let r = ready.expect("the style file resolves"); + assert_eq!(r.style.layers.len(), 2); + match r.style.sources.first().map(|s| &s.1) { + Some(Source::Vector { tiles, .. }) => assert_eq!(tiles, &["https://local-style.example/{z}/{x}/{y}.pbf"]), + _ => panic!("no vector source"), + } + // A `file://` address reads the file it names, a space in the name written encoded. + let spaced = dir.join("topo style.json"); + std::fs::write(&spaced, style.to_string()).unwrap(); + let shown = spaced.display().to_string(); + let uri = if cfg!(windows) { + format!("file:///{}", shown.replace('\\', "/").replace(' ', "%20")) + } else { + format!("file://{}", shown.replace(' ', "%20")) + }; + let Resolve::Ready(r) = settled(&spec(Kind::Style, &uri)) else { panic!("{uri} must resolve") }; + assert_eq!(r.style.layers.len(), 2); + // An encoded extension names the same file: the first check reads the decoded path too. + let stem = uri.strip_suffix(".json").expect("the address ends in .json"); + let dotted = format!("{stem}%2Ejson"); + let Resolve::Ready(r) = settled(&spec(Kind::Style, &dotted)) else { panic!("{dotted} must resolve") }; + assert_eq!(r.style.layers.len(), 2); + // A network share written encoded into a `file://` address is refused once decoded. + let hidden = "file:///%2F%2Fserver%2Fshare%2Ftopo.json"; + assert!(matches!(settled(&spec(Kind::Style, hidden)), Resolve::Failed(_))); + // What can't be drawn says so, with the file it is about. + let missing = dir.join("gone.json").display().to_string(); + let Resolve::Failed(e) = settled(&spec(Kind::Style, &missing)) else { panic!("a missing file must fail") }; + assert!(e.contains("gone.json"), "{e}"); + let array = dir.join("array.json"); + std::fs::write(&array, "[]").unwrap(); + let Resolve::Failed(e) = settled(&spec(Kind::Style, &array.display().to_string())) else { panic!("not a style") }; + assert!(e.contains("JSON object"), "{e}"); + let text = dir.join("style.txt"); + std::fs::write(&text, style.to_string()).unwrap(); + let Resolve::Failed(e) = settled(&spec(Kind::Style, &text.display().to_string())) else { panic!("not a .json file") }; + assert!(e.contains(".json"), "{e}"); + // A relative path is judged as a web address, and refused as one. + assert!(!is_local_style("styles/topo.json")); + assert!(matches!(settled(&spec(Kind::Style, "styles/topo.json")), Resolve::Failed(_))); + // Windows reads mixed separators as a share too, and `C:topo.json` from the drive's current folder. + for path in ["/\\server\\share\\topo.json", "\\/server/share/topo.json", "file:///\\server\\share\\topo.json", "C:topo.json"] { + assert!(pmtiles::check_local_path(path, "a style file", &["json"]).is_err(), "{path}"); + assert!(matches!(settled(&spec(Kind::Style, path)), Resolve::Failed(_)), "{path}"); + } + for path in ["C:\\Maps\\topo.json", "C:/Maps/topo.json", "/home/me/maps/topo.json"] { + assert!(pmtiles::check_local_path(path, "a style file", &["json"]).is_ok(), "{path}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// A `file://` address names its file by encoded text (RFC 8089): it is decoded before the + /// file is checked and read, and the slash before a Windows drive dropped, while a path the + /// user typed is its own text. + #[test] + fn a_file_address_names_the_path_it_encodes() { + assert!(local_path("file:///home/me/%FF.json").is_err()); + assert!(local_path("file:///C:topo.json").is_err()); + assert!(local_path("file://server/share/topo.json").is_err()); + for (written, read) in [ + ("/home/me/maps/topo.json", "/home/me/maps/topo.json"), + ("/home/me/maps/100% plain.json", "/home/me/maps/100% plain.json"), + ("C:\\Maps\\topo.json", "C:\\Maps\\topo.json"), + ("file:///home/me/maps/topo%20style.json", "/home/me/maps/topo style.json"), + ("file:///home/me/maps/day%23night.json", "/home/me/maps/day#night.json"), + ("file:///home/me/100%25ish.json", "/home/me/100%ish.json"), + // Not an escape: it stays as written. + ("file:///home/me/a%zz.json", "/home/me/a%zz.json"), + ("file:///C:/Maps/topo%20style.json", "C:/Maps/topo style.json"), + ("file:///C:\\Maps\\topo.json", "C:\\Maps\\topo.json"), + ("file:///home/me/maps/topo%2Ejson", "/home/me/maps/topo.json"), + ] { + assert_eq!(local_path(written).unwrap(), read, "{written}"); + } + // A share written encoded, or with the extra slash, is a share once decoded. + for share in ["file:////server/share/topo.json", "file:///%2F%2Fserver%2Fshare%2Ftopo.json"] { + assert!(local_path(share).is_err(), "{share}"); + } + } + /// A tile layer of one source that names its credit is credited with that alone, not again /// in its TileJSON's wording (#2244); one that names none takes its TileJSON's. A style's /// sources keep their credits beside the layer's. diff --git a/crates/tiles/src/source/local_style.rs b/crates/tiles/src/source/local_style.rs new file mode 100644 index 0000000000..e0847269d7 --- /dev/null +++ b/crates/tiles/src/source/local_style.rs @@ -0,0 +1,234 @@ +//! Bounded asynchronous reads of local styles. Parsed styles survive pending TileJSON fetches. + +use super::*; +use web_time::Duration; + +type Answer = Arc, String>>>>; +struct Read { + started: Instant, + used: Instant, + answer: Answer, +} +type Reads = HashMap; +const MAX_READS: usize = 4; +const MAX_STYLES: usize = super::MAX_RESOLVED; +pub(super) const REFRESH: Duration = Duration::from_secs(60); + +/// Worker reservations outlive cache refreshes, including reads stuck in the operating system. +fn active() -> &'static Mutex<[Option; MAX_READS]> { + static ACTIVE: Mutex<[Option; MAX_READS]> = Mutex::new([None; MAX_READS]); + &ACTIVE +} + +/// Releases the reserved slot even if a cancellation callback panics or spawning fails. +struct Slot(usize); +impl Slot { + /// Reserve a worker and record its start independently of the document it may produce. + fn reserve() -> Option { + let mut workers = active().lock().unwrap_or_else(|e| e.into_inner()); + let (index, started) = workers.iter_mut().enumerate().find(|(_, started)| started.is_none())?; + *started = Some(Instant::now()); + Some(Self(index)) + } +} +impl Drop for Slot { + fn drop(&mut self) { + if let Some(started) = active().lock().unwrap_or_else(|e| e.into_inner()).get_mut(self.0) { + *started = None; + } + } +} + +fn reads() -> &'static Mutex { + static READS: OnceLock> = OnceLock::new(); + READS.get_or_init(Mutex::default) +} + +/// Refresh drops retained documents. Detached completions only update their own answer cell. +pub(super) fn forget() { + reads().lock().unwrap_or_else(|e| e.into_inner()).clear(); +} + +/// Removes only this read, preserving a replacement created by a cache refresh. +fn remove(path: &str, answer: &Answer) { + let mut all = reads().lock().unwrap_or_else(|e| e.into_inner()); + if all.get(path).is_some_and(|read| Arc::ptr_eq(&read.answer, answer)) { + all.remove(path); + } +} + +/// Reads and parses on a counted worker; at most four files can occupy storage threads. +/// Refreshes once a minute or on the map's explicit cache refresh, without filesystem I/O here. +pub(super) fn get(path: &str) -> Result>, String> { + let mut all = reads().lock().unwrap_or_else(|e| e.into_inner()); + if let Some(read) = all.get_mut(path) { + read.used = Instant::now(); + let result = read.answer.lock().unwrap_or_else(|e| e.into_inner()); + if result.is_none() { + return if read.started.elapsed() > Duration::from_secs(30) { + Err(format!("{path}: the style file read has not answered within 30 seconds")) + } else { + Ok(None) + }; + } + if read.started.elapsed() < REFRESH { + return result.clone().transpose(); + } + } + // Prefer keeping the styles being drawn; never evict a read still under way. + if all.len() >= MAX_STYLES && !all.contains_key(path) { + let oldest = all + .iter() + .filter(|(_, read)| read.answer.lock().unwrap_or_else(|e| e.into_inner()).is_some()) + .min_by_key(|(_, read)| read.used) + .map(|(path, _)| path.clone()); + if let Some(oldest) = oldest { + all.remove(&oldest); + } else { + return Ok(None); + } + } + let Some(slot) = Slot::reserve() else { + let stalled = + active().lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().any(|started| started.elapsed() > Duration::from_secs(30)); + return if stalled { + Err("style file reads are occupied by stalled storage; retry after storage responds".into()) + } else { + Ok(None) + }; + }; + let answer: Answer = Arc::new(Mutex::new(None)); + all.insert(path.to_string(), Read { started: Instant::now(), used: Instant::now(), answer: answer.clone() }); + let name = path.to_string(); + let still = cache::current_still(); + let counted = cache::Counted::start(); + drop(all); + let worker_answer = answer.clone(); + let worker_name = name.clone(); + let worker_still = still.clone(); + let spawned = std::thread::Builder::new().name("rustgis-style-file".into()).spawn(move || { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + cache::with_optional_still(worker_still, || { + cache::check_still(&cache::current_still())?; + let doc = super::read_local_style(&name)?; + cache::check_still(&cache::current_still())?; + let style = Style::parse(&doc)?; + cache::check_still(&cache::current_still())?; + Ok(Arc::new(style)) + }) + })) + .unwrap_or_else(|_| Err("the style file reader could not finish".into())); + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cache::check_still(&still).is_ok())).unwrap_or(false) { + *worker_answer.lock().unwrap_or_else(|e| e.into_inner()) = Some(result); + } else { + remove(&worker_name, &worker_answer); + } + drop(slot); + drop(counted); + }); + if let Err(error) = spawned { + let error = format!("could not start a style file read: {error}"); + remove(path, &answer); + return Err(error); + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Reloading drops documents, but cannot make occupied storage workers young or free again. + #[test] + fn stalled_workers_still_report_an_error_after_refresh() { + let _turn = cache::turn(); + super::forget(); + let slots: Vec<_> = (0..MAX_READS).map(|_| Slot::reserve().unwrap()).collect(); + let started = Instant::now() - Duration::from_secs(31); + active().lock().unwrap().fill(Some(started)); + for i in 0..MAX_READS { + reads() + .lock() + .unwrap() + .insert(format!("stalled-{i}.json"), Read { started, used: started, answer: Arc::new(Mutex::new(None)) }); + } + assert!(get("another.json").unwrap_err().contains("stalled storage")); + super::forget(); + assert!(get("another.json").unwrap_err().contains("stalled storage")); + assert!(Slot::reserve().is_none(), "refresh does not allow a fifth worker"); + drop(slots); + assert!(Slot::reserve().is_some(), "a finished worker releases its reservation"); + } + + #[test] + fn older_finished_styles_do_not_exhaust_the_session_cache() { + let _turn = cache::turn(); + super::forget(); + let dir = std::env::temp_dir().join(format!("rustgis-style-eviction-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for i in 0..=MAX_STYLES { + let path = dir.join(format!("{i}.json")); + std::fs::write(&path, r#"{"version":8,"sources":{},"layers":[]}"#).unwrap(); + let name = path.display().to_string(); + assert!(get(&name).unwrap().is_none()); + cache::wait(std::time::Duration::from_secs(2)); + assert!(get(&name).unwrap().is_some(), "style {i} loads after earlier projects"); + } + assert_eq!(reads().lock().unwrap().len(), MAX_STYLES); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// More files than worker slots retain their parsed documents while sources are pending. + #[test] + fn five_styles_reuse_their_documents_and_cancelled_reads_do_not_poison_other_callers() { + let _turn = cache::turn(); + super::forget(); + let dir = std::env::temp_dir().join(format!("rustgis-five-styles-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut names = Vec::new(); + for i in 0..5 { + let path = dir.join(format!("{i}.json")); + std::fs::write(&path, r#"{"version":8,"sources":{},"layers":[]}"#).unwrap(); + let name = path.display().to_string(); + assert!(get(&name).unwrap().is_none()); + cache::wait(std::time::Duration::from_secs(2)); + assert!(get(&name).unwrap().is_some()); + std::fs::remove_file(&path).unwrap(); + names.push(name); + } + for name in names { + assert!(get(&name).unwrap().is_some()); + } + super::forget(); + let path = dir.join("retry.json"); + std::fs::write(&path, r#"{"version":8,"sources":{},"layers":[]}"#).unwrap(); + let name = path.display().to_string(); + cache::with_still(Arc::new(|| false), || assert!(get(&name).unwrap().is_none())); + cache::wait(std::time::Duration::from_secs(2)); + assert!(get(&name).unwrap().is_none(), "a live caller retries the cancelled read"); + cache::wait(std::time::Duration::from_secs(2)); + assert!(get(&name).unwrap().is_some()); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn parsed_style_is_retained_until_refresh_and_refresh_reads_again() { + let _turn = cache::turn(); + super::forget(); + let dir = std::env::temp_dir().join(format!("rustgis-local-style-cache-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("style.json"); + std::fs::write(&path, r#"{"version":8,"sources":{},"layers":[]}"#).unwrap(); + let name = path.to_str().unwrap(); + assert!(get(name).unwrap().is_none()); + cache::wait(std::time::Duration::from_secs(2)); + let first = get(name).unwrap().expect("counted read completed"); + std::fs::remove_file(&path).unwrap(); + assert_eq!(get(name).unwrap().unwrap(), first, "pending source polls reuse the parsed style"); + super::forget(); + assert!(get(name).unwrap().is_none()); + cache::wait(std::time::Duration::from_secs(2)); + assert!(get(name).unwrap_err().contains("style.json")); + std::fs::remove_dir(&dir).unwrap(); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 81ceedd9d0..87169e751e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2817,7 +2817,7 @@ fn gpkg_discard(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { /// Add Tile Layer: an XYZ/TMS/WMS template, vector tiles or a MapLibre style by address. fn add_tiles(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { use rustgis_engine::map::TileKind; - ui.label(egui::RichText::new(tl!("A tile service's address: raster tiles with {z}/{x}/{y} (or {-y}, {q}, {bbox-epsg-3857} for WMS), vector tiles (.pbf) or TileJSON, a MapLibre style, a PMTiles archive (a web address, or a file on this computer), or an MBTiles file on this computer.")).weak()); + ui.label(egui::RichText::new(tl!("A tile service's address: raster tiles with {z}/{x}/{y} (or {-y}, {q}, {bbox-epsg-3857} for WMS), vector tiles (.pbf) or TileJSON, a MapLibre style (a web address, or a .json file on this computer), a PMTiles archive (a web address, or a file on this computer), or an MBTiles file on this computer.")).weak()); egui::Grid::new("tiles").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| { ui.label(tl!("Address")); ui.horizontal(|ui| { @@ -2835,6 +2835,15 @@ fn add_tiles(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { app.dialogs.mode = if path.to_ascii_lowercase().ends_with(".mbtiles") { "mbtiles" } else { "pmtiles" }; app.dialogs.text = path; } + // A MapLibre style saved on this computer, such as one exported from a style editor + // (#2388): its tiles still come from the web addresses it names. + if !cfg!(target_arch = "wasm32") + && ui.button(tl!("Style File…")).on_hover_text(tl!("A MapLibre style (.json) on this computer.")).clicked() + && let Some(path) = pick_open(&["json"], tl!("MapLibre style")) + { + app.dialogs.mode = "style"; + app.dialogs.text = path; + } }); ui.end_row(); let input_label = ui.label(tl!("Type")); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 4f8f5b9c51..505c64d42b 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -722,7 +722,7 @@ were rounded, and Export Raster, which writes the rounded values, says so again. | --- | --- | --- | --- | | Raster tiles | XYZ/TMS template (`{z}/{x}/{y}`, `{-y}`, `{s}`, `{q}`), WMS (`{bbox-epsg-3857}`) | Home › Add › Basemap › Add Tile Layer | PNG, JPEG and WebP. | | Vector tiles | Mapbox Vector Tiles (`.pbf`, `.mvt`) template, or TileJSON | Add Tile Layer | Drawn in a built-in style that knows the OpenMapTiles, Protomaps and Shortbread schemas. | -| MapLibre styles | `style.json` | Add Tile Layer | A supported subset of vector and raster sources, sprites, expressions and zoom functions; see [Maps and Basemaps](maps.md#basemaps) for styling limits. | +| MapLibre styles | `style.json`: a web address, or a desktop file | Add Tile Layer (or **Style File…**) | A supported subset of vector and raster sources, sprites, expressions and zoom functions; see [Maps and Basemaps](maps.md#basemaps) for styling limits. | | PMTiles | `.pmtiles`: a web address, or a desktop file | Add Tile Layer (or **Tile Archive File…**), Add Data, or drop a local file on desktop | Version 3 archives only: PNG, JPEG or WebP rasters, or MVT vectors; uncompressed, gzip, Brotli or Zstandard. Read a tile at a time by byte ranges (CORS on the web). Browser local-file uploads aren't supported; use an archive's web address. The map moves to the archive's bounds, except a world archive. Vector archives use the built-in basemap style, or a colour per layer when added as an overlay. | | MBTiles | `.mbtiles`: a file | Add Data, drop the file, Add Tile Layer's **Tile Archive File…** button, or upload in the web app | Raster (PNG, JPEG, WebP) or vector tiles, as its metadata says, drawn as PMTiles archives are. The desktop reads the file in place, a tile at a time; on Windows the file can't be moved or deleted while a map draws it, until its layer is removed. The web app reads an upload into memory (the plain `tiles` table and the deduplicated layouts of mbutil, TileMill and Planetiler) and keeps it for the session: a project saved there asks for the file again. | diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index c03e108b67..6e2f930b4f 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -557,7 +557,13 @@ colour off, as that basemap draws its own colours: the desktop read in place a tile at a time (**Tile Archive File…**, Add Data, or drop it on the window); in the web app added with Add Data and held in memory for the session (a project keeps the layer, and asks for the file again). -- **Map styles**: a MapLibre style document (`style.json`), with its vector, raster and +- **Map styles**: a MapLibre style document (`style.json`) by its web address or, on the desktop, + a `.json` file on this computer (**Style File…**, for one exported from a style editor such as + Maputnik; the project keeps its path, and a file that can no longer be read says why when the map + draws it). Local styles are read and parsed off the drawing thread, kept while sources load, + and read again after a cache refresh or at most once a minute. Their referenced addresses + must be on the public internet; relative paths and local-network services are refused. + Styles can contain vector, raster and elevation (`raster-dem`: Terrarium, Mapbox or custom encoding) sources. RustGIS draws background, fill, line, circle and raster layers, labels with their icons from the style's sprites (SDF icons in their `icon-color`; the icons of a sprite in the style's diff --git a/schema/fixtures/tile_style_file.rgis b/schema/fixtures/tile_style_file.rgis new file mode 100644 index 0000000000..5f4f4b2317 --- /dev/null +++ b/schema/fixtures/tile_style_file.rgis @@ -0,0 +1,29 @@ +{ + "format": 2, + "name": "Local style", + "requires": [ + "tile-style-file" + ], + "maps": [ + { + "name": "Map", + "layers": [], + "basemap": "Paper", + "camera": { + "center": { + "x": 0, + "y": 0 + }, + "res": 30000 + }, + "tiles": [ + { + "name": "Local style", + "kind": "style", + "url": "/data/maps/style.json" + } + ] + } + ], + "active_map": 0 +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 86064375ca..3694c0b707 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1257,6 +1257,7 @@ "terrain-block-walls-top", "shaded-relief-effects", "normalized-legend-urls", + "tile-style-file", "field-origin", "slope-percent", "shaded-relief-light", @@ -1407,6 +1408,7 @@ "terrain-block-walls-top", "shaded-relief-effects", "normalized-legend-urls", + "tile-style-file", "field-origin", "slope-percent", "shaded-relief-light",