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
4 changes: 2 additions & 2 deletions crates/data/src/gml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -879,8 +879,8 @@ mod tests {
}

/// A place a file's system can't give in longitude/latitude is kept missing (NaN), as when the
/// reader converted the file, so the layer still saves and is read in longitude/latitude; its
/// other places keep the file's numbers.
/// reader converted the file, so the layer's places that convert are still read in
/// longitude/latitude; its other places keep the file's numbers.
#[test]
fn a_place_with_no_longitude_latitude_is_kept_missing() {
let gml = r#"<ogr:FeatureCollection xmlns:ogr="http://ogr.maptools.org/" xmlns:gml="http://www.opengis.net/gml">
Expand Down
136 changes: 69 additions & 67 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,8 +411,9 @@ impl<'de> Deserialize<'de> for Features {

/// A feature class: a named table of features sharing a schema and geometry type.
/// Its geometry is in the system it holds its coordinates in ([`Dataset::held_in`]): a file's
/// own system for a file read in one, WGS 84 longitude/latitude for one without, for features
/// drawn or made by tools and plugins, and for a saved project's.
/// own system for a file read in one (and a saved project keeps it), WGS 84 longitude/latitude
/// for one without, for features drawn or made by tools and plugins, and for a project saved by
/// an older release.
#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct Dataset {
pub name: String,
Expand All @@ -424,7 +425,8 @@ pub struct Dataset {
pub source: Option<String>,
/// The coordinate system it was read in, when that isn't longitude/latitude: what an export
/// writes by default. Its geometry is in [`Dataset::held_in`], which is this system for a file
/// read now and longitude/latitude for one a saved project holds.
/// read now or a project saved by this release, and longitude/latitude for one a project saved
/// by an older release holds.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub crs: Option<raster::Crs>,
/// Import lost geometry while interpreting source coordinates. Defining a projection cannot
Expand All @@ -440,9 +442,11 @@ pub struct Dataset {
#[serde(skip)]
pub windowed: bool,
/// The system its geometry is in ([`Dataset::coord_crs`]): longitude/latitude unless it was
/// put in another with [`Dataset::hold_in`]. A project saves its features in
/// longitude/latitude, as older releases read them, so a saved dataset reads back held there.
#[serde(skip, default = "held_in_lonlat")]
/// put in another with [`Dataset::hold_in`]. A project saves its features in it, exactly,
/// with the system beside them (`held_in`, absent for longitude/latitude, as every release
/// saved them before), so a saved dataset reads back held as it was; a project with one
/// requires `native-coordinates`.
#[serde(default = "held_in_lonlat")]
pub held_in: raster::Crs,
/// The system of the map it is shown on, when that map draws it straight into its own system
/// (the map's `direct_system`, set by the map): its places are then given in
Expand All @@ -453,7 +457,8 @@ pub struct Dataset {
pub shown_in: Option<raster::Crs>,
}

/// What a dataset read from a project holds its coordinates in ([`Dataset::held_in`]).
/// What a dataset saved without a system of its own holds its coordinates in
/// ([`Dataset::held_in`]): longitude/latitude, as every release saved them before.
fn held_in_lonlat() -> raster::Crs {
raster::Crs::LonLat
}
Expand Down Expand Up @@ -653,20 +658,8 @@ impl Serialize for Dataset {
st.serialize_field("geometry_type", &self.geometry_type)?;
st.serialize_field("fields", &self.fields)?;
let none: &[Feature] = &[];
// In longitude/latitude, as every release reads a saved dataset's features: converted a
// row at a time as it is written, so a large layer held in another system isn't copied
// whole. A place that can't be given there fails the save, naming its feature, rather
// than being saved wrong; `hold_in` only holds a dataset whose places all convert.
if self.windowed {
st.serialize_field("features", none)?;
} else {
let to = self.lonlat_conversion().map_err(serde::ser::Error::custom)?;
if to.is_identity() {
st.serialize_field("features", self.features.as_slice())?;
} else {
st.serialize_field("features", &SavedInLonLat { ds: self, to })?;
}
}
// In the system it holds them in, exactly, as it reads them back (`held_in`, below).
st.serialize_field("features", if self.windowed { none } else { self.features.as_slice() })?;

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.

Possible cancellation regression (confidence about 40%). The removed SavedInLonLat path checked Cancel per row (stop_when_asked(i)) when it converted a held layer. Now a held layer is one serialize call over features.as_slice(), with no check. Lon/lat layers already worked this way, so the PR matches them. But a held layer used to be cancellable during save, and the PR body doesn't mention losing that. Please check whether a project save runs with Cancel. If it does, a long check here is needed, or the doc comment should say the step is not cancellable.

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 as is. The per-row check belonged to the conversion to lon/lat while writing, which was the slow part. That conversion is gone, so a held layer is now written as its rows are, exactly as lon/lat layers always were, with no per-row Cancel check. A save is no longer slower for a held layer than for a lon/lat one.

st.serialize_field("source", &self.source)?;
if let Some(crs) = &self.crs {
st.serialize_field("crs", crs)?;
Expand All @@ -683,53 +676,13 @@ impl Serialize for Dataset {
} else {
st.skip_field("zm_dropped")?;
}
st.end()
}
}

/// A dataset's rows in longitude/latitude as [`Dataset::in_lonlat`] gives them, each converted as
/// it is written ([`Dataset`]'s `Serialize`), written as [`Feature`] writes itself.
struct SavedInLonLat<'a> {
ds: &'a Dataset,
to: raster::Reprojection,
}

impl Serialize for SavedInLonLat<'_> {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::{Error, SerializeSeq, SerializeStruct};
struct Values<'a>(RowRef<'a>);
impl Serialize for Values<'_> {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
s.collect_seq(self.0.values())
}
}
struct Row<'a>(RowRef<'a>, Option<Geometry>);
impl Serialize for Row<'_> {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
let mut st = s.serialize_struct("Feature", 3)?;
st.serialize_field("id", &self.0.id())?;
st.serialize_field("geometry", &self.1)?;
st.serialize_field("attrs", &Values(self.0))?;
st.end()
}
}
let mut seq = s.serialize_seq(Some(self.ds.features.len()))?;
for (i, r) in self.ds.features.rows().enumerate() {
stop_when_asked(i).map_err(S::Error::custom)?;
let geometry = match r.geometry() {
Some(g) => Some(convert_keeping_missing(&self.to, g, &HeldPlaces::default()).ok_or_else(|| {
S::Error::custom(format!(
"{}: feature {} has a place in {} that can't be given in longitude/latitude",
self.ds.name,
r.id(),
self.to.source().label()
))
})?),
None => None,
};
seq.serialize_element(&Row(r, geometry))?;
// Absent for longitude/latitude, as every release saved a dataset before.
if self.held_in != raster::Crs::LonLat && !self.windowed {
st.serialize_field("held_in", &self.held_in)?;
} else {
st.skip_field("held_in")?;
}
seq.end()
st.end()
}
}

Expand Down Expand Up @@ -1435,6 +1388,55 @@ fn convert_keeping_missing(to: &raster::Reprojection, g: &Geometry, held: &HeldP
mod tests {
use super::*;

/// A dataset held in another system saves its features there, exactly, with the system
/// beside them, and reads back held as it was, bit for bit, with no conversion (#2032 C2d):
/// in UTM, in Robinson and in a system given by its PROJ definition. A window onto a source
/// saves no rows, and one in longitude/latitude no system, as every release saved them.
#[test]
fn a_held_dataset_reads_back_bit_for_bit() {
let defined =
raster::Crs::parse("+proj=tmerc +lat_0=0 +lon_0=9 +k=0.9996 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs").unwrap();
let bits = |ds: &Dataset| -> Vec<Vec<(u64, u64)>> {
ds.features
.rows()
.map(|r| {
let mut out = Vec::new();
if let Some(g) = r.geometry() {
g.for_each_coord(|c| out.push((c.x.to_bits(), c.y.to_bits())));
}
out
})
.collect()
};
for crs in [raster::Crs::Epsg(32632), raster::Crs::parse("ESRI:54030").unwrap(), defined] {
let mut ds = Dataset::new("held", GeometryType::Polyline, vec![Field::new("n", FieldType::Integer)]);
let line = |x: f64| vec![Coord::new(x, 48.7), Coord::new(x + 0.013, 48.71), Coord::new(x + 0.031, 48.69)];
ds.push(Some(Geometry::Line(vec![line(11.5), line(11.6)])), vec![Value::Int(1)]);
ds.push(None, vec![Value::Int(2)]);
ds.push(Some(Geometry::Line(vec![line(8.1)])), vec![Value::Int(3)]);
ds.hold_in(crs).unwrap();
// Through JSON text, as a project saves it.
let saved = serde_json::to_string(&ds).unwrap();
let held_in = serde_json::from_str::<serde_json::Value>(&saved).unwrap()["held_in"].clone();
assert_eq!(held_in, serde_json::to_value(crs).unwrap(), "{}", crs.label());
let back: Dataset = serde_json::from_str(&saved).unwrap();
assert_eq!(back.coord_crs(), crs, "{}", crs.label());
assert_eq!(bits(&back), bits(&ds), "{}", crs.label());
assert_eq!(back.features.len(), 3);
}
let mut window = Dataset::new("window", GeometryType::Point, vec![]);
window.push(Some(Geometry::Point(Coord::new(11.5, 48.7))), vec![]);
window.hold_in(raster::Crs::Epsg(32632)).unwrap();
window.windowed = true;
let v = serde_json::to_value(&window).unwrap();
assert!(v.get("held_in").is_none() && v["features"] == serde_json::json!([]), "{v}");
let mut plain = Dataset::new("plain", GeometryType::Point, vec![]);
plain.push(Some(Geometry::Point(Coord::new(11.5, 48.7))), vec![]);
let v = serde_json::to_value(&plain).unwrap();
assert!(v.get("held_in").is_none(), "{v}");
assert_eq!(serde_json::from_value::<Dataset>(v).unwrap().coord_crs(), raster::Crs::LonLat);
}

/// A layer made from another is held as that one is, with its system for exports; one with a
/// place the system can't hold stays in longitude/latitude with no system of its own.
#[test]
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -862,8 +862,8 @@ fn package_map(s: &mut Session, mobile: bool, tol: f64) -> Result<Vec<u8>, Strin
if l.is_raster() || tol <= 0.0 {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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.

Test gap (confidence about 60%). The PR body says a mobile package at tolerance 0 keeps a held layer in its own system and requires native-coordinates. That is a change from the previous lon/lat output. The only mobile-package test with a held layer, a_held_layer_is_shared_alike (held_layers.rs:521), uses tolerance 0.0001, and I found no held-layer test at tolerance 0. Please add one that saves a mobile package at "tolerance": 0 and asserts both the requires header and that the layers reopen bit for bit. This is a coverage point, not the design question already raised in the earlier thread on this line.

continue;
}
// Simplified in longitude/latitude, as the package saves it, whatever system the
// layer holds its coordinates in.
// Simplified in longitude/latitude, as the tolerance is in degrees, whatever system
// the layer holds its coordinates in; the package saves it there.
if let std::borrow::Cow::Owned(ds) = l.dataset.in_lonlat()? {
l.dataset = ds;
}
Expand Down
13 changes: 10 additions & 3 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,11 @@ pub const CAPABILITIES: &[&str] = &[
"zarr-window",
"blank-paper",
"layout-frame-border",
NATIVE_COORDINATES,
];
/// A layer or table saved in a coordinate system of its own, not longitude/latitude
/// (`Dataset::held_in`, #2032 C2d): an older reader would read its coordinates as degrees.
pub(crate) const NATIVE_COORDINATES: &str = "native-coordinates";
/// Independent marker sizes alongside classified point colours (`Layer::size_by`).
pub(crate) const SIZE_BY_CAPABILITY: &str = "classified-point-size";
/// The most entries a document's `requires` may list: past it the document is refused without
Expand Down Expand Up @@ -515,12 +519,15 @@ struct TableFile {
crs_incomplete: bool,
#[serde(default)]
zm_dropped: bool,
/// The system its features are in, when not longitude/latitude (`Dataset::held_in`).
#[serde(default)]
held_in: Option<rustgis_data::raster::Crs>,
}

impl From<TableFile> for Table {
/// Loads stored data under a fresh runtime identity, never one supplied by the file.
fn from(t: TableFile) -> Self {
let TableFile { id, name, geometry_type, fields, features, source, crs, crs_incomplete, zm_dropped } = t;
let TableFile { id, name, geometry_type, fields, features, source, crs, crs_incomplete, zm_dropped, held_in } = t;
Table {
id,
instance_id: next_table_instance(),
Expand All @@ -534,8 +541,8 @@ impl From<TableFile> for Table {
crs_incomplete,
zm_dropped,
windowed: false,
// Saved in longitude/latitude, as `Dataset`'s own saving writes them.
held_in: rustgis_data::raster::Crs::LonLat,
// As `Dataset`'s own saving writes them.
held_in: held_in.unwrap_or(rustgis_data::raster::Crs::LonLat),
shown_in: None,
},
}
Expand Down
16 changes: 15 additions & 1 deletion crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ impl Project {
{
required.push("field-generation");
}
// A table saved in a coordinate system of its own, as a layer's is (map_capabilities).
if !required.contains(&super::NATIVE_COORDINATES) && self.tables.iter().any(|t| held_natively(&t.dataset)) {
required.push(super::NATIVE_COORDINATES);
}
// Saved symbology keeps its images too.
if !required.contains(&"picture-markers") && self.styles.iter().any(|s| s.renderer.has_picture_markers()) {
required.push("picture-markers");
Expand Down Expand Up @@ -402,6 +406,13 @@ fn zarr_window(layer: &Layer) -> bool {
layer.raster.as_ref().and_then(|r| r.time_zarr.as_ref()).is_some_and(|z| z.window.is_some())
}

/// Whether a dataset is saved in a coordinate system of its own (`Dataset::held_in`): an older
/// reader would take its coordinates for longitude/latitude, and save it again without its
/// system (one with no features too, such as a template's layers).
fn held_natively(ds: &rustgis_data::Dataset) -> bool {

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.

Possible rule conflict (confidence about 50%). held_natively exempts a held layer with no features, but Dataset::serialize still writes held_in for it. An older release then opens the project without refusing, and saves it again without held_in, so the layer's system is lost while the file is still rewritten. AGENTS.md says a file is "never saved again without what this version couldn't read". The exemption may be deliberate for template layers, but it should be stated in docs/maintaining.md, or the requirement should drop the features check. Please confirm the intent.

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 4da2da1: the exemption is gone. A held layer with no features requires native-coordinates too, since held_in is still written and an older reader would save it again without it. The test now asserts that, and docs/maintaining.md says it.

!ds.windowed && ds.coord_crs() != rustgis_data::raster::Crs::LonLat
}

/// The capabilities a layer needs, in [`map_capabilities`]'s order.
fn layer_capabilities(layer: &Layer) -> Vec<&'static str> {
[
Expand All @@ -410,6 +421,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> {
(layer.size_by.is_some(), super::SIZE_BY_CAPABILITY),
(layer.has_picture_markers(), "picture-markers"),
(zarr_window(layer), "zarr-window"),
(held_natively(&layer.dataset), super::NATIVE_COORDINATES),
]
.into_iter()
.filter_map(|(used, name)| used.then_some(name))
Expand All @@ -430,7 +442,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
mut pictures,
mut zarr,
) = (false, false, false, false, false, false, false, false, false, false, false);
let (mut offline_area_id, mut paper) = (false, false);
let (mut offline_area_id, mut paper, mut native) = (false, false, 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 @@ -450,6 +462,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
sized |= map.layers.iter().any(|layer| layer.size_by.is_some());
pictures |= map.layers.iter().any(Layer::has_picture_markers);
zarr |= map.layers.iter().any(zarr_window);
native |= map.layers.iter().any(|layer| held_natively(&layer.dataset));
legends |= map.tiles.iter().any(|tile| {
tile.legends.iter().any(|legend| rustgis_data::login_address::inner(&legend.url).len() > rustgis_map::tiles::MAX_LEGEND_URL)
});
Expand All @@ -468,6 +481,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
(zarr, "zarr-window"),
(offline_area_id, "offline-map-area-id"),
(paper, "blank-paper"),
(native, super::NATIVE_COORDINATES),
]
.into_iter()
.filter_map(|(used, name)| used.then_some(name))
Expand Down
Loading
Loading