Skip to content
76 changes: 64 additions & 12 deletions crates/data/src/ogc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,13 @@ pub struct ServiceLayer {
/// service's GetLegendGraphic, then its default style's picture; a WMTS layer's default
/// style's, each for its scales. None when the service gives none.
pub legends: Vec<Legend>,
/// The legend pictures its default style offers that RustGIS can't show: in a format other
/// than PNG or JPEG, or at an address other than the web's (an `ftp:` one). A WMS style's
/// `LegendURL`s are the one legend in other formats or sizes (WMS 1.3.0 §7.2.4.6.4), so a WMS
/// layer keeps the first it can show and loses nothing while it has one: its count is 1 when
/// none could be shown and the service draws none. A WMTS style's are for different scales,
/// so each it can't keep is counted.
pub legends_left_out: usize,
/// The Web Mercator zooms its tiles are drawn at, least and greatest, when the service says:
/// a WMS layer's scale hints, a WMTS layer's tile matrices. `None`: the usual range.
pub zooms: Option<(u8, u8)>,
Expand Down Expand Up @@ -1124,6 +1131,8 @@ fn wms(url: &str, root: &Node) -> Service {
if let Some(l) = wms_legend(url, &styles).filter(|l| !legends.contains(l)) {
legends.push(l);
}
// Its style offers a picture, and none can be shown: its legend is lost.
let legends_left_out = usize::from(legends.is_empty() && wms_offers_legend(&styles));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The WMS count is at most 1 per layer, whatever the number of pictures its default style offers. wms_legend keeps only the first picture RustGIS shows (its find_map, around line 1354) and drops the rest without any count. So a style with two valid PNG LegendURLs (say, one per size) silently loses the second. A style with three SVG pictures reports 1 legend picture(s) ... left out.

The WMTS path now counts each picture it can't keep, so the two services report differently. The notice's noun is "legend picture(s)", so a per-layer count undercounts. Either count each offered picture that isn't kept (the first valid one stays the layer's legend), or state in the doc comment and the notice that a WMS layer keeps one picture by design and why the rest aren't counted. I have not run the tests.

Confidence: medium. The one-picture design may be deliberate, but the count is what users see.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By design, now said in the field's doc comment (2b699e5). A WMS style's LegendURLs are the one legend in other formats or sizes (WMS 1.3.0 §7.2.4.6.4). So a layer that keeps one it can show loses nothing, and one that keeps none loses its legend, counted once. A WMTS style's are for different scales, so each one it can't keep is counted.

service.layers.push(ServiceLayer {
zooms: Some(scales.zooms()),
name,
Expand All @@ -1144,6 +1153,7 @@ fn wms(url: &str, root: &Node) -> Service {
}),
feature_info,
legends,
legends_left_out,
});
}
if cut_times > 0 {
Expand Down Expand Up @@ -1343,8 +1353,7 @@ const MAX_STYLES: usize = 64;
/// A WMS layer's legend: its default style's (the one a GetMap with `STYLES=` draws: the one
/// named `default`, else the first), the first of its `LegendURL`s in a format RustGIS shows.
fn wms_legend(url: &str, styles: &[Node]) -> Option<Legend> {
let style =
styles.iter().find(|s| child_text(s, "Name").is_some_and(|n| n.eq_ignore_ascii_case("default"))).or_else(|| styles.first())?;
let style = wms_default_style(styles)?;
children(style, "LegendURL").find_map(|l| {
if !legend_format(child_text(&l, "Format").as_deref()) {
return None;
Expand All @@ -1355,6 +1364,16 @@ fn wms_legend(url: &str, styles: &[Node]) -> Option<Legend> {
})
}

/// The style a GetMap with `STYLES=` draws: the one named `default`, else the first.
fn wms_default_style<'s, 'a, 'i>(styles: &'s [Node<'a, 'i>]) -> Option<&'s Node<'a, 'i>> {
styles.iter().find(|s| child_text(s, "Name").is_some_and(|n| n.eq_ignore_ascii_case("default"))).or_else(|| styles.first())
}

/// Whether a WMS layer's default style ([`wms_default_style`]) offers any legend picture.
fn wms_offers_legend(styles: &[Node]) -> bool {
wms_default_style(styles).is_some_and(|s| children(s, "LegendURL").next().is_some())
}

/// A service's GetLegendGraphic request for a layer, when its capabilities offer one (the SLD
/// profile's `GetLegendGraphic` among its requests) in PNG or JPEG.
fn wms_legend_graphic(root: &Node, url: &str, get_map: &str, version: &str) -> Option<impl Fn(&str) -> Legend + use<>> {
Expand Down Expand Up @@ -1546,16 +1565,21 @@ fn wmts(url: &str, root: &Node) -> Service {
let default_style = children(&layer, "Style").find(|s| s.attribute("isDefault") == Some("true")).or_else(|| child(&layer, "Style"));
let style = default_style.and_then(|s| child_text(&s, "Identifier")).unwrap_or_else(|| "default".into());
// Its default style's legends (WMTS 1.0.0 §7.1.1.1.1), each for the scales it gives.
let legends: Vec<Legend> = default_style
.iter()
.flat_map(|s| children(s, "LegendURL"))
.filter(|l| legend_format(l.attribute("format")))
.filter_map(|l| {
let url = href(&l).and_then(|h| resolve(url, &h)).filter(|h| is_web(h))?;
Some(Legend { url, min_scale: scale_attr(&l, "minScaleDenominator"), max_scale: scale_attr(&l, "maxScaleDenominator") })
})
.take(MAX_LEGENDS)
.collect();
// The first [`MAX_LEGENDS`] it can show are kept; those it can't, and those past them,
// are lost (counted, not held).
let (mut legends, mut legends_left_out) = (Vec::new(), 0usize);
for l in default_style.iter().flat_map(|s| children(s, "LegendURL")) {
let shown =
legend_format(l.attribute("format")).then(|| href(&l).and_then(|h| resolve(url, &h)).filter(|h| is_web(h))).flatten();
match shown {
Some(url) if legends.len() < MAX_LEGENDS => legends.push(Legend {
url,
min_scale: scale_attr(&l, "minScaleDenominator"),
max_scale: scale_attr(&l, "maxScaleDenominator"),
}),
_ => legends_left_out += 1,
}
}
let linked: Vec<String> = children(&layer, "TileMatrixSetLink").filter_map(|l| child_text(&l, "TileMatrixSet")).collect();
let bbox = child(&layer, "WGS84BoundingBox").and_then(|b| {
let lo: Vec<f64> = child_text(&b, "LowerCorner")?.split_whitespace().filter_map(|t| t.parse().ok()).collect();
Expand Down Expand Up @@ -1696,6 +1720,7 @@ fn wmts(url: &str, root: &Node) -> Service {
time,
feature_info: None,
legends,
legends_left_out,
});
}
cut_listing(&mut service);
Expand Down Expand Up @@ -1844,6 +1869,7 @@ fn wfs(url: &str, root: &Node) -> Service {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
}
if let (n, Some(first)) = unread {
Expand Down Expand Up @@ -2014,6 +2040,7 @@ fn wcs(url: &str, root: &Node) -> Service {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
};
let (mut n, mut left, mut long_ids) = (0, 0, 0);
Expand Down Expand Up @@ -2728,6 +2755,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result<Service, String> {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
listed = true;
}
Expand Down Expand Up @@ -2758,6 +2786,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result<Service, String> {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
features(&mut service);
// A dynamic map's layers, each drawn alone (`layers=show:<id>`): a national layer is
Expand All @@ -2780,6 +2809,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result<Service, String> {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
}
}
Expand All @@ -2796,6 +2826,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result<Service, String> {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
} else if lower.ends_with("/vectortileserver") {
service.kind = "ArcGIS VectorTileServer".into();
Expand All @@ -2814,6 +2845,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result<Service, String> {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
} else {
if let Some((root, id)) = b.rsplit_once('/')
Expand Down Expand Up @@ -2923,6 +2955,7 @@ fn arcgis_directory(b: &str, v: &serde_json::Value) -> Service {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
}
for s in v.get("services").and_then(|s| s.as_array()).into_iter().flatten().take(MAX_LISTED_LAYERS) {
Expand All @@ -2949,6 +2982,7 @@ fn arcgis_directory(b: &str, v: &serde_json::Value) -> Service {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
}
if skipped > 0 {
Expand Down Expand Up @@ -3013,6 +3047,7 @@ fn ogc_api(url: &str, v: &serde_json::Value) -> Result<Service, String> {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
}
if !service.layers.is_empty() || service.collections_url.is_some() || service.dataset.is_some() {
Expand Down Expand Up @@ -3083,6 +3118,7 @@ fn ogc_api(url: &str, v: &serde_json::Value) -> Result<Service, String> {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
}
if let Some((t, list, withheld)) = &vector {
Expand All @@ -3097,6 +3133,7 @@ fn ogc_api(url: &str, v: &serde_json::Value) -> Result<Service, String> {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
}
if map.is_some() || vector.is_some() {
Expand Down Expand Up @@ -3152,6 +3189,7 @@ fn ogc_api(url: &str, v: &serde_json::Value) -> Result<Service, String> {
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
});
}
if unreadable > 0 {
Expand Down Expand Up @@ -7879,6 +7917,9 @@ mod tests {
// A picture RustGIS doesn't show, or not on the web: the parent's, or none.
assert_eq!(urls(&s, "only svg"), Vec::<String>::new());
assert_eq!(urls(&s, "not on the web"), Vec::<String>::new());
// Those two lose their legend; a GIF passed over for a PNG loses none.
let lost = |s: &Service, name: &str| s.layers.iter().find(|l| l.name == name).unwrap().legends_left_out;
assert_eq!(["inherits", "own", "named default", "only svg", "not on the web"].map(|n| lost(&s, n)), [0, 0, 0, 1, 1]);
assert!(s.layers.iter().flat_map(|l| &l.legends).all(|l| l.min_scale.is_none() && l.max_scale.is_none()));
// With it (swisstopo's, in its SLD namespace): the service's legend first, the style's after.
let glg = r#"<sld:GetLegendGraphic><Format>image/gif</Format><Format>image/png</Format><DCPType><HTTP><Get><OnlineResource xlink:href="https://maps.example.org/de/?"/></Get></HTTP></DCPType></sld:GetLegendGraphic>"#;
Expand All @@ -7896,6 +7937,8 @@ mod tests {
"https://maps.example.org/de/?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetLegendGraphic&LAYER=only%20svg&FORMAT=image%2Fpng&SLD_VERSION=1.1.0"
]
);
// The service draws its legend: none is lost.
assert!(s.layers.iter().all(|l| l.legends_left_out == 0));
// WMS 1.1.1 (SLD 1.0): no SLD version; its own address, else GetMap's.
let glg = r#"<GetLegendGraphic><Format>image/jpeg</Format></GetLegendGraphic>"#;
let s = parse("https://maps.example.org/wms", caps("1.1.1", glg).as_bytes()).unwrap();
Expand Down Expand Up @@ -7934,6 +7977,15 @@ mod tests {
Legend { url: "https://t.example.org/1.0.0/far.jpg".into(), min_scale: Some(50_000.0), max_scale: None },
]
);
// The SVG one can't be shown: lost.
assert_eq!(s.layers[0].legends_left_out, 1);
// Past the most it keeps, a picture it could show is lost too, and counted.
let many: String =
(0..=MAX_LEGENDS).map(|i| format!(r#"<LegendURL format="image/png" xlink:href="https://t.example.org/{i}.png"/>"#)).collect();
let crowded = xml
.replace(r#"<LegendURL format="image/png" xlink:href="https://t.example.org/near.png" maxScaleDenominator="50000"/>"#, &many);
let c = parse("https://t.example.org/1.0.0/WMTSCapabilities.xml", crowded.as_bytes()).unwrap();
assert_eq!((c.layers[0].legends.len(), c.layers[0].legends_left_out), (MAX_LEGENDS, 3));
// The one for the map's scale: up to below the maximum, from the minimum.
let at = |scale: f64| legends_at(legends, scale).map(|l| l.url.as_str()).collect::<Vec<_>>();
assert_eq!(at(10_000.0), ["https://t.example.org/near.png"]);
Expand Down
13 changes: 12 additions & 1 deletion crates/data/src/ogc/dataset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,18 @@ fn advertised(from: &str, href: &str, withheld: &mut u32) -> Option<String> {
/// Constructs an offer whose tile template has already been read, so adding it needs no
/// second tileset fetch and cannot fall back to a guessed template.
fn layer(name: String, title: String, offer: Offer) -> ServiceLayer {
ServiceLayer { name, title, offer, bbox: None, tilesets: None, time: None, feature_info: None, legends: Vec::new(), zooms: None }
ServiceLayer {
name,
title,
offer,
bbox: None,
tilesets: None,
time: None,
feature_info: None,
legends: Vec::new(),
legends_left_out: 0,
zooms: None,
}
}

impl DatasetDiscovery {
Expand Down
18 changes: 11 additions & 7 deletions crates/engine/src/cmd/clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,25 +254,29 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult {
l.selection = (first..first + n).collect();
let name = l.name.clone();
let features = |n: usize| if n == 1 { "1 feature".to_string() } else { format!("{n} features") };
use rustgis_data::loss::{LossCode, Note};
let mut notices = Vec::new();
if unplaced > 0 {
let (have, they) = if unplaced == 1 { ("has", "it wasn't") } else { ("have", "they weren't") };
notices.push(format!(
"Paste: {} {have} a place that layer {name} ({}) can't hold, so {they} pasted",
features(unplaced),
own.label()
notices.push(Note::loss(
LossCode::DroppedFeature,
format!("Paste: {} {have} a place that layer {name} ({}) can't hold, so {they} pasted", features(unplaced), own.label()),
));
}
for (f, (cuts, n)) in l.dataset.fields.iter().zip(unfit) {
notices.extend(cuts.notices("Paste", &f.name));
notices.extend(cuts.classified("Paste", &f.name).into_iter().map(|(code, text)| Note::loss(code, text)));
// A value that asks for null isn't counted: only values the field couldn't hold.
if n > 0 {
notices.push(format!("Paste: '{}' is null in {}, whose value isn't a {} value", f.name, features(n), f.ty.label()));
notices.push(Note::loss(
LossCode::DroppedValue,
format!("Paste: '{}' is null in {}, whose value isn't a {} value", f.name, features(n), f.ty.label()),
));
}
}
super::design::apply(s, id, (first..first + n).map(|r| super::design::Change { before: None, row: Some(r) }).collect())?;
s.map_mut().layers.iter_mut().filter(|o| o.id != id).for_each(|o| o.selection.clear());
s.notify(format!("Pasted {n} features into {name}"), false);
for notice in said.into_iter().chain(notices.into_iter().map(rustgis_data::loss::Note::plain)) {
for notice in said.into_iter().chain(notices) {
s.say(notice);
}
Ok(json!({"pasted": n, "layer": id}))
Expand Down
Loading
Loading