Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions crates/data/src/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, &'static str> {
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()
Expand Down
73 changes: 70 additions & 3 deletions crates/engine/src/cmd/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,13 +217,13 @@ fn build_package(
};
let mut entries: Vec<(String, Vec<u8>)> = 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 {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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());
Expand All @@ -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);
Expand All @@ -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()) {
Expand All @@ -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)),
}
Expand All @@ -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
Expand Down Expand Up @@ -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");
Expand Down
21 changes: 20 additions & 1 deletion crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ fn left_linked<'a>(what: &str, maps: impl IntoIterator<Item = &'a Map>) -> 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)
Expand Down Expand Up @@ -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());
}
}
8 changes: 6 additions & 2 deletions crates/engine/src/cmd/tiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const TILE_ROLES: &[crate::ParamRole] = &[crate::ParamRole { key: "legend", role
pub fn commands() -> Vec<C> {
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)"#),
Expand Down Expand Up @@ -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<TileKind, String> {
pub(crate) fn add_kind(p: &Value, url: &str) -> Result<TileKind, String> {
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)),
Expand All @@ -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,
}
}
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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));
}
}
Expand Down
Loading
Loading