Skip to content
Closed
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
7 changes: 7 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3007,6 +3007,7 @@ impl Session {
let mut landed = Vec::new();
let mut dates: Vec<rustgis_data::loss::Note> = 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 {
Expand Down Expand Up @@ -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));
Comment on lines +3067 to +3068

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.

AGENTS.md asks for one notice per kind with a count. This pushes one notice per linked layer, so a project with several changed links gives several notices of the same kind. The existing source_errors path already aggregates this way, with a count. The same pattern would fit here: collect (name, saved, current) and emit one source_count_changed-style notice with a count, or name the layers in a list. The test that checks one notice per layer would then need updating.

Category: agents-md

}
if layer.source.as_mut().is_some_and(|source| source.take_display_window()) {
landed.push(&*layer);
}
Expand All @@ -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),
Expand Down
18 changes: 18 additions & 0 deletions crates/engine/src/notice_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(&current.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 {
Expand Down
6 changes: 6 additions & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand Down Expand Up @@ -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();
Expand Down
8 changes: 8 additions & 0 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
[
Expand All @@ -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))
Expand Down Expand Up @@ -1105,6 +1110,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> 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.
Expand All @@ -1113,6 +1119,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> 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
Expand Down Expand Up @@ -1180,6 +1187,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> 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))
Expand Down
65 changes: 65 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>(), expected.into_iter().collect::<Vec<_>>());
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 `<Null>` its view reads took for empty,
/// and its streamed exports (Export, Data Interop) say them too; a clean one says nothing (#2059).
#[test]
Expand Down
3 changes: 3 additions & 0 deletions crates/map/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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);
Expand Down
60 changes: 60 additions & 0 deletions crates/map/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ impl AmbiguousAreas {

/// A streamed layer's source.
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(remote = "Self")]

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.

#[serde(remote = "Self")] is needed here only so that getter works on a private field. With a remote derive, the derive emits inherent serialize/deserialize functions and not trait impls, which is why the manual impl Serialize/Deserialize below call Self::serialize. Inherent methods win path resolution, so this is correct, but it reads like infinite recursion. A one-line comment saying so, and why a getter is needed, would save the next reader time.

Category: quality

pub struct SourceLayer {
/// The file it reads; reopened when the project loads.
#[serde(default)]
Expand All @@ -129,6 +130,12 @@ pub struct SourceLayer {
/// The GeoPackage table.
#[serde(default)]
pub table: Option<String>,
/// 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<u64>,
/// The whole-source count seen at the first source header check.
#[serde(skip)]
checked_feature_count: Option<u64>,
/// A Shapefile's source CRS override, reapplied when its path is reopened.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub shapefile_crs: Option<rustgis_data::raster::Crs>,
Expand Down Expand Up @@ -273,6 +280,18 @@ pub struct SourceLayer {
pub sqlserver: Option<SqlServerOrigin>,
}

impl Serialize for SourceLayer {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
Self::serialize(self, serializer)
}
}

impl<'de> Deserialize<'de> for SourceLayer {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::deserialize(deserializer)
}
}

/// A PostGIS table a layer reads live.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PostgisOrigin {
Expand Down Expand Up @@ -882,6 +901,8 @@ impl SourceLayer {
path: _,
file_name: _,
table: _,
saved_feature_count: _,
checked_feature_count: _,
shapefile_crs,
embedded: _,
handle: _,
Expand Down Expand Up @@ -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<u64> {
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<u64> {
if self.is_open() { self.linked_feature_count() } else { self.checked_feature_count.or(self.saved_feature_count) }
}
Comment on lines +1119 to +1121

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.

When a source is open, this returns the live header count and ignores the saved baseline. The baseline is only compared at check_feature_count, and take_feature_count_change only clears it later, in notice_landed_pixels. Any save that runs before that point overwrites the baseline with the current count, so the change is never reported. Two paths reach that state:

  • repair(false, …) (normalize_after, used when a map is imported) opens linked sources and never calls check_feature_count, because the check is gated on opened.
  • A source that opens with skipped rows returns None here, so the baseline and the linked-source-feature-count requirement are dropped with no notice.

A save of a project that was just opened, with no frame between, does the same. Keeping an uncompared or unsaid baseline until it is taken fixes all three. Please also add a regression test that saves before any view sync and one that imports a linked layer, since the current test only saves after a sync.

Suggested change
pub fn feature_count_for_save(&self) -> Option<u64> {
if self.is_open() { self.linked_feature_count() } else { self.checked_feature_count.or(self.saved_feature_count) }
}
pub fn feature_count_for_save(&self) -> Option<u64> {
// A baseline not yet compared or reported stays the count written: the header read now may differ from it.
if let Some(saved) = self.saved_feature_count {
return Some(saved);
}
if self.is_open() { self.linked_feature_count() } else { self.checked_feature_count }
}

Category: bug


/// 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.
Expand Down Expand Up @@ -2371,6 +2429,8 @@ impl SourceLayer {
path,
file_name: _,
table: _,
saved_feature_count: _,
checked_feature_count: _,
shapefile_crs: _,
embedded,
handle: _,
Expand Down
1 change: 1 addition & 0 deletions schema/fixtures/linked_source_feature_count.rgis
Original file line number Diff line number Diff line change
@@ -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"]}
6 changes: 4 additions & 2 deletions schema/project.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down Expand Up @@ -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
Expand Down
Loading