diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 2a85247964..3ba9322baa 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -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, + /// 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)>, @@ -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)); service.layers.push(ServiceLayer { zooms: Some(scales.zooms()), name, @@ -1144,6 +1153,7 @@ fn wms(url: &str, root: &Node) -> Service { }), feature_info, legends, + legends_left_out, }); } if cut_times > 0 { @@ -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 { - 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; @@ -1355,6 +1364,16 @@ fn wms_legend(url: &str, styles: &[Node]) -> Option { }) } +/// 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 Legend + use<>> { @@ -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 = 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 = children(&layer, "TileMatrixSetLink").filter_map(|l| child_text(&l, "TileMatrixSet")).collect(); let bbox = child(&layer, "WGS84BoundingBox").and_then(|b| { let lo: Vec = child_text(&b, "LowerCorner")?.split_whitespace().filter_map(|t| t.parse().ok()).collect(); @@ -1696,6 +1720,7 @@ fn wmts(url: &str, root: &Node) -> Service { time, feature_info: None, legends, + legends_left_out, }); } cut_listing(&mut service); @@ -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 { @@ -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); @@ -2728,6 +2755,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result { time: None, feature_info: None, legends: Vec::new(), + legends_left_out: 0, }); listed = true; } @@ -2758,6 +2786,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result { 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:`): a national layer is @@ -2780,6 +2809,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result { time: None, feature_info: None, legends: Vec::new(), + legends_left_out: 0, }); } } @@ -2796,6 +2826,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result { time: None, feature_info: None, legends: Vec::new(), + legends_left_out: 0, }); } else if lower.ends_with("/vectortileserver") { service.kind = "ArcGIS VectorTileServer".into(); @@ -2814,6 +2845,7 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result { time: None, feature_info: None, legends: Vec::new(), + legends_left_out: 0, }); } else { if let Some((root, id)) = b.rsplit_once('/') @@ -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) { @@ -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 { @@ -3013,6 +3047,7 @@ fn ogc_api(url: &str, v: &serde_json::Value) -> Result { 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() { @@ -3083,6 +3118,7 @@ fn ogc_api(url: &str, v: &serde_json::Value) -> Result { time: None, feature_info: None, legends: Vec::new(), + legends_left_out: 0, }); } if let Some((t, list, withheld)) = &vector { @@ -3097,6 +3133,7 @@ fn ogc_api(url: &str, v: &serde_json::Value) -> Result { time: None, feature_info: None, legends: Vec::new(), + legends_left_out: 0, }); } if map.is_some() || vector.is_some() { @@ -3152,6 +3189,7 @@ fn ogc_api(url: &str, v: &serde_json::Value) -> Result { time: None, feature_info: None, legends: Vec::new(), + legends_left_out: 0, }); } if unreadable > 0 { @@ -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::::new()); assert_eq!(urls(&s, "not on the web"), Vec::::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#"image/gifimage/png"#; @@ -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#"image/jpeg"#; let s = parse("https://maps.example.org/wms", caps("1.1.1", glg).as_bytes()).unwrap(); @@ -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#""#)).collect(); + let crowded = xml + .replace(r#""#, &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::>(); assert_eq!(at(10_000.0), ["https://t.example.org/near.png"]); diff --git a/crates/data/src/ogc/dataset.rs b/crates/data/src/ogc/dataset.rs index 68c00d7e99..46ba131033 100644 --- a/crates/data/src/ogc/dataset.rs +++ b/crates/data/src/ogc/dataset.rs @@ -97,7 +97,18 @@ fn advertised(from: &str, href: &str, withheld: &mut u32) -> Option { /// 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 { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index a0c8e75373..9d33bdac7e 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -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})) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index baebeec62d..825b1d9afa 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -389,8 +389,11 @@ fn notify_left_out(s: &mut Session, name: &str, left: &LeftOut) { } } -/// What writing a value took from it, by field: a notice key ([`notify_loss`]). -type Losses = Vec<(String, &'static str)>; +/// What writing a value took from it: a notice key ([`notify_loss`]) and the loss's code. +type CellLoss = (&'static str, LossCode); + +/// What writing a row's values took from them, by field. +type Losses = Vec<(String, CellLoss)>; /// A new row's values for `fields`: those given (`"attributes"`, [`given_attributes`]), else /// `defaults` (a feature template's), each as its field holds it, with what that took from each @@ -419,13 +422,19 @@ fn new_row(fields: &[Field], p: &Json, defaults: &[(String, Value)]) -> Result<( } // A date-time (a native caller's template default) keeps only its day in a date field. if matches!(value, Value::DateTime(t) if f.ty == FieldType::Date && !t.is_date()) { - losses.push((f.name.clone(), "{layer}, field '{field}', row {row}: 1 attribute value kept only its day")); + losses.push(( + f.name.clone(), + ("{layer}, field '{field}', row {row}: 1 attribute value kept only its day", LossCode::DroppedTime), + )); } // A date (a native caller's template default) is no yes/no value: null, and said. if f.ty == FieldType::Boolean && coerced.is_null() && !value.asks_null() { losses.push(( f.name.clone(), - "{layer}, field '{field}', row {row}: 1 attribute value was written as null because it isn't a yes/no value", + ( + "{layer}, field '{field}', row {row}: 1 attribute value was written as null because it isn't a yes/no value", + LossCode::DroppedValue, + ), )); } Ok(coerced) @@ -435,13 +444,13 @@ fn new_row(fields: &[Field], p: &Json, defaults: &[(String, Value)]) -> Result<( } /// Says what writing a value of `field`, in row `row` of layer or table `name`, took from it. -fn notify_loss(s: &mut Session, key: &'static str, name: &str, field: String, row: usize) { - s.notify_text( +fn notify_loss(s: &mut Session, (key, code): CellLoss, name: &str, field: String, row: usize) { + s.notify_loss( + code, crate::notice_text::NoticeText::format( key, [("layer", name.to_string().into()), ("field", field.into()), ("row", row.saturating_add(1).to_string().into())], ), - false, ); } @@ -537,12 +546,13 @@ impl Cuts { /// The notices for what writing the whole-number or date field `field` cut, each starting with `by` /// (the command or rule that wrote it). Empty when nothing was cut. + #[cfg(test)] pub(crate) fn notices(&self, by: &str, field: &str) -> Vec { self.classified(by, field).into_iter().map(|(_, text)| text).collect() } /// Pairs each coercion message with its cause at the point the loss is counted. - fn classified(&self, by: &str, field: &str) -> Vec<(LossCode, String)> { + pub(crate) fn classified(&self, by: &str, field: &str) -> Vec<(LossCode, String)> { let results = |n: usize| if n == 1 { "1 result".to_string() } else { format!("{n} results") }; let mut out = Vec::new(); if self.fractions > 0 { @@ -876,15 +886,24 @@ fn delete(s: &mut Session, _: &Json) -> CmdResult { } /// A numeric conversion's loss, shared by edits and feature creation. Null entered explicitly is quiet. -fn numeric_loss(input: &Value, v: &Value, ty: FieldType) -> Option<&'static str> { +fn numeric_loss(input: &Value, v: &Value, ty: FieldType) -> Option { if ty.is_numeric() && v.is_null() && !input.asks_null() { - Some("{layer}, field '{field}', row {row}: 1 attribute value was written as null because it isn't a number") + Some(( + "{layer}, field '{field}', row {row}: 1 attribute value was written as null because it isn't a number", + LossCode::DroppedValue, + )) } else if ty == FieldType::Integer { let (exact, cut) = coerce_cut(input.clone(), ty); match cut { - Cut::Fraction => Some("{layer}, field '{field}', row {row}: 1 attribute value lost its fraction"), - Cut::Range => Some("{layer}, field '{field}', row {row}: 1 attribute value was clamped to the 64-bit integer range"), - Cut::None if &exact != v => Some("{layer}, field '{field}', row {row}: 1 attribute value lost integer precision"), + Cut::Fraction => Some(("{layer}, field '{field}', row {row}: 1 attribute value lost its fraction", LossCode::ChangedTruncated)), + // The value given is gone: the range's limit stands in its place. + Cut::Range => Some(( + "{layer}, field '{field}', row {row}: 1 attribute value was clamped to the 64-bit integer range", + LossCode::DroppedValue, + )), + Cut::None if &exact != v => { + Some(("{layer}, field '{field}', row {row}: 1 attribute value lost integer precision", LossCode::ChangedRounded)) + } _ => None, } } else { @@ -1056,14 +1075,18 @@ fn convert_field(s: &mut Session, p: &Json) -> CmdResult { let (kind, one) = if ty == FieldType::Date { ("dates", "a date") } else { ("date-times", "a date-time") }; if nulled > 0 { let rows = if nulled == 1 { "1 row".to_string() } else { format!("{nulled} rows") }; - s.notify( + // Text that asks for null isn't counted (`to_dates`): only text that isn't a date. + s.say(rustgis_data::loss::Note::loss( + LossCode::DroppedValue, format!("Convert Field: '{name}' holds {kind} now, and is null in {rows} whose text isn't {one}: {}", examples.join(", ")), - false, - ); + )); } if rounded > 0 { let values = if rounded == 1 { "1 value was".to_string() } else { format!("{rounded} values were") }; - s.notify(format!("Convert Field: {values} rounded to the microsecond in '{name}', as more digits than that aren't kept"), false); + s.say(rustgis_data::loss::Note::loss( + LossCode::ChangedRounded, + format!("Convert Field: {values} rounded to the microsecond in '{name}', as more digits than that aren't kept"), + )); } Ok(json!({"converted": converted, "null": nulled})) } @@ -1673,8 +1696,9 @@ fn land_layer_dates(s: &mut Session, p: &Json) -> Option { check_layer_dates(s, id, fi, ty)?; let layer = s.map_mut().layer_mut(id).ok_or("no layer")?; (layer.dataset.fields, layer.dataset.features) = (output.fields, output.features); + // Each with its code, as a table's edit lands. for notice in notices { - s.notify(notice.text, notice.error); + s.relay_notice(notice); } Ok(answer) })()) diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 8a97c710e9..8ddaa0b775 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -279,15 +279,19 @@ pub(crate) fn drawn( }) } -/// What drawing an export on `copy` (a copy of the session) said, each notice with its severity, -/// to say again where the export lands; past the notices a session keeps, how many earlier ones -/// there were. `path` names the file in that count. -pub(crate) fn copy_notices(copy: &mut Session, path: &str) -> Vec<(rustgis_data::diagnostics::Severity, String)> { - copy_notices_coded(copy, path).into_iter().map(|(severity, note)| (severity, note.text)).collect() +/// [`drawn`] for an export drawn on `copy`, a copy of the session: what drawing it said, a loss +/// kept with its code and said with the export's notes ([`copy_notices_coded`]). +pub(crate) fn drawn_on(copy: &mut Session, written: Result, path: String) -> Result { + let (coded, said): (Vec<_>, Vec<_>) = copy_notices_coded(copy, &path).into_iter().partition(|(_, note)| note.loss.is_some()); + let said = said.into_iter().map(|(severity, note)| (severity, note.text)).collect(); + let mut wrote = drawn(©.project.maps, said, written, path)?; + wrote.notes.extend(coded.into_iter().map(|(_, note)| note)); + Ok(wrote) } -/// [`copy_notices`] with each notice's loss code, for an export that says them itself -/// ([`say_coded`]). +/// What drawing an export on `copy` (a copy of the session) said, each notice with its severity +/// and its loss code, to say again where the export lands; past the notices a session keeps, how +/// many earlier ones there were. `path` names the file in that count. pub(crate) fn copy_notices_coded(copy: &mut Session, path: &str) -> Vec<(rustgis_data::diagnostics::Severity, rustgis_data::loss::Note)> { let kept = std::mem::take(&mut copy.notices); let earlier = copy.notices_given().saturating_sub(kept.len() as u64); diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 694c87c682..cbb1680421 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -652,7 +652,10 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Result let below = h < 0.0; let orient = |o: Orient| if below { o.reversed() } else { o }; // A solid of zero height would be two coincident caps facing apart: STL leaves it out. + // Counted as lost only when it had an area or a point to give: a polygon whose every outer + // ring encloses nothing (fewer than 3 vertices, or all on one line) has neither. if !mesh.keep_lines && h == 0.0 && !matches!(&*g, Geometry::Line(_)) { - mesh.flat += 1; + let shaped = match &*g { + Geometry::Polygon(polys) => polys.iter().any(|rings| { + rings.first().is_some_and(|r| { + // Twice the ring's signed area (the shoelace sum), taken from its first + // vertex so that coordinates far from the origin don't cancel a small + // area out; a closing vertex adds nothing. Against the rounding its terms + // can carry (a few ulps each), so rounding on a ring along a slanted line + // isn't taken for an area, and a real one past it is. + let Some(o) = r.first() else { return false }; + let (mut twice, mut terms) = (0.0f64, 0.0f64); + for (a, b) in r.iter().zip(r.iter().cycle().skip(1)) { + let (ax, ay, bx, by) = (a.x - o.x, a.y - o.y, b.x - o.x, b.y - o.y); + twice += ax * by - bx * ay; + terms += (ax * by).abs() + (bx * ay).abs(); + } + // A coordinate that isn't finite gives no sum, but a place to lose all the same. + let rounding = 4.0 * f64::EPSILON * terms * r.len() as f64; + !twice.is_finite() || twice.abs() > rounding + }) + }), + Geometry::MultiPoint(points) => !points.is_empty(), + _ => true, + }; + mesh.flat += usize::from(shaped); + mesh.flat_seen += 1; continue; } let before = mesh.vertices; @@ -1517,7 +1550,10 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result mesh.short_lines += usize::from(n == 1); continue; } - mesh.lines += 1; + // A part with all its vertices in one place has no length to lose. + let long = part.first().is_some_and(|f| part.iter().any(|c| c != f)); + mesh.lines += usize::from(long); + mesh.lines_seen += 1; if !mesh.keep_lines { continue; } @@ -1558,10 +1594,10 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result } } if mesh.vertices == 0 { - if mesh.flat > 0 && !mesh.keep_lines { + if mesh.flat_seen > 0 && !mesh.keep_lines { return Err("nothing to export: every polygon and point has zero height, and STL holds solids, not flat sheets".into()); } - if mesh.lines + mesh.short_lines > 0 && !mesh.keep_lines { + if mesh.lines_seen + mesh.short_lines > 0 && !mesh.keep_lines { return Err("nothing to export: STL holds polygons and points, not lines".into()); } return Err("nothing to export".into()); @@ -1678,10 +1714,16 @@ fn stl_bytes(s: &mut Session, p: &Value) -> Result<(Vec, StlReport, Vec 0 { - s.notify(format!("Left out {} polygon(s) and point(s) of zero height: STL holds solids, not flat sheets", mesh.flat), false); + s.say(rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedFeature, + format!("Left out {} polygon(s) and point(s) of zero height: STL holds solids, not flat sheets", mesh.flat), + )); } if report.lines > 0 { - s.notify(format!("STL holds triangles only: left out {} polyline(s)", report.lines), false); + s.say(rustgis_data::loss::Note::loss( + rustgis_data::loss::LossCode::DroppedFeature, + format!("STL holds triangles only: left out {} polyline(s)", report.lines), + )); } if report.degenerate > 0 { s.notify( diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index e50badf6db..e116bcb591 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -6683,8 +6683,7 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Result, Vec<_>) = - super::exports::copy_notices_coded(&mut copy, &path).into_iter().partition(|(_, note)| note.loss.is_some()); - let said = said.into_iter().map(|(severity, note)| (severity, note.text)).collect(); - let mut wrote = super::exports::drawn(©.project.maps, said, written, path)?; - wrote.notes.extend(coded.into_iter().map(|(_, note)| note)); - Ok(wrote) + super::exports::drawn_on(&mut copy, written, path) })) } diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index d16cf33337..eaf466db26 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -150,8 +150,7 @@ const MAX_SERVICE_DOCUMENTS: usize = 32; /// this byte budget applies only to the linked dataset documents. pub(crate) const MAX_DATASET_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 }; /// A notice for legend pictures the layer cannot keep because of their addresses. -const LEGENDS_LEFT_OUT_NOTICE: &str = - "{n} legend picture(s) the service listed were left out: their addresses are too long or do not use HTTP or HTTPS"; +const LEGENDS_LEFT_OUT_NOTICE: &str = "{n} legend picture(s) the service listed were left out: their addresses are too long or do not use HTTP or HTTPS, or the pictures aren't PNG or JPEG"; /// Most bytes of document addresses a listing repeats: each listed layer's `source_url` is its /// document's address, which nothing bounds (a landing page links to any collections address). @@ -1496,7 +1495,9 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis s.notify_counted( Some(rustgis_data::loss::LossCode::DroppedLegend), LEGENDS_LEFT_OUT_NOTICE, - u32::try_from(offered.saturating_sub(legends.len())).unwrap_or(u32::MAX), + // Those its address checks refused, and those the service offered that RustGIS + // can't show (another format, or an `ftp:` address). + u32::try_from(offered.saturating_sub(legends.len()).saturating_add(layer.legends_left_out)).unwrap_or(u32::MAX), ); if !legends.is_empty() { add["legend"] = json!(legends); @@ -2421,6 +2422,7 @@ mod tests { time: None, feature_info: None, legends: Vec::new(), + legends_left_out: 0, zooms: None, }], ..Service::default() diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index dfae39f803..d5be1833bf 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -322,7 +322,7 @@ fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value) -> Result<(String, m.layers.iter_mut().filter(|l| shared_layer("webScene", l)).try_for_each(|l| load_whole(s, l))?; let scene = gltf(&m, s.view_size)?; for note in scene.notes() { - s.notify(note, false); + s.say(note); } Ok((m.name.clone(), scene.bytes, m.name.clone())) } @@ -1065,34 +1065,46 @@ struct SceneBytes { } impl SceneBytes { - /// The same counted explanations accompany a usable scene and an empty-result error. - fn notes(&self) -> Vec { + /// The same counted explanations accompany a usable scene and an empty-result error. Features + /// left out are losses, with their codes; rings and line parts with too few vertices hold no + /// area or length to lose, and fanned caps and held heights say how the scene draws them. + fn notes(&self) -> Vec { + use rustgis_data::loss::{LossCode, Note}; let mut notes = Vec::new(); if self.fanned > 0 { - notes.push(super::items::fanned_caps_note(self.fanned)); + notes.push(Note::plain(super::items::fanned_caps_note(self.fanned))); } if self.out_of_range > 0 { - notes.push(format!("{} feature(s) left out of the scene: a coordinate is too far from the map's centre", self.out_of_range)); + notes.push(Note::loss( + LossCode::DroppedFeature, + format!("{} feature(s) left out of the scene: a coordinate is too far from the map's centre", self.out_of_range), + )); } if self.limited > 0 { - notes.push(format!("{} feature(s) left out of the scene: the {MAX_FEATURES} feature limit was reached", self.limited)); + notes.push(Note::loss( + LossCode::DroppedOverLimit, + format!("{} feature(s) left out of the scene: the {MAX_FEATURES} feature limit was reached", self.limited), + )); } if self.unplaced > 0 { - notes.push(format!("{} feature(s) left out of the scene: a place can't be given in longitude/latitude", self.unplaced)); + notes.push(Note::loss( + LossCode::DroppedFeature, + format!("{} feature(s) left out of the scene: a place can't be given in longitude/latitude", self.unplaced), + )); } if self.skipped_outer > 0 { - notes.push(format!("Skipped {} polygon(s) whose outer ring has fewer than 3 vertices", self.skipped_outer)); + notes.push(Note::plain(format!("Skipped {} polygon(s) whose outer ring has fewer than 3 vertices", self.skipped_outer))); } if self.holes_dropped > 0 { - notes.push(format!("Dropped {} hole(s) with fewer than 3 vertices", self.holes_dropped)); + notes.push(Note::plain(format!("Dropped {} hole(s) with fewer than 3 vertices", self.holes_dropped))); } if self.single_vertex_lines > 0 { - notes.push(format!("Skipped {} line part(s) with a single vertex", self.single_vertex_lines)); + notes.push(Note::plain(format!("Skipped {} line part(s) with a single vertex", self.single_vertex_lines))); } for (layer, n) in &self.held { - notes.push(format!( + notes.push(Note::plain(format!( "{n} feature(s) of '{layer}' had their extrusion base or height held to the web scene's limit: base plus height stays within 1,000 km" - )); + ))); } notes } @@ -1363,7 +1375,8 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result { } if nodes.is_empty() { let notes = scene.notes(); - let why = if notes.is_empty() { String::new() } else { format!(": {}", notes.join("; ")) }; + let why = + if notes.is_empty() { String::new() } else { format!(": {}", notes.iter().map(|n| n.as_str()).collect::>().join("; ")) }; return Err(format!("the map has no features to put in a scene{why}")); } // As drawn: a camera set from outside a command may not be clamped yet. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d17acb0707..30306c3417 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1499,6 +1499,28 @@ fn editing_features_and_fields() { assert_eq!(s.map().layer_by_name("Cities").unwrap().dataset.features.len(), n - 1); } +/// A value written into a whole-number field says what it lost, with its code: a fraction cut, a +/// value that isn't a number written as null, one past the 64-bit range clamped; a whole number +/// and an empty value lose nothing. +#[test] +fn set_value_says_what_a_whole_number_field_took_with_its_code() { + use rustgis_data::loss::LossCode::*; + let mut s = world(); + s.run("edit.addField", &json!({"layer": "Cities", "name": "count", "type": "integer"})).unwrap(); + for (value, code) in [ + (json!(2.5), Some(ChangedTruncated)), + (json!("many"), Some(DroppedValue)), + (json!(1e30), Some(DroppedValue)), + (json!(7), None), + (json!(""), None), + ] { + let mark = s.notice_mark(); + s.run("edit.setValue", &json!({"layer": "Cities", "row": 0, "field": "count", "value": value})).unwrap(); + let said: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("field 'count'")).map(|n| n.loss()).collect(); + assert_eq!(said, code.into_iter().map(Some).collect::>(), "{value}"); + } +} + /// A date field is added, edited as ISO text, compared in a where clause, calculated, offered to /// the time slider, and kept as dates through a project save; arithmetic on it is an error, and /// text that isn't a date is reported, not quietly stored as null. @@ -1548,8 +1570,10 @@ fn date_fields_work_from_adding_to_saving() { let mark = s.notice_mark(); let row = s.run("edit.addFeature", &json!({"layer": "Cities", "geometry": here, "template": "Old"})).unwrap()["row"].as_u64().unwrap(); - let notices: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert_eq!(notices.iter().any(|n| n.contains("field 'founded'") && n.contains("kept only its day")), said, "{when}: {notices:?}"); + let notices: Vec<_> = s.notices_since(mark).iter().map(|n| (n.text.clone(), n.loss())).collect(); + let hits: Vec<_> = notices.iter().filter(|(n, _)| n.contains("field 'founded'") && n.contains("kept only its day")).collect(); + assert_eq!(!hits.is_empty(), said, "{when}: {notices:?}"); + assert!(hits.iter().all(|(_, loss)| *loss == Some(rustgis_data::loss::LossCode::DroppedTime)), "{when}: {notices:?}"); assert_eq!(cell(&s, "Cities", row as usize, "founded"), "2026-03-07"); s.run("edit.undo", &Value::Null).unwrap(); } @@ -1586,7 +1610,8 @@ fn date_fields_work_from_adding_to_saving() { let mark = s.notice_mark(); s.run("edit.paste", &json!({"layer": "Moments"})).unwrap(); assert!( - s.notices_since(mark).iter().any(|n| n.text == "Paste: 'seen' holds dates, so 1 result kept only its day"), + s.notices_since(mark).iter().any(|n| n.text == "Paste: 'seen' holds dates, so 1 result kept only its day" + && n.loss() == Some(rustgis_data::loss::LossCode::DroppedTime)), "{:?}", s.notices_since(mark) ); @@ -1722,8 +1747,14 @@ fn text_fields_convert_to_dates() { assert_eq!((out["converted"].as_u64(), out["null"].as_u64()), (Some(2), Some(1))); let day = |d| V::parse(d, FieldType::Date); assert_eq!(column(&s, "founded"), (FieldType::Date, vec![day("2026-03-05"), day("1999-12-31"), V::Null, V::Null])); - let notices: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert_eq!(notices, ["Convert Field: 'founded' holds dates now, and is null in 1 row whose text isn't a date: 'n/a'"]); + let notices: Vec<_> = s.notices_since(mark).iter().map(|n| (n.text.clone(), n.loss())).collect(); + assert_eq!( + notices, + [( + "Convert Field: 'founded' holds dates now, and is null in 1 row whose text isn't a date: 'n/a'".to_string(), + Some(rustgis_data::loss::LossCode::DroppedValue) + )] + ); s.run("edit.undo", &Value::Null).unwrap(); assert_eq!(column(&s, "founded"), before); @@ -1761,8 +1792,14 @@ fn text_fields_convert_to_dates() { let mark = s.notice_mark(); let out = s.run("edit.convertField", &json!({"layer": "Cities", "field": "fine", "type": "datetime"})).unwrap(); assert_eq!((out["converted"].as_u64(), out["null"].as_u64()), (Some(3), Some(0))); - let notices: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert_eq!(notices, ["Convert Field: 2 values were rounded to the microsecond in 'fine', as more digits than that aren't kept"]); + let notices: Vec<_> = s.notices_since(mark).iter().map(|n| (n.text.clone(), n.loss())).collect(); + assert_eq!( + notices, + [( + "Convert Field: 2 values were rounded to the microsecond in 'fine', as more digits than that aren't kept".to_string(), + Some(rustgis_data::loss::LossCode::ChangedRounded) + )] + ); assert_eq!(column(&s, "fine").1[0], at("2026-03-05T14:30:00.123457Z")); let err = s.run("edit.convertField", &json!({"layer": "Cities", "field": "founded", "type": "date"})).unwrap_err(); @@ -26217,7 +26254,10 @@ fn service_legends_left_out_are_reported() { EPSG:3857roadsRoads "#; let long = format!("https://maps.example.com/legends/{}.png", "a".repeat(rustgis_map::tiles::MAX_LEGEND_URL)); - for (legend, left_out) in [(long.as_str(), true), ("https://maps.example.com/legends/roads.png", false)] { + // Too long, on ftp (which the parse leaves out, counted for this notice), and kept. + for (legend, left_out) in + [(long.as_str(), true), ("ftp://maps.example.com/legends/roads.png", true), ("https://maps.example.com/legends/roads.png", false)] + { let mut s = Session::new(Project::default()); let mark = s.notice_mark(); s.run("service.add", &json!({"url": "https://maps.example.com/wms", "layer": "roads", "text": WMS.replace("LEGEND", legend)})) @@ -54387,6 +54427,11 @@ fn stl_leaves_out_lines_and_skips_flat_triangles_and_says_so() { mesh_feature(json!({"type": "LineString", "coordinates": [[0.0, 0.02], [0.01, 0.02]]}), 5.0), mesh_feature(json!({"type": "Point", "coordinates": [0.03, 0.02]}), 20.0), mesh_feature(json!({"type": "Point", "coordinates": [0.05, 0.02]}), 0.0), + // Flat, and with no area to lose (two vertices, and three on one line): not counted among + // those left out. + mesh_feature(json!({"type": "Polygon", "coordinates": [[[0.08, 0.0], [0.09, 0.0], [0.08, 0.0]]]}), 0.0), + mesh_feature(json!({"type": "Polygon", "coordinates": [[[0.08, 0.03], [0.09, 0.03], [0.1, 0.03], [0.08, 0.03]]]}), 0.0), + mesh_feature(json!({"type": "Polygon", "coordinates": [[[0.0, 0.05], [0.01, 0.08], [0.02, 0.11], [0.0, 0.05]]]}), 0.0), mesh_feature( json!({"type": "Polygon", "coordinates": [[[0.06, 0.0], [0.07, 0.0], [0.070_000_000_01, 0.0], [0.07, 0.01], [0.06, 0.01], [0.06, 0.0]]]}), 30.0 @@ -54399,8 +54444,10 @@ fn stl_leaves_out_lines_and_skips_flat_triangles_and_says_so() { let tris = stl_triangles(&bytes); assert_eq!(tris.len(), 12 + 12); let said = |part: &str| s.notices.iter().any(|n| n.text.contains(part)); - assert!(said("Left out 2 polygon(s) and point(s) of zero height")); - assert!(said("left out 1 polyline")); + let lost = + |part: &str| s.notices.iter().any(|n| n.text.contains(part) && n.loss() == Some(rustgis_data::loss::LossCode::DroppedFeature)); + assert!(lost("Left out 2 polygon(s) and point(s) of zero height")); + assert!(lost("left out 1 polyline")); assert!(said("zero-area")); assert!(said("no units")); // A layer of squares gives neither the line nor the zero-area notices. @@ -54604,7 +54651,8 @@ fn web_scene_fans_caps_it_cannot_triangulate_and_says_so() { let mut s = mesh_session(json!([mesh_feature(far, 30.0), mesh_feature(far_line, 30.0), mesh_feature(square(0.0, false), 30.0)])); s.run("share.webScene", &json!({"path": path})).unwrap(); assert!( - s.notices.iter().any(|n| n.text == "2 feature(s) left out of the scene: a coordinate is too far from the map's centre"), + s.notices.iter().any(|n| n.text == "2 feature(s) left out of the scene: a coordinate is too far from the map's centre" + && n.loss() == Some(rustgis_data::loss::LossCode::DroppedFeature)), "{:?}", s.notices ); diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 59dcc7c978..4f0cfb9342 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -960,6 +960,13 @@ fn a_web_scene_leaves_out_what_it_cannot_place() { said.iter().any(|n| n.contains("1 feature(s) left out of the scene: a place can't be given in longitude/latitude")), "{said:?}" ); + assert!( + s.notices_since(mark) + .iter() + .any(|n| n.text.contains("left out of the scene: a place can't") + && n.loss() == Some(rustgis_data::loss::LossCode::DroppedFeature)), + "{said:?}" + ); } /// A held layer's feature with a place that can't be given in longitude/latitude is drawn without diff --git a/crates/engine/src/tests/scene_losses.rs b/crates/engine/src/tests/scene_losses.rs index 858980000b..ae8ba055f3 100644 --- a/crates/engine/src/tests/scene_losses.rs +++ b/crates/engine/src/tests/scene_losses.rs @@ -70,7 +70,12 @@ fn web_scene_reports_the_feature_limit_and_does_not_count_filtered_rows() { s.map_mut().add_dataset(ds); assert_eq!(positions(&scene(&mut s, "limit")), 400_000, "two positions per exported point"); let expected = "1 feature(s) left out of the scene: the 200000 feature limit was reached"; - assert_eq!(s.notices.iter().filter(|n| n.text == expected).count(), 1, "{:?}", s.notices); + assert_eq!( + s.notices.iter().filter(|n| n.text == expected && n.loss() == Some(rustgis_data::loss::LossCode::DroppedOverLimit)).count(), + 1, + "{:?}", + s.notices + ); s.run("layer.definitionQuery", &json!({"layer":"Points", "where":"i < 200000"})).unwrap(); s.notices.clear(); assert_eq!(positions(&scene(&mut s, "filtered-limit")), 400_000);