Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 46 additions & 13 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,9 +448,8 @@ impl Dataset {
/// Drawing converts geometry from it ([`raster::Crs::to`]), so a dataset that keeps the
/// coordinates it was read in can say so here without the map changing. Longitude/latitude
/// never fails to convert, and [`Dataset::hold_in`] only holds a dataset where every place
/// converts. The map draws none of a layer whose conversion fails (`Layer::projected_in`) and
/// doesn't say so yet: before a reader holds a file's own system (#2032 C2b), that needs a
/// notice, as AGENTS.md's "Never silent" asks.
/// converts. A place that can't be converted isn't drawn, and the session says so
/// ([`Dataset::unplaced_in_lonlat`]).
pub fn coord_crs(&self) -> raster::Crs {
self.held_in
}
Expand Down Expand Up @@ -492,8 +491,14 @@ impl Dataset {
/// coordinate (NaN, infinite) stays as it is, for the edit to judge as it does today; refused,
/// naming its system, when its system can't be converted or one of its places can't be.
pub fn geometry_to_lonlat<'a>(&self, g: &'a Geometry) -> std::result::Result<Cow<'a, Geometry>, String> {
let to = self.coord_crs().to(raster::Crs::LonLat)?;
Self::converted_to_lonlat(&to, g)
Self::geometry_to_lonlat_by(&self.lonlat_conversion()?, g)
}

/// [`Dataset::geometry_to_lonlat`] by `to`, its [`Dataset::lonlat_conversion`] made once for
/// many geometries: refused, naming its system, when one of the geometry's places can't be
/// converted.
pub fn geometry_to_lonlat_by<'a>(to: &raster::Reprojection, g: &'a Geometry) -> std::result::Result<Cow<'a, Geometry>, String> {
Self::converted_to_lonlat(to, g)
.ok_or_else(|| format!("a place of this feature in {} can't be given in longitude/latitude", to.source().label()))
}

Expand Down Expand Up @@ -973,6 +978,30 @@ impl Dataset {
}
}

/// How many of its features have a place that can't be given in longitude/latitude, which
/// the map, the globe and the drawings made from either leave out: none while its coordinates
/// are longitude/latitude, as every dataset's are today. Refused, naming its system, when the
/// system can't be converted at all (then none of it is drawn). It reads every place through
/// the conversion, on the calling thread, with no Cancel: as long as converting the layer
/// takes.
pub fn unplaced_in_lonlat(&self) -> std::result::Result<usize, String> {
let to = self.lonlat_conversion()?;
if to.is_identity() {
return Ok(0);
}
// Counted, not converted: a place that isn't a number is kept, as a conversion keeps it.
let unplaced = |g: &Geometry| {
let lost = std::cell::Cell::new(false);
g.for_each_coord(|c| {
if !lost.get() && c.is_finite() && to.point(c).is_none() {
lost.set(true);
}
});
lost.get()
};
Ok(self.features.rows().filter_map(|r| r.geometry()).filter(|g| unplaced(g)).count())
}

/// The dataset in longitude/latitude, the space analysis tools work in: borrowed while its
/// coordinates are longitude/latitude ([`Dataset::coord_crs`]), as every dataset's are today;
/// otherwise a copy with every geometry converted, missing coordinates kept. Refused, naming
Expand Down Expand Up @@ -1017,15 +1046,20 @@ impl Dataset {
/// `results`, a dataset in longitude/latitude made from this one (a tool's update of it), in
/// its own coordinates: as it is while they are longitude/latitude, as every dataset's are
/// today; otherwise each geometry written back as an edit is ([`Dataset::edit_from_lonlat`]),
/// its stored places kept as stored. Refused, naming the first feature, when one of its places
/// can't be held in its system.
/// its stored places kept as stored. Every stored place is read, but only those the results
/// read as are held, so what is held is as large as the results, not the layer. Refused, naming
/// the first feature, when one of its places can't be held in its system.
pub fn results_from_lonlat(&self, mut results: Dataset) -> std::result::Result<Dataset, String> {
if self.edits_in_lonlat() {
return Ok(results);
}
let mut held = HeldPlaces::default();
for g in self.features.iter().filter_map(|f| f.geometry.as_ref()) {
self.hold_places(g, None, &mut held);
let edits: Vec<&Geometry> = results.features.rows().filter_map(|r| r.geometry()).collect();
if !edits.is_empty() {
held.want_only(&edits);
for g in self.features.rows().filter_map(|r| r.geometry()) {
self.hold_places(g, None, &mut held);
}
}
for f in &mut results.features {
if let Some(g) = f.geometry.take() {
Expand All @@ -1039,10 +1073,9 @@ impl Dataset {
/// `merged`, its features in longitude/latitude as [`Dataset::in_lonlat`] gives them with some
/// updated, added or left out (an offline area's sync), in its own coordinates: a feature whose
/// id isn't in `changed` is taken as it holds it, not converted back; a changed one is written
/// back as [`Dataset::results_from_lonlat`] writes it: every stored place is read, but only
/// those the changes read as are held, so what is held is as large as the changes, not the
/// layer. As it is while its
/// coordinates are longitude/latitude, as every dataset's are today.
/// back as [`Dataset::results_from_lonlat`] writes it, holding only the stored places the
/// changes read as. As it is while its coordinates are longitude/latitude, as every dataset's
/// are today.
pub fn merged_from_lonlat(
&self,
mut merged: Dataset,
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1280,14 +1280,15 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result<Mesh, String>
};
let mut mesh = Mesh { keep_lines, ..Mesh::default() };
let rows = l.visible_rows();
let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?;
for (row, ft) in l.dataset.features.iter().enumerate() {
if row.is_multiple_of(256) {
rustgis_data::progress::check().map_err(|e| e.to_string())?;
}
// A feature with no geometry draws nothing, so its height is neither used nor reported.
let Some(g) = ft.geometry.as_ref().filter(|_| rows.get(row) == Some(&true)) else { continue };
// Placed from longitude/latitude, whatever system the layer holds its coordinates in.
let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id))?;
let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id))?;
// A height that isn't a finite number takes the default, and is counted.
let height = match hf {
Some(fi) => match l.dataset.value(row, fi).as_f64().filter(|h| h.is_finite()) {
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/cmd/labels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -867,13 +867,14 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult {
out_fields,
);
let mut moved = Vec::new();
let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?;

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.

Behaviour change (confidence: low, ~0.3). The layer's conversion is now resolved before the loop, so the command fails for an unconvertible system even when no selected row has a geometry. Before, the error came only from a feature that reached the conversion. The same pattern appears in items.rs (layer_mesh), sharing.rs (styled_features), stac_area.rs (selected) and workspace.rs (selected_lines). Failing here is consistent with "unusable results are errors", so this is probably acceptable. The PR doesn't mention it, though, so please state it in the PR body or confirm the early failure is intended.

for (row, ft) in l.dataset.features.rows().enumerate() {
if rows.get(row) != Some(&true) {
continue;
}
// In longitude/latitude, as the annotation layer holds its points and moved labels are.
let Some(g) = ft.geometry() else { continue };
let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?;
let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?;
let Some(at) = g.label_point() else { continue };
for (i, class) in matcher.classes_of(&l.dataset, row).filter(|(_, c)| c.visible) {
let text = match by_text(i).and_then(|e| e.text_cut(&l.dataset, row)) {
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/cmd/sharing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,7 @@ fn styled_features(l: &Layer, budget: &mut usize) -> Result<Vec<Value>, String>
let mut out = Vec::new();
// Its symbol by expression (no map scale: the page zooms on its own).
let styler = l.styler(None);
let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?;
for (row, ft) in l.dataset.features.rows().enumerate() {
if *budget == 0 {
break;
Expand All @@ -523,7 +524,7 @@ fn styled_features(l: &Layer, budget: &mut usize) -> Result<Vec<Value>, String>
continue;
}
let Some(g) = ft.geometry() else { continue };
let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?;
let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?;
let sym = styler.symbol(row);
let props: serde_json::Map<String, Value> =
l.dataset.fields.iter().enumerate().map(|(i, f)| (f.name.clone(), json!(l.dataset.value(row, i).to_string()))).collect();
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/cmd/stac_area.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,10 @@ fn selected(s: &Session, p: &Value) -> Result<(Vec<Geometry>, Vec<String>), Stri
}
// In longitude/latitude, as a search area is, whatever system the layer holds them in.
let mut geometries: Vec<Geometry> = Vec::new();
let to = layer.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", layer.name))?;
for f in layer.selection.iter().filter_map(|row| layer.dataset.features.row(*row)) {
if let Some(g) = f.geometry() {
let g = layer.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", layer.name, f.id()))?;
let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", layer.name, f.id()))?;
geometries.push(g.into_owned());
}
}
Expand Down
42 changes: 31 additions & 11 deletions crates/engine/src/cmd/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,9 +498,12 @@ fn selected_lines(s: &Session, p: &Value, all: bool) -> Result<Vec<Vec<Coord>>,
};
// Sampled in longitude/latitude, whatever system the layer holds its coordinates in.
let mut out: Vec<Vec<Coord>> = Vec::new();
let to = l.dataset.lonlat_conversion().map_err(|e| format!("{n}: {e}"))?;
for f in rows.iter().filter_map(|r| l.dataset.features.row(*r)) {
let Some(g) = f.geometry().filter(|g| matches!(g, Geometry::Line(_))) else { continue };
if let Geometry::Line(parts) = &*l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{n}: feature {}: {e}", f.id()))? {
if let Geometry::Line(parts) =
&*rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{n}: feature {}: {e}", f.id()))?
{
let v: Vec<Coord> = parts.iter().flatten().copied().collect();
if v.len() >= 2 {
out.push(v);
Expand Down Expand Up @@ -884,16 +887,33 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) -
// system the source, its last synced copy or the package hold them in; the source is
// written back in its own, its unchanged places as stored (`results_from_lonlat`).
let ol_ds = ol.dataset.in_lonlat().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?;
let baseline = area
.data
.layers
.iter()
.find(|l| l.id == ol.id)
.map(|l| l.dataset.in_lonlat())
.transpose()
.map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?;
let last_synced = area.data.layers.iter().find(|l| l.id == ol.id).map(|l| &l.dataset);
let baseline = last_synced.map(|d| d.in_lonlat()).transpose().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?;
// Whether a feature was edited offline: the returned copy against the last synced one,
// as they are when both are held in the same system (as an offline map in the project
// and its area are), so a conversion that changed meanwhile (a datum grid downloaded)
// can't make an unedited feature look edited; else both in longitude/latitude.
type ById<'a> = std::collections::HashMap<u64, rustgis_data::RowRef<'a>>;
fn by_id(d: &rustgis_data::Dataset) -> ById<'_> {
d.features.rows().map(|r| (r.id(), r)).collect()
}
let raw: Option<(ById<'_>, ById<'_>)> =
last_synced.filter(|b| b.coord_crs() == ol.dataset.coord_crs()).map(|b| (by_id(b), by_id(&ol.dataset)));
let same_row = |a: rustgis_data::RowRef, b: rustgis_data::RowRef| a.geometry() == b.geometry() && a.values().eq(b.values());
// `lonlat_base` and `lonlat_now`, the copies in longitude/latitude, are used only when
// the two aren't held in the same system.
let unchanged_offline = |fid: u64, lonlat_base: Option<&&rustgis_data::Feature>, lonlat_now: &rustgis_data::Feature| match &raw
{
Some((raw_base, raw_now)) => raw_base.get(&fid).is_some_and(|b| raw_now.get(&fid).is_some_and(|n| same_row(*b, *n))),
None => lonlat_base.is_some_and(|b| *b == lonlat_now),
};
let same_as_last = match (&raw, &baseline) {
(Some(_), Some(_)) => last_synced.is_some_and(|b| b.features == ol.dataset.features),
(None, Some(b)) => b.features == ol_ds.features,

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.

Bug (confidence: medium, ~0.6). This is the case the PR's third bullet says it fixes, and it still isn't fixed for a returned package. When the returned copy is held in longitude/latitude but the source and last-synced copy are held in UTM, raw is None, so both sides are converted with the conversion in force at sync time. Failure: the package is downloaded before a datum grid is installed (fallback conversion G1), the grid is installed, and then the area is synced. For every unedited feature, baseline (G2) != ol_ds (G1), so changed_offline is true and *x = f.clone() overwrites the source with G1-converted coordinates. If the source was edited since the last sync, the conflict is reported, but the source edit is still replaced. The new test covers only the same-system path, and the PR body acknowledges that.

Suggested fix: compare the returned copy against the lonlat copy frozen when the area was downloaded or last synced, rather than re-converting the baseline now.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Kept for C2c, and the PR body now says so under "Not in this PR". The same-system path covers an offline map in the project. A field package returned in longitude/latitude to a source held in UTM is still compared in longitude/latitude, because there's no longitude/latitude copy from the download to compare it with: the area keeps its last synced copy in the source's system. Packages from held sources first occur with the flip, so the fix goes there: keep the area's longitude/latitude copy from packaging and compare the returned copy with it. Until then, the conflict notice names such a feature and Undo restores the source.

_ => false,
};
if !offline_fields_match(&sl.dataset.fields, &ol_ds.fields)
&& baseline.as_ref().is_none_or(|b| !offline_fields_match(&b.fields, &ol_ds.fields) || b.features != ol_ds.features)
&& baseline.as_ref().is_none_or(|b| !offline_fields_match(&b.fields, &ol_ds.fields) || !same_as_last)
{
return Err(format!("cannot sync layer '{}': source and offline fields differ; align the fields before syncing", ol.name));
}
Expand Down Expand Up @@ -926,7 +946,7 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) -
for f in &ol_ds.features {
let fid = f.id;
if had.contains(&fid) {
let changed_offline = base.get(&fid).is_none_or(|b| *b != f);
let changed_offline = !unchanged_offline(fid, base.get(&fid), f);
match sl.dataset.features.iter_mut().find(|x| x.id == fid) {
Some(x) if changed_offline && x != f => {
if base.get(&fid).is_some_and(|b| *b != x) {
Expand Down
60 changes: 60 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,10 @@ pub struct Session {
pub(crate) crs_used_elsewhere: Vec<(String, String)>,
/// When the frame path last looked for missing datum grids ([`Session::say_grid_notes`]).
grid_notes_checked: Option<web_time::Instant>,
/// Each layer held in another system (by instance) and the geometry revision and system whose
/// places were last counted for [`Session::say_unplaced`], so a version of a layer is looked at
/// once.
unplaced_checked: std::collections::HashMap<u64, (u64, rustgis_data::raster::Crs)>,
/// The datum grids the map's layers were last projected with
/// ([`rustgis_data::raster::crs::grid_generation`]).
grid_generation: u64,
Expand Down Expand Up @@ -1337,6 +1341,7 @@ impl Session {
grid_pairs: Vec::new(),
crs_used_elsewhere: Vec::new(),
grid_notes_checked: None,
unplaced_checked: Default::default(),
grid_generation: rustgis_data::raster::crs::grid_generation(),
grid_downloads_said: Default::default(),
grid_turns: 0,
Expand Down Expand Up @@ -1767,6 +1772,7 @@ impl Session {
self.undo_memory.publish(&self.project, &self.undo, &self.redo);
// And the coordinate systems that needed a missing datum grid, after every command.
self.say_grid_notes();
self.say_unplaced();
// A plugin's command waiting for its fetches answers `pending` and runs again when they
// land: logged then, once. (Another command's `pending`, a download the web app makes, is
// logged as it is asked for: nothing runs it again.)
Expand Down Expand Up @@ -3060,6 +3066,60 @@ impl Session {
if due {
self.grid_notes_checked = Some(web_time::Instant::now());
self.say_grid_notes();
self.say_unplaced();
}
}

/// Says, once for each version of a layer's geometry, that a layer held in another system
/// has features with a place that can't be given in longitude/latitude, which the map and
/// the globe draw from: they draw such a feature without that place (a line broken there, a
/// point not at all), and labels' lines, block diagrams and terrain water leave it out. Or
/// that none of the layer is drawn, when its system can't be converted.
/// Layers in longitude/latitude, every layer read today, are passed over at no cost. A held
/// layer's count reads each of its places through the conversion, on the UI thread with no
/// Cancel, once per version of its geometry: as long as converting it for the map takes.
fn say_unplaced(&mut 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.

Performance / Never hold the window (confidence: medium, ~0.5). say_unplaced runs synchronously on the UI thread after every command, and at frame cadence through say_grid_notes_now_and_then. Every edit bumps geometry_rev, so the next check walks every place of each held layer (unplaced_in_lonlat, data/src/lib.rs:980). For a large held layer that is a full conversion pass on the UI thread, with no Cancel, no progress count, and no doc comment saying the long step is unchecked. The PR says counting "keeps nothing", but not how long it takes. Either move the count off the UI thread, or state the cost and bound it per frame.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Stated in bafe9e2, with the move off the UI thread left for part 2 (#2032). The doc comments of say_unplaced and Dataset::unplaced_in_lonlat now say that it runs on the UI thread with no Cancel, once per version of a held layer's geometry, and takes as long as converting the layer. The map's projected cache already converts the same layer on the same thread after an edit, so it about doubles a cost that's already there. Part 2 moves both off the thread, with Cancel and a benchmark.

// One notice per kind, with the count and the layers it is about.
let (mut features, mut partly, mut undrawn) = (0usize, Vec::new(), Vec::new());
let mut seen = std::collections::HashSet::new();
for map in &self.project.maps {
for l in map.layers.iter().filter(|l| !l.is_raster() && l.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat) {
seen.insert(l.instance_id());
let version = (l.geometry_rev(), l.dataset.coord_crs());
if self.unplaced_checked.insert(l.instance_id(), version) == Some(version) {
continue;
}
match l.dataset.unplaced_in_lonlat() {
Ok(0) => {}
Ok(n) => {
features += n;
partly.push(format!("map '{}', layer '{}' ({n})", map.name, l.name));
}
Err(e) => undrawn.push(format!("map '{}', layer '{}': {e}", map.name, l.name)),
}
}
}
// Layers gone are forgotten, so the map stays as small as the project.
self.unplaced_checked.retain(|id, _| seen.contains(id));
let listed = |v: &[String]| {
let more = v.len().saturating_sub(10);
let shown = v.iter().take(10).cloned().collect::<Vec<_>>().join("; ");
if more > 0 { format!("{shown}; and {more} more") } else { shown }
};
if features > 0 {
let text = format!(
"{features} feature(s) have a place that can't be given in longitude/latitude: the map and the globe draw them without it, and labels' lines, block diagrams and terrain water leave them out ({})",
listed(&partly)
);
self.notice(text, rustgis_data::diagnostics::Severity::Warning);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
if !undrawn.is_empty() {
let text = format!(
"{} layer(s) aren't drawn, as their system can't be given in longitude/latitude: {}",
undrawn.len(),
listed(&undrawn)
);
self.notice(text, rustgis_data::diagnostics::Severity::Warning);

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 notices (confidence: low-medium, ~0.4). AGENTS.md asks for "one notice per kind with a count". This loop emits one notice per held layer, so two held layers with undrawable features give two notices of the same kind. Aggregate them into a single notice that names the layers and gives the total count.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in bafe9e2: one notice per kind. One counts every held layer's features with a place that can't be given in longitude/latitude, and names each map and layer with its count (up to 10, then "and N more"). The other names the layers whose system can't be converted at all. a_held_layers_undrawable_features_are_said_once now checks two layers in one notice.

}
}

Expand Down
Loading
Loading