Skip to content
Merged
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
98 changes: 98 additions & 0 deletions crates/data/src/ogc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,55 @@ fn wfs(url: &str, root: &Node) -> Service {
service
}

// ---------------------------------------------------------------------------------------------
// Features over an area

/// Query parameters that already filter a request by place or by feature, or that name another
/// coordinate system for a box (OGC API's `bbox-crs`): an address carrying one is left as it is.
const SPATIAL_KEYS: [&str; 7] = ["bbox", "bbox-crs", "filter", "cql_filter", "featureid", "resourceid", "geometry"];

/// An [`Offer::Features`] address that asks only for the features crossing a longitude/latitude
/// `area` (west, south, east, north), in each service's own terms:
/// - a WFS 1.1 or 2.0 GetFeature: `BBOX` in CRS84 (longitude first) when its `SRSNAME` is
/// CRS84, else in `urn:ogc:def:crs:EPSG::4326`, latitude first as that URN fixes (a bare
/// `EPSG:4326` is read either way by different servers);
/// - an ArcGIS layer's query: an envelope in EPSG:4326 that the features intersect;
/// - an OGC API collection's items: `bbox`, longitude first by the standard (its `next` links
/// keep it).
///
/// `None` when the request can't carry the box: a WFS 1.0 GetFeature (its `BBOX` is in the
/// type's own coordinate system, which its capabilities may not give as longitude/latitude), an
/// address that already filters, or an area across the antimeridian or off the globe.
pub fn features_in_area(url: &str, area: [f64; 4]) -> Option<String> {
let [w, s, e, n] = area;
let lon = |x: f64| (-180.0..=180.0).contains(&x);
let lat = |y: f64| (-90.0..=90.0).contains(&y);
if !(lon(w) && lon(e) && lat(s) && lat(n) && w <= e && s <= n) {
return None;
}
if SPATIAL_KEYS.iter().any(|k| query_value(url, k).is_some()) {
return None;
}
let is = |key: &str, value: &str| query_value(url, key).is_some_and(|v| v.eq_ignore_ascii_case(value));
let q = if is("service", "wfs") && is("request", "getfeature") {
if query_value(url, "version").is_none_or(|v| v.starts_with("1.0")) {
return None;
}
if query_value(url, "srsname").is_some_and(is_crs84) {
format!("BBOX={w},{s},{e},{n},urn:ogc:def:crs:OGC:1.3:CRS84")
} else {
format!("BBOX={s},{w},{n},{e},urn:ogc:def:crs:EPSG::4326")
}
} else if is_arcgis_query(url) {
format!("geometry={w},{s},{e},{n}&geometryType=esriGeometryEnvelope&inSR=4326&spatialRel=esriSpatialRelIntersects")
} else if base(url).trim_end_matches('/').ends_with("/items") {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
format!("bbox={w},{s},{e},{n}")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else {
return None;
};
Some(with_query(url, &q))
}

// ---------------------------------------------------------------------------------------------
// WCS

Expand Down Expand Up @@ -2321,6 +2370,55 @@ mod tests {
assert!(s.notes.iter().any(|n| n.contains("1 collections")));
}

#[test]
fn features_asked_for_over_an_area() {
let piaui = [-45.99, -10.93, -40.37, -2.74];
let offered = |caps: &str, body: &str| {
let s = parse(caps, body.as_bytes()).unwrap();
let Offer::Features { url } = &s.layers[0].offer else { panic!("{:?}", s.layers[0].offer) };
url.clone()
};
// WFS 2.0 offering CRS84: the box in CRS84, longitude first.
let v20 = r#"<WFS_Capabilities version="2.0.0"><FeatureTypeList><FeatureType><Name>CGMAT:munic</Name><DefaultCRS>urn:ogc:def:crs:EPSG::4674</DefaultCRS><OtherCRS>urn:ogc:def:crs:OGC:1.3:CRS84</OtherCRS></FeatureType></FeatureTypeList></WFS_Capabilities>"#;
let url = offered("https://x.org/geoserver/wfs", v20);
assert_eq!(features_in_area(&url, piaui).unwrap(), format!("{url}&BBOX=-45.99,-10.93,-40.37,-2.74,urn:ogc:def:crs:OGC:1.3:CRS84"));
// WFS 1.1 without CRS84: latitude first, as urn:ogc:def:crs:EPSG::4326 fixes.
let v11 = r#"<WFS_Capabilities version="1.1.0"><FeatureTypeList><FeatureType><Name>a</Name><DefaultSRS>urn:ogc:def:crs:EPSG::4326</DefaultSRS></FeatureType></FeatureTypeList></WFS_Capabilities>"#;
let url = offered("https://x.org/wfs", v11);
assert_eq!(features_in_area(&url, piaui).unwrap(), format!("{url}&BBOX=-10.93,-45.99,-2.74,-40.37,urn:ogc:def:crs:EPSG::4326"));
// WFS 1.0 reads its box in the type's own coordinate system: not asked.
let v10 = r#"<WFS_Capabilities version="1.0.0"><FeatureTypeList><FeatureType><Name>roads</Name><SRS>EPSG:4326</SRS></FeatureType></FeatureTypeList></WFS_Capabilities>"#;
assert_eq!(features_in_area(&offered("https://old.example.org/wfs", v10), piaui), None);
// ArcGIS: an envelope in EPSG:4326, kept by the pages that follow (they add to the query).
let arcgis = r#"{"currentVersion": 11.1, "layers": [{"id": 0, "name": "Parcels"}]}"#;
let url = offered("https://x.org/arcgis/rest/services/A/FeatureServer", arcgis);
let asked = features_in_area(&url, piaui).unwrap();
assert_eq!(
asked,
format!(
"{url}&geometry=-45.99,-10.93,-40.37,-2.74&geometryType=esriGeometryEnvelope&inSR=4326&spatialRel=esriSpatialRelIntersects"
)
);
assert!(arcgis_page_url(&asked, 2, 2, Some("FID")).contains("&geometry=-45.99,-10.93,-40.37,-2.74&"));
// OGC API Features: bbox, longitude first, before a fragment.
assert_eq!(
features_in_area("https://api.example.org/collections/a/items?limit=10000&f=json#x", piaui).unwrap(),
"https://api.example.org/collections/a/items?limit=10000&f=json&bbox=-45.99,-10.93,-40.37,-2.74#x"
);
assert_eq!(
features_in_area("https://api.example.org/collections/a/items", [-1.5, 0.0, 2.0, 1e-7]).unwrap(),
"https://api.example.org/collections/a/items?bbox=-1.5,0,2,0.0000001"
);
// Across the antimeridian, off the globe, already filtered, or not a feature request.
assert_eq!(features_in_area("https://api.example.org/collections/a/items", [170.0, -20.0, -170.0, -10.0]), None);
assert_eq!(features_in_area("https://api.example.org/collections/a/items", [-200.0, -20.0, 10.0, 95.0]), None);
assert_eq!(features_in_area("https://api.example.org/collections/a/items?bbox=1,2,3,4", piaui), None);
let other_crs = "https://api.example.org/collections/a/items?bbox-crs=http://www.opengis.net/def/crs/EPSG/0/31983";
assert_eq!(features_in_area(other_crs, piaui), None);
assert_eq!(features_in_area(&format!("{}&CQL_FILTER=uf%3D'PI'", offered("https://x.org/wfs", v11)), piaui), None);
assert_eq!(features_in_area("https://x.org/data.geojson", piaui), None);
}

#[test]
fn wfs_versions_and_axes() {
// WFS 1.0: onlineResource, TYPENAME and MAXFEATURES.
Expand Down
51 changes: 45 additions & 6 deletions crates/engine/src/cmd/service.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Web map and feature services: connect to a WMS, WMTS, WFS, WCS, OGC API Features or ArcGIS
//! REST service, list what it offers (from its capabilities), and add a layer — map layers as
//! tile layers, feature types and collections as data downloaded as GeoJSON, coverages as rasters
//! tile layers, feature types and collections as data downloaded as GeoJSON (the whole layer, or
//! the features crossing an area), coverages as rasters
//! (a GeoTIFF of the view from GetCoverage). And search a catalogue (CSW) for records and the
//! services and files they link to.
//!
Expand All @@ -26,7 +27,7 @@ pub fn commands() -> Vec<C> {
r#"{"url": "a WMS, WMTS or WFS address (GetCapabilities is added), an OGC API collections address or landing page (its map tiles and linked collections), or an ArcGIS FeatureServer, MapServer, ImageServer or VectorTileServer, or an ArcGIS services directory or folder (its folders and services, each listed by its own url)", "type"?: "wms"|"wmts"|"wfs"|"ogcapi"|"arcgis" (guessed from the address), "text"?: "the capabilities document, when already fetched", "documents"?: [{"url": "a discovered document address", "text": "its fetched JSON"}]} → layers with source_url, and next when supplied documents need another fetch"#,
),
C::new("service.add", "Add Service Layer", "Home › Add", add).params(
r#"{"url": "as service.layers", "type"?, "layer": "the layer's name (service.layers lists them)", "name"?: text, "time"?: "a time-enabled WMTS layer's date (2024-06-01; its default otherwise)", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed layer's source_url", "describe"?: "a WCS coverage's DescribeCoverage document, when already fetched", "tiles"?: "an OGC API layer's tile template, when already read from its tileset (the app's)", "bbox"?: [west, south, east, north] | "view" (the default) | "full" (a WCS coverage's area)}"#,
r#"{"url": "as service.layers", "type"?, "layer": "the layer's name (service.layers lists them)", "name"?: text, "time"?: "a time-enabled WMTS layer's date (2024-06-01; its default otherwise)", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed layer's source_url", "describe"?: "a WCS coverage's DescribeCoverage document, when already fetched", "tiles"?: "an OGC API layer's tile template, when already read from its tileset (the app's)", "bbox"?: [west, south, east, north] | "view" | "full": a WCS coverage's area (the view by default); for a WFS, OGC API or ArcGIS feature layer, only the features that cross it (the whole layer, "full", by default)}"#,
),
C::new("service.coverage", "WCS Coverage Request", "Home › Add", coverage).view().params(
r#"{"url": "a WCS address", "type"?: "wcs", "layer": "the coverage's name", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed coverage's source_url", "describe"?: "its DescribeCoverage answer, when already fetched", "bbox"?: [west, south, east, north] | "view" (the default) | "full"} → the GetCoverage address of a GeoTIFF (layer.addUrl adds it)"#,
Expand Down Expand Up @@ -417,24 +418,62 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult {
}
}
Offer::Features { url: items } => {
let area = features_area(s, p)?;
let asked = area.and_then(|a| rustgis_data::ogc::features_in_area(items, a));
#[cfg(target_arch = "wasm32")]
{
let _ = items;
let _ = (items, asked);
Err(format!("{url}: in the web app, Home › Add Data › From Service downloads the features"))
}
#[cfg(not(target_arch = "wasm32"))]
{
if p.get("bbox").is_some_and(|b| !b.is_null() && *b != "full") && asked.is_none() {
let why = if area.is_none() { "an area across the antimeridian" } else { "the service can't be asked for an area" };
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
s.notify(format!("{name}: {why}, so the whole layer is asked for"), false);
}
let max = crate::render::rustgis_tiles::cache::MAX_DOWNLOAD;
let bytes = download_features(s, &name, items, max)?;
let bytes = download_features(s, &name, asked.as_deref().unwrap_or(items), max)
.map_err(|e| slow_whole_layer(e, asked.is_some()))?;
let bytes = features_answer(s, &name, bytes);
let r = super::raster::add_named_bytes(s, &json!({"name": name}), format!("{name}.geojson"), bytes)?;
zoom(s);
let mut r = super::raster::add_named_bytes(s, &json!({"name": name}), format!("{name}.geojson"), bytes)?;
// Over an area, the features crossing it: the view stays, or goes to a box given
// (the whole layer's bounds would show a country to fill one state).
match (asked.is_some(), area, p.get("bbox")) {
(true, Some([w, so, e, n]), Some(Value::Array(_))) => s.zoom_to(&rustgis_geom::Extent::new(w, so, e, n)),
(true, ..) => {}
_ => zoom(s),
}
if let (Some(_), Some(out)) = (&asked, r.as_object_mut()) {
out.insert("area".into(), json!(area));
}
Ok(r)
}
}
}
}

/// The area a service's features are asked for over: a `bbox` given (`[west, south, east,
/// north]`, or `"view"`, the map's), else none, for the whole layer (`"full"` says so). A box
/// across the antimeridian asks for the whole layer too, as `catalog.search` does.
fn features_area(s: &Session, p: &Value) -> Result<Option<[f64; 4]>, String> {
match p.get("bbox") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(f)) if f == "full" => Ok(None),
Some(_) => Ok(Some(super::catalogs::area(s, p)?).filter(|a| a[0] <= a[2])),
}
}

/// A whole layer too slow to download while a command waits: the error says an area can be asked
/// for instead.
#[cfg(not(target_arch = "wasm32"))]
fn slow_whole_layer(e: String, over_area: bool) -> String {
if !over_area && (e.contains("timeout") || e.contains("timed out")) {
format!("{e}; or ask for the features in an area only, with \"bbox\": [west, south, east, north] or \"view\"")
} else {
e
}
}

/// The area a coverage is asked for over: `bbox` given, `"full"` (its bounds), or the map's view
/// (the default); within its bounds when they are known.
fn coverage_area(s: &Session, p: &Value, info: &rustgis_data::ogc::CoverageInfo, id: &str) -> Result<[f64; 4], String> {
Expand Down
56 changes: 56 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8591,6 +8591,62 @@ fn arcgis_features_read_past_the_record_limit() {
);
}

/// A feature layer comes whole unless an area is asked for (#819): then only the features that
/// cross it, a WFS 1.1 or 2.0 asked with `BBOX` latitude first in urn:ogc:def:crs:EPSG::4326. A
/// WFS 1.0, or an area across the antimeridian, is asked whole, and says so.
#[test]
fn service_features_asked_for_over_an_area() {
use ogc_server::{Route, Server};
let features = r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"n": 1}, "geometry": {"type": "Point", "coordinates": [-42.8, -5.1]}}]}"#;
let server = Server::new(vec![Route::new("/wfs", features)]);
let caps = |version: &str| {
format!(
r#"<WFS_Capabilities version="{version}"><OperationsMetadata><Operation name="GetFeature"><DCP><HTTP><Get href="{}/wfs?"/></HTTP></DCP></Operation></OperationsMetadata>
<FeatureTypeList><FeatureType><Name>CGMAT:munic</Name><Title>Municipalities</Title><DefaultSRS>EPSG:4674</DefaultSRS></FeatureType></FeatureTypeList></WFS_Capabilities>"#,
server.base
)
};
let url = format!("{}/wfs", server.base);
let piaui = json!([-45.99, -10.93, -40.37, -2.74]);
let mut s = Session::new(Project::default());
let add = |s: &mut Session, version: &str, bbox: Option<Value>| {
let mut p = json!({"url": url, "layer": "CGMAT:munic", "text": caps(version), "name": format!("M{}", s.map().layers.len())});
if let Some(b) = bbox {
p["bbox"] = b;
}
s.run("service.add", &p).unwrap()
};
let r = add(&mut s, "1.1.0", Some(piaui.clone()));
assert_eq!(r["features"], 1);
assert_eq!(r["area"], piaui);
let r = add(&mut s, "2.0.0", Some(json!("view")));
assert!(r["area"].is_array(), "{r}");
let r = add(&mut s, "2.0.0", None);
assert!(r.get("area").is_none(), "{r}");
add(&mut s, "2.0.0", Some(json!("full")));
add(&mut s, "2.0.0", Some(json!([170.0, -20.0, -170.0, -10.0])));
add(&mut s, "1.0.0", Some(piaui.clone()));
let boxes: Vec<Option<String>> =
server.requests().iter().map(|r| r.query.iter().find(|(k, _)| k == "BBOX").map(|(_, v)| v.clone())).collect();
assert_eq!(boxes.len(), 6);
assert_eq!(boxes[0].as_deref(), Some("-10.93,-45.99,-2.74,-40.37,urn:ogc:def:crs:EPSG::4326"));
assert!(boxes[1].as_deref().is_some_and(|b| b.ends_with(",urn:ogc:def:crs:EPSG::4326")), "{boxes:?}");
assert_eq!(&boxes[2..], [None, None, None, None]);
let notes: Vec<&str> = s.notices.iter().map(|n| n.text.as_str()).collect();
assert!(notes.iter().any(|n| n.starts_with("M4: an area across the antimeridian")), "{notes:?}");
assert!(notes.iter().any(|n| n.starts_with("M5: the service can't be asked for an area")), "{notes:?}");
// Asked for the box given, the map goes to it, not to the whole layer's bounds.
s.run("service.add", &json!({"url": url, "layer": "CGMAT:munic", "text": caps("2.0.0"), "name": "Piauí", "bbox": piaui})).unwrap();
let v = view_lonlat(&s);
assert!(v[0] < -45.0 && v[2] > -41.0 && v[1] < -10.0 && v[3] > -3.0 && v[2] - v[0] < 20.0, "{v:?}");
}

/// The map's view in longitude/latitude, as `bbox: "view"` reads it.
fn view_lonlat(s: &Session) -> [f64; 4] {
let e = crate::cmd::workspace::view_extent(s);
[e.min_x, e.min_y, e.max_x, e.max_y]
}

/// A WCS coverage (from a local server) becomes a raster of the view, asked for in EPSG:4326 within
/// its bounds; an error answer is refused. A catalogue's records come with the links RustGIS can
/// follow, those pointing inward left out.
Expand Down
2 changes: 1 addition & 1 deletion crates/ui-egui/src/connectiontree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ fn add_from(app: &mut RustGisApp, child: &Value, source: Option<&ServiceSource>,
let params = add["params"].clone();
match (source, child.get("layer").filter(|l| l.is_object())) {
(Some(source), Some(layer)) => {
serviceui::add_layer_from(app, source, layer, "", false, origin)?;
serviceui::add_layer_from(app, source, layer, "", None, false, origin)?;
}
_ => match command {
"layer.addUrl" => {
Expand Down
12 changes: 11 additions & 1 deletion crates/ui-egui/src/dialogs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,11 @@ fn add_service(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool {
ui.label(egui::RichText::new(tl!("YYYY-MM-DD, for the layers that change with time")).small().weak());
});
}
// Feature layers come whole, or only the features crossing the map's view.
if !grouped && layers.iter().any(|l| l["offer"]["type"] == "features") {
ui.checkbox(&mut browse.area, tl!("Only the map's area"))
.on_hover_text(tl!("Feature layers: ask the service only for the features that cross the map's view"));
}
if grouped && layers.iter().any(|l| l["offer"]["type"] == "features") {
ui.horizontal(|ui| {
ui.label(tl!("Name"));
Expand Down Expand Up @@ -929,7 +934,12 @@ fn add_service(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool {
let title = l.get("title").and_then(Value::as_str).unwrap_or(name).to_string();
// Features are downloaded in the background, as From URL… does; map layers are added now.
let time = app.ui.service_browse.time.trim().to_string();
match crate::serviceui::add_layer(app, &src, &l, &time, true) {
// The view's area, for a feature layer only: a map layer never asks for one, so an
// unknown view can't stop it.
let features = l["offer"]["type"] == "features";
let area =
(features && app.ui.service_browse.area).then(|| rustgis_engine::cmd::catalogs::area(&app.session, &Value::Null)).transpose();
match area.and_then(|area| crate::serviceui::add_layer(app, &src, &l, &time, area, true)) {
Ok(m) => app.dialogs.info = Some(format!("{m} {title}")),
Err(e) => app.dialogs.error = Some(e),
}
Expand Down
3 changes: 3 additions & 0 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,9 @@ pub struct ServiceBrowse {
pub filter: String,
/// The date time-enabled layers are added at (their default when empty).
pub time: String,
/// Feature layers are asked only for the features crossing the map's view (Only the map's
/// area), not whole.
pub area: bool,
/// The directories (and their types) opened before the one shown, the last most recent.
pub back: Vec<(String, &'static str)>,
}
Expand Down
Loading
Loading