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
5 changes: 3 additions & 2 deletions crates/analysis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,8 +460,9 @@ pub fn resolve_params(spec: &ToolSpec, params: &Value) -> Result<Value, String>
/// The keys of `params` that `spec` doesn't read, for an error that a required parameter is
/// missing (#2307): a misspelled key is the likely reason, and a failed run's warnings are taken
/// back, so the error says it: " (given 'clips', which Clip doesn't read)". Empty when there are
/// none. Bounded as [`quoted_keys`] bounds them.
fn unread(spec: &ToolSpec, params: &Value) -> String {
/// none. Bounded as [`quoted_keys`] bounds them. A caller adding it to an error the tool gave
/// checks for this exact text, so it isn't said twice.
pub fn unread(spec: &ToolSpec, params: &Value) -> String {
let Some(given) = params.as_object() else { return String::new() };
let unknown: Vec<&str> = given.keys().map(String::as_str).filter(|k| !is_expected_key(spec, params, k)).collect();
if unknown.is_empty() {
Expand Down
8 changes: 0 additions & 8 deletions crates/data/src/source/fgb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,14 +143,6 @@ impl FgbSource {
Self::new(f, Input::Path(path.to_path_buf(), None), name)
}

/// Opens a private conversion, keeping its files alive for every shared reader.
#[cfg(not(target_arch = "wasm32"))]
pub fn open_owned_path(path: &Path, name: &str, workspace: Arc<super::gdal::ReloadWorkspace>) -> Result<Self> {
let mut source = Self::open_path(path, name)?;
source._workspace = Some(workspace);
Ok(source)
}

pub fn open_bytes(bytes: Vec<u8>, name: &str) -> Result<Self> {
Self::open_shared(super::Shared(Arc::new(bytes)), name)
}
Expand Down
6 changes: 0 additions & 6 deletions crates/data/src/source/parquet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,6 @@ impl ParquetSource {
Ok(source)
}

/// Opens a private conversion, keeping its files alive for every shared reader.
#[cfg(not(target_arch = "wasm32"))]
pub fn open_owned_path(path: &Path, name: &str, workspace: Arc<super::duckdb::ReloadWorkspace>) -> Result<Self> {
Self::open_converted_path(path, name, None, Some(workspace))
}

pub fn open_bytes(bytes: Vec<u8>, name: &str) -> Result<Self> {
Self::open_shared(super::Shared(Arc::new(bytes)), name)
}
Expand Down
75 changes: 72 additions & 3 deletions crates/data/src/topojson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,31 @@ fn position(p: &Json) -> Option<Pos> {
Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, extra])
}

/// Whether a position's third member is there but is neither a number nor null (`"10"`, `true`):
/// the position is read without a height, which [`read`] counts. Null is no height, written on
/// purpose (before a measure, `[x, y, null, m]`).
fn height_unread(p: &Json) -> bool {
p.as_array().and_then(|a| a.get(2)).is_some_and(|z| !z.is_number() && !z.is_null())
}

/// The positions of a geometry's points (Point, MultiPoint, and those of a GeometryCollection's
/// members, at most four collections deep) whose height [`height_unread`].
fn point_heights_unread(g: &Json, depth: usize) -> usize {
let coords = g.get("coordinates");
let own = match g.get("type").and_then(Json::as_str) {
Some("Point") => coords.map_or(0, |c| usize::from(height_unread(c))),
Some("MultiPoint") => coords.and_then(Json::as_array).map_or(0, |a| a.iter().filter(|p| height_unread(p)).count()),
_ => 0,
};
let collection = g.get("type").and_then(Json::as_str) == Some("GeometryCollection");
let nested = if collection && depth < 4 {
g.get("geometries").and_then(Json::as_array).into_iter().flatten().map(|m| point_heights_unread(m, depth + 1)).sum()
Comment thread
giswqs marked this conversation as resolved.
Resolved
} else {
0
};
own.saturating_add(nested)
}

/// "1 geometry" or "2 geometries": `n` and the word for one or for several.
fn counted(n: usize, one: &str, several: &str) -> String {
if n == 1 { format!("1 {one}") } else { format!("{n} {several}") }
Expand Down Expand Up @@ -103,6 +128,9 @@ struct Topology {
arcs: Vec<Option<Vec<Pos>>>,
/// By arc, the positions inside a plain arc that couldn't be read and were left out of it.
arcs_lost: Vec<usize>,
/// By arc, the positions read without a height their third member gave as something other
/// than a number ([`height_unread`]).
arcs_heights_unread: Vec<usize>,
transform: Option<([f64; 2], [f64; 2])>,
/// Coordinates still allowed to be rebuilt, across all objects. A geometry is checked whole
/// and counted ([`Topology::need`]) before any arc is copied, so only geometries kept use it,
Expand Down Expand Up @@ -331,14 +359,15 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result<Vec<(Dataset,
// and counted; one at its end (a joint), or a quantized one (every later position is a delta
// from it), makes the arc unreadable.
let mut total = 0usize;
let (mut arcs, mut arcs_lost) = (Vec::new(), Vec::new());
let (mut arcs, mut arcs_lost, mut arcs_heights_unread) = (Vec::new(), Vec::new(), Vec::new());
for a in v.get("arcs").and_then(Json::as_array).map(Vec::as_slice).unwrap_or_default() {
// Read ahead, off the UI thread: a large file can be cancelled between arcs and objects.
crate::progress::check()?;
// An arc that isn't an array of positions can't be read either.
let Some(positions) = a.as_array() else {
arcs.push(None);
arcs_lost.push(0);
arcs_heights_unread.push(0);
continue;
};
total += positions.len();
Expand Down Expand Up @@ -371,9 +400,15 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result<Vec<(Dataset,
(Some(p), None) => positions.len() - p.len(),
_ => 0,
});
// Only the positions the arc keeps: one left out is counted as left out, not as read.
arcs_heights_unread.push(if pts.is_some() {
positions.iter().filter(|p| position(p).is_some() && height_unread(p)).count()
} else {
0
});
arcs.push(pts);
}
let mut topo = Topology { arcs, arcs_lost, transform, budget };
let mut topo = Topology { arcs, arcs_lost, arcs_heights_unread, transform, budget };
let objects = v.get("objects").and_then(Json::as_object).ok_or_else(|| DataError::Format(format!("{file_name}: no objects")))?;
let mut out = Vec::new();
for (name, obj) in objects.iter().take(MAX_OBJECTS) {
Expand All @@ -392,7 +427,7 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result<Vec<(Dataset,
};
// Geometries that couldn't be read, those left out at the coordinate limit, and the arcs
// drawn through by those rebuilt.
let (mut bad, mut cut, mut properties_left_out) = (0usize, 0usize, 0usize);
let (mut bad, mut cut, mut properties_left_out, mut point_heights) = (0usize, 0usize, 0usize, 0usize);
let mut used = std::collections::BTreeSet::new();
let features: Vec<Json> = members
.into_iter()
Expand All @@ -404,6 +439,7 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result<Vec<(Dataset,
match topo.geometry(g) {
Ok(geometry) => {
arcs_used(g, 0, &mut used);
point_heights = point_heights.saturating_add(point_heights_unread(g, 0));
geometry
}
Err(Unreadable) => {
Expand Down Expand Up @@ -457,6 +493,13 @@ fn read_with(file_name: &str, text: &str, budget: usize) -> Result<Vec<(Dataset,
counted(lost, "position", "positions")
));
}
let heights = used.iter().filter_map(|i| topo.arcs_heights_unread.get(*i)).fold(point_heights, |n, h| n.saturating_add(*h));
if heights > 0 {
rep.messages.push(format!(
"{} with a third member that isn't a number read without a height",
counted(heights, "position", "positions")
));
}
if no_list {
rep.messages.push(format!("object {name} is a geometry collection without a list of geometries: nothing in it was read"));
}
Expand Down Expand Up @@ -619,6 +662,32 @@ mod tests {
assert_eq!(rep.skipped, 0);
}

/// A third member that isn't a number (text, true) is read without a height, counted in one
/// notice per layer, for points and arcs alike; numeric heights, or none, say nothing.
#[test]
fn a_height_that_isnt_a_number_is_said() {
let said = |text: &str| -> Vec<String> {
let (_, rep) = read("h.topojson", text).unwrap().remove(0);
rep.messages.into_iter().filter(|m| m.contains("read without a height")).collect()
};
let lossy = r#"{"type":"Topology","objects":{"o":{"type":"GeometryCollection","geometries":[
{"type":"Point","coordinates":[1,2,"10"]},{"type":"MultiPoint","coordinates":[[1,2,true],[3,4,5]]},{"type":"LineString","arcs":[0]}]}},
"arcs":[[[0,0,"a"],[1,1,2],[2,2,"b"]]]}"#;
assert_eq!(said(lossy), ["4 positions with a third member that isn't a number read without a height"]);
let clean = r#"{"type":"Topology","objects":{"o":{"type":"GeometryCollection","geometries":[
{"type":"Point","coordinates":[1,2,10]},{"type":"Point","coordinates":[1,2,null]},{"type":"LineString","arcs":[0]}]}},
"arcs":[[[0,0,1],[1,1]]]}"#;
assert!(said(clean).is_empty());
// A position left out of its arc isn't also read without a height; a member of a Point
// (not a collection) isn't read, so isn't counted either.
let left_out = r#"{"type":"Topology","objects":{"o":{"type":"Point","coordinates":[0,0],
"geometries":[{"type":"Point","coordinates":[3,4,"bad"]}]},"p":{"type":"LineString","arcs":[0]}},
"arcs":[[[0,0],[null,1,"bad"],[2,2]]]}"#;
for (_, rep) in read("h.topojson", left_out).unwrap() {
assert!(!rep.messages.iter().any(|m| m.contains("read without a height")), "{:?}", rep.messages);
}
}

#[test]
fn a_plain_position_not_read_is_left_out_of_its_arc_and_said() {
// Plain coordinates aren't deltas: the arc keeps its other positions, and the file says
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,13 @@ url = { workspace = true }
# Generated layers for the never-silent round trip (tests/never_silent_roundtrip.rs).
proptest = { workspace = true }

# Time slider animations as GIFs (exported by the desktop app only).
# Random field-package identities; in the browser through its JavaScript crypto.
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = { version = "0.4", features = ["wasm_js"] }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
getrandom = "0.4"
# Time slider animations as GIFs (exported by the desktop app only).
image = { workspace = true, features = ["gif"] }

# The live PostGIS tests make their own tables, and change rows as someone else would.
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/box_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ pub(crate) fn delete_box(s: &mut Session, p: &Value) -> CmdResult {
return Err("the feature changed during this edit".into());
}
let layer = s.map_mut().layer_mut(id).ok_or("no layer")?;
let before = layer.dataset.features.remove(row);
let before = layer.dataset.features.remove_row(row).ok_or("no such feature")?;
layer.selection = layer.selection.iter().copied().filter(|r| *r != row).map(|r| if r > row { r - 1 } else { r }).collect();
layer.touch_geometry();
crate::cmd::design::apply(s, id, vec![crate::cmd::design::Change { before: Some(before), row: None }])?;
Expand Down
5 changes: 3 additions & 2 deletions crates/engine/src/cmd/deeplearning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,9 @@ fn training(s: &Session, p: &Value) -> Result<Training, String> {
};
let epochs = epochs as usize;
// Without a name given, a new model never replaces one: it gets a name of its own.
let (name, auto) = match ps(p, "model") {
Some(_) => (name(&json!({"name": p.get("model")}), format!("{}_model", r.name))?, None),
// A blank name is none given: it gets a name of its own too.
let (name, auto) = match ps(p, "model").map(str::trim).filter(|m| !m.is_empty()) {

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.

No regression test for the blank-name fix (low confidence, quality). A blank model used to take the auto = None path and overwrite an existing <raster>_model on store. The fix is correct, but the diff adds no test for it. The PR body says bugs get regression tests. A small test would train (or fake a short run) with "model": " " twice and check that the second model is kept under a new name and nothing is replaced. The same goes for the new "Import Task:" cut-name title and the "neither graph nor steps" refusal in model.rs, which also have no tests in the diff.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The fix is a one-line routing change (blank is treated like absent, as other name parameters are). Training a model twice for a test is slow, so that test and the Import Task title and neither-graph-nor-steps tests are left for the release quality pass.

Some(m) => (super::within("model", "a model's name", m, 200)?, None),
None => {
let base = format!("{}_model", r.name);
(free_name(s, &base), Some(base))
Expand Down
7 changes: 1 addition & 6 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1725,12 +1725,7 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult {
super::at_most("subtypes", "a field", list, 1000)?;
for v in list {
let code = v.get("code").and_then(Json::as_i64).ok_or("each subtype has an integer code")?;
let name = super::within(
"a subtype's name",
"a subtype's name",
v.get("name").and_then(Json::as_str).ok_or("each subtype has a name")?,
200,
)?;
let name = super::within("name", "a subtype's name", v.get("name").and_then(Json::as_str).ok_or("each subtype has a name")?, 200)?;
let defaults: Vec<(String, Value)> = v
.get("defaults")
.and_then(Json::as_object)
Expand Down
10 changes: 4 additions & 6 deletions crates/engine/src/cmd/diagram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,9 @@ pub(crate) fn hidden_notice(s: &mut Session, id: u32) {
}
}

/// What [`hidden_notice`] says about `l`, or `None` when its diagram (if any) shows: also given
/// for each such layer a project, map file or layer file opens with.
/// What [`hidden_notice`] says about `l`, or `None` when its diagram (if any) shows. Opening a
/// project, map file or layer file checks only whether this is `Some`, counting such layers by
/// kind in one notice each; this text isn't shown there.
pub(crate) fn hidden_text(l: &rustgis_map::Layer) -> Option<String> {
l.diagram.as_ref()?;
// A name read from a file may be any length.
Expand Down Expand Up @@ -579,10 +580,7 @@ mod tests {
let mark = full.notices.len();
full.run("map.import", &json!({"text": map})).unwrap();
let said: Vec<&str> = full.notices[mark..].iter().map(|n| n.text.as_str()).collect();
assert!(
said.iter().any(|t| t.contains("1 layout(s) beyond the 200 a project holds removed while checking the project")),
"{said:?}"
);
assert!(said.iter().any(|t| t.contains("1 layout(s) beyond the 200 a project holds removed while importing the map")), "{said:?}");
// A map import takes the layers' diagrams, so says what reading them changed.
let mut damaged_map: serde_json::Value = serde_json::from_str(&map).unwrap();
let layer = damaged_map["layers"].as_array_mut().unwrap().iter_mut().find(|l| l["id"] == json!(id)).unwrap();
Expand Down
Loading
Loading