diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 65f0fe9178..06f72ce04e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3007,6 +3007,7 @@ impl Session { let mut landed = Vec::new(); let mut dates: Vec = Vec::new(); let mut not_utf8 = Vec::new(); + let mut source_counts = Vec::new(); let mut source_errors = Vec::new(); let mut source_error_count = 0; for map in &mut self.project.maps { @@ -3063,6 +3064,9 @@ impl Session { for note in layer.source.as_mut().map(|source| source.take_read_notes()).unwrap_or_default() { dates.push(note.prefixed(&layer.name)); } + if let Some((saved, current)) = layer.source.as_mut().and_then(|source| source.take_feature_count_change()) { + source_counts.push(notice_text::NoticeText::source_count_changed(&layer.name, saved, current)); + } if layer.source.as_mut().is_some_and(|source| source.take_display_window()) { landed.push(&*layer); } @@ -3074,6 +3078,9 @@ impl Session { for note in dates { self.say(note); } + for text in source_counts { + self.notify_text(text, false); + } for (loss, note) in not_utf8 { match loss { Some(code) => self.notify_loss(code, note), diff --git a/crates/engine/src/notice_text.rs b/crates/engine/src/notice_text.rs index 1d5f1becef..2c7af58112 100644 --- a/crates/engine/src/notice_text.rs +++ b/crates/engine/src/notice_text.rs @@ -58,6 +58,24 @@ impl NoticeText { }) } + /// Reports the net change in the source's size since the project was saved. + pub(crate) fn source_count_changed(name: &str, saved: u64, current: u64) -> Self { + let key = match (current, current > saved) { + (1, true) => "{name}: the source has {count} feature, {change} more than when the project was saved", + (1, false) => "{name}: the source has {count} feature, {change} fewer than when the project was saved", + (_, true) => "{name}: the source has {count} features, {change} more than when the project was saved", + (_, false) => "{name}: the source has {count} features, {change} fewer than when the project was saved", + }; + Self::format( + key, + [ + ("name", name.to_string().into()), + ("count", rustgis_map::graphics::commas(¤t.to_string()).into()), + ("change", rustgis_map::graphics::commas(&saved.abs_diff(current).to_string()).into()), + ], + ) + } + /// Renders trusted templates through the front end's formatter; literal data bypasses it. pub(crate) fn render(&self, format: &impl Fn(&str, &[(&str, &str)]) -> String) -> String { match self { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 00c183374c..00d00b1cd7 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -134,6 +134,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-publication-parts", "layout-publication-legend", "shaded-relief-shadow-softness", + LINKED_SOURCE_FEATURE_COUNT, ]; /// An offline area keeping the versions that lost a sync or a Bring Back /// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them. @@ -147,6 +148,8 @@ pub(crate) const NATIVE_COORDINATES: &str = "native-coordinates"; pub(crate) const PROJECT_CRS: &str = "project-crs"; /// Independent marker sizes alongside classified point colours (`Layer::size_by`). pub(crate) const SIZE_BY_CAPABILITY: &str = "classified-point-size"; +/// A linked source's baseline for comparing its count on the next open. +pub(crate) const LINKED_SOURCE_FEATURE_COUNT: &str = "linked-source-feature-count"; /// The most entries a document's `requires` may list: past it the document is refused without /// the rest being read. pub(crate) const MAX_REQUIRES: usize = 256; @@ -1815,6 +1818,9 @@ impl Project { { log::warn!("{}: {e}", l.name); } + if opened { + src.check_feature_count(); + } } l.normalize_selection(); let fields = l.dataset.fields.len(); diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 701fb728d7..852615006b 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1062,6 +1062,10 @@ fn removes_duplicate_labels(layer: &Layer) -> bool { layer.labels.in_order().any(|c| c.remove_duplicates.is_some()) } +fn saves_source_count(layer: &Layer) -> bool { + layer.source.as_ref().and_then(|source| source.feature_count_for_save()).is_some() +} + /// The capabilities a layer needs, in [`map_capabilities`]'s order. fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { [ @@ -1077,6 +1081,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { (label_clearance(layer), "label-clearance"), (removes_duplicate_labels(layer), "label-duplicates"), (held_natively(&layer.dataset), super::NATIVE_COORDINATES), + (saves_source_count(layer), super::LINKED_SOURCE_FEATURE_COUNT), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) @@ -1105,6 +1110,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) = (false, false, false, false, false, false, false); let (mut crisp, mut bed, mut walls_top, mut soft) = (false, false, false, false); + let mut source_count = false; for map in maps { offline_area_id |= map.offline_area_id.is_some(); // A blank basemap's paper colour (#2532), which an older reader would draw and save white. @@ -1113,6 +1119,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static weighed |= map.layers.iter().any(label_weight); cleared |= map.layers.iter().any(label_clearance); deduped |= map.layers.iter().any(removes_duplicate_labels); + source_count |= map.layers.iter().any(saves_source_count); // A tile layer drawn nearest (#2804), which an older reader would draw and save blended. crisp |= map.tiles.iter().any(|t| t.resampling != rustgis_map::raster::Resampling::Bilinear); // An older reader doesn't know the MGRS graticule (#1042 piece 8): it refuses the @@ -1180,6 +1187,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (mgrs, "graticule-mgrs"), (on_top, "graticule-on-top"), (grid_color, "graticule-color"), + (source_count, super::LINKED_SOURCE_FEATURE_COUNT), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0cf477dd2f..33138f1d68 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2095,6 +2095,71 @@ fn a_streamed_shapefile_says_dates_it_could_not_read_once() { assert!(err.contains("Load All Features"), "{err}"); } +/// A project saves the total even when its view holds fewer rows. Reopening compares +/// the source header once, before the first redraw, and accepts old projects. +#[test] +fn linked_source_count_is_compared_on_project_reopen() { + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let dir = Dir(std::env::temp_dir().join(format!("rustgis-linked-count-{}-{nanos}", std::process::id()))); + std::fs::create_dir(&dir.0).unwrap(); + let path = dir.0.join("points.geojson"); + let project = dir.0.join("linked.rgis"); + let write = |count| { + let features: Vec<_> = (1..=count) + .map(|rank| json!({"type": "Feature", "geometry": {"type": "Point", "coordinates": [0, rank]}, "properties": {"rank": rank}})) + .collect(); + std::fs::write(&path, json!({"type": "FeatureCollection", "features": features}).to_string()).unwrap(); + }; + let view = rustgis_geom::Extent::new(-0.1, 0.9, 0.1, 1.1); + write(2); + let mut s = Session::new(Project::default()); + s.run("map.basemap", &json!({"name": "paper"})).unwrap(); + s.run("layer.addData", &json!({"path": path, "name": "Parcels", "stream": true})).unwrap(); + s.run("layer.definitionQuery", &json!({"layer": "Parcels", "where": "rank = 1"})).unwrap(); + s.map_mut().sync_sources(&view, 1000.0, true); + assert_eq!(s.map().layer_by_name("Parcels").unwrap().dataset.features.len(), 1); + s.run("project.save", &json!({"path": project})).unwrap(); + let mut saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&project).unwrap()).unwrap(); + assert_eq!(saved["maps"][0]["layers"][0]["source"]["saved_feature_count"], 2); + assert_eq!(saved["requires"], json!(["linked-source-feature-count"])); + + for (count, legacy, expected) in [ + (2, false, None), + (1, false, Some("Parcels: the source has 1 feature, 1 fewer than when the project was saved")), + (3, false, Some("Parcels: the source has 3 features, 1 more than when the project was saved")), + (1, true, None), + ] { + write(count); + if legacy { + saved.as_object_mut().unwrap().remove("requires"); + saved["maps"][0]["layers"][0]["source"].as_object_mut().unwrap().remove("saved_feature_count"); + std::fs::write(&project, saved.to_string()).unwrap(); + } + let mut reopened = Session::new(Project::default()); + let mark = reopened.notice_mark(); + reopened.run("project.open", &json!({"path": project})).unwrap(); + if expected.is_some() { + assert_eq!(reopened.notices_since(mark).iter().filter(|note| Some(note.text.as_str()) == expected).count(), 1); + } + for _ in 0..2 { + reopened.map_mut().sync_sources(&view, 1000.0, true); + reopened.notice_landed_rasters(); + } + let notes = reopened.notices_since(mark); + let changes: Vec<_> = notes.iter().filter(|note| note.text.contains("the source has")).collect(); + assert_eq!(changes.iter().map(|note| note.text.as_str()).collect::>(), expected.into_iter().collect::>()); + if let Some(note) = changes.first() { + assert!(note.translated(|key, _| key.to_string()).unwrap().contains("{change}")); + } + } +} + /// A Shapefile read in place says, once, the text values `` its view reads took for empty, /// and its streamed exports (Export, Data Interop) say them too; a clean one says nothing (#2059). #[test] diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 868991549a..f6773a0d20 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -788,6 +788,7 @@ impl Layer { return src.is_pending(); } } + src.check_feature_count(); if let Some(info) = self.source.as_ref().and_then(|s| s.info()) { match self.fields_from_source(&info.fields, info.format) { Ok(fields) => { @@ -5152,6 +5153,8 @@ mod tests { let l = Layer::new_streamed(1, src); assert!(l.dataset.features.is_empty()); assert_eq!(l.feature_count(), count); + let saved = serde_json::to_value(&l.source).unwrap(); + assert_eq!(saved.get("saved_feature_count"), count.map(serde_json::Value::from).as_ref()); } // Not open yet: nothing to say. assert_eq!(Layer::new_streamed(1, source::SourceLayer::default()).feature_count(), None); diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index 6f9d2588e7..5d90dbc88d 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -119,6 +119,7 @@ impl AmbiguousAreas { /// A streamed layer's source. #[derive(Clone, Default, Serialize, Deserialize)] +#[serde(remote = "Self")] pub struct SourceLayer { /// The file it reads; reopened when the project loads. #[serde(default)] @@ -129,6 +130,12 @@ pub struct SourceLayer { /// The GeoPackage table. #[serde(default)] pub table: Option, + /// The whole-source count saved with this layer, until the reopened header is compared. + #[serde(default, skip_serializing_if = "Option::is_none", getter = "Self::feature_count_for_save")] + saved_feature_count: Option, + /// The whole-source count seen at the first source header check. + #[serde(skip)] + checked_feature_count: Option, /// A Shapefile's source CRS override, reapplied when its path is reopened. #[serde(default, skip_serializing_if = "Option::is_none")] pub shapefile_crs: Option, @@ -273,6 +280,18 @@ pub struct SourceLayer { pub sqlserver: Option, } +impl Serialize for SourceLayer { + fn serialize(&self, serializer: S) -> Result { + Self::serialize(self, serializer) + } +} + +impl<'de> Deserialize<'de> for SourceLayer { + fn deserialize>(deserializer: D) -> Result { + Self::deserialize(deserializer) + } +} + /// A PostGIS table a layer reads live. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PostgisOrigin { @@ -882,6 +901,8 @@ impl SourceLayer { path: _, file_name: _, table: _, + saved_feature_count: _, + checked_feature_count: _, shapefile_crs, embedded: _, handle: _, @@ -1073,7 +1094,44 @@ impl SourceLayer { if self.same_opening(live) { self.read_notes.clone_from(&live.read_notes); self.read_note_kinds.clone_from(&live.read_note_kinds); + self.saved_feature_count = live.saved_feature_count; + self.checked_feature_count = live.checked_feature_count; + } + } + + /// A direct file link's known whole-source count. Opening may have omitted unreadable rows + /// from that metadata. Conversions can contain a geometry subset, and live table counts can + /// be filtered or estimated. + fn linked_feature_count(&self) -> Option { + let linked = self.linked_file().is_some() || self.path.as_deref().is_some_and(rustgis_data::source::is_remote_name); + if self.gdal.is_some() || self.duckdb.is_some() || !linked { + return None; } + let handle = self.handle.as_ref()?; + if handle.skipped_at_open() > 0 { + return None; + } + handle.info().count + } + + /// The count this source will write, obtained without opening the source or reading rows. + /// Unopened links retain the last known count. + pub fn feature_count_for_save(&self) -> Option { + if self.is_open() { self.linked_feature_count() } else { self.checked_feature_count.or(self.saved_feature_count) } + } + + /// Records the first comparable header, independently of which rows the view asks for. + pub fn check_feature_count(&mut self) { + if self.saved_feature_count.is_some() && self.checked_feature_count.is_none() { + self.checked_feature_count = self.linked_feature_count(); + } + } + + /// Takes the saved-to-current difference once, including across subsequent view reads. + pub fn take_feature_count_change(&mut self) -> Option<(u64, u64)> { + let current = self.checked_feature_count?; + let saved = self.saved_feature_count.take()?; + (saved != current).then_some((saved, current)) } /// Whether another installed window needs its retained display expressions checked. @@ -2371,6 +2429,8 @@ impl SourceLayer { path, file_name: _, table: _, + saved_feature_count: _, + checked_feature_count: _, shapefile_crs: _, embedded, handle: _, diff --git a/schema/fixtures/linked_source_feature_count.rgis b/schema/fixtures/linked_source_feature_count.rgis new file mode 100644 index 0000000000..59ad8effd2 --- /dev/null +++ b/schema/fixtures/linked_source_feature_count.rgis @@ -0,0 +1 @@ +{"format":2,"name":"Linked source count","maps":[{"name":"Map","layers":[{"id":1,"name":"Parcels","visible":true,"dataset":{"name":"Parcels","geometry_type":"Point","fields":[{"name":"rank","ty":"Integer","alias":null}],"features":[],"source":"./points.geojson"},"renderer":{"Single":{"fill":[224,123,57,255],"stroke":[255,255,255,255],"stroke_width":1.0,"size":7.0,"marker":"Circle"}},"labels":{"enabled":false,"field":"rank","size":10.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto"},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":true,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"source":{"path":"./points.geojson","file_name":null,"table":null,"saved_feature_count":2},"geometry_rev":0}],"basemap":"Paper","camera":{"center":{"x":0.0,"y":167006.2942262065},"res":173.22577333514909,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":2}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[],"requires":["linked-source-feature-count"]} diff --git a/schema/project.schema.json b/schema/project.schema.json index af3226434b..bd54e2b200 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1295,7 +1295,8 @@ "layout-text-statistics", "layout-publication-parts", "layout-publication-legend", - "shaded-relief-shadow-softness" + "shaded-relief-shadow-softness", + "linked-source-feature-count" ], "type": "string" }, @@ -1419,7 +1420,8 @@ "layout-text-statistics", "layout-publication-parts", "layout-publication-legend", - "shaded-relief-shadow-softness" + "shaded-relief-shadow-softness", + "linked-source-feature-count" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2