From e7377f88a8632e54daf3a1f9c950b5fe49d0cb6c Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 21 Nov 2026 23:51:43 -0500 Subject: [PATCH 1/7] chore(sweep): render, map and analysis fixes from the release pass Render and layouts: clearer layout.publication/export/addElement wording, one off_dem refusal for block diagrams, counted block notices, no Export Raster on the web tile menu, dead code removed, a vacuous line-label test made to check its case, garbled docs fixed. Map and analysis: DuckDB conversions count the rows whose Z/M values they drop; a terrain block's walls layer is a saved capability (terrain-block-walls-layer, with a fixture); an overflowing network cost closes its line with a count; tile trims aren't counted as cuts; Perpendicular label placement in the Labels pane and the guide; Size by and notice wording; QGIS notes and source options past their caps are counted; closed manual breaks refuse the open-below sentinel; the cancel test checks next_table_id only grows; one diagram read path; docs and comments fixed; Reload Data and Restore Fill get icons of their own. --- crates/analysis/src/network.rs | 32 ++++++- crates/analysis/src/tools.rs | 20 +++-- crates/analysis/src/tools/network_analysis.rs | 20 +++++ crates/data/src/export.rs | 16 +--- crates/data/src/source/duckdb.rs | 59 +++++++++---- crates/engine/src/cmd/block_model.rs | 4 +- crates/engine/src/cmd/items.rs | 2 +- crates/engine/src/cmd/layer.rs | 19 +++- crates/engine/src/cmd/layout.rs | 19 ++-- crates/engine/src/cmd/project.rs | 10 ++- crates/engine/src/cmd/terrain_blocks.rs | 2 +- crates/engine/src/cmd/view.rs | 17 +--- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 22 ++++- crates/engine/src/tests.rs | 64 ++++++++++++-- crates/engine/src/tests/cancellation.rs | 6 +- .../integration/project_save_roundtrip.rs | 6 +- crates/map/src/diagram.rs | 75 ++++++++-------- crates/map/src/effects.rs | 39 ++++----- crates/map/src/geolibre/style.rs | 6 +- crates/map/src/lod.rs | 13 +-- crates/map/src/qgis/mod.rs | 12 +++ crates/map/src/qgis/source.rs | 43 ++++++--- crates/map/src/qgis/tests.rs | 9 +- crates/map/src/source.rs | 5 +- crates/map/src/symbol_by.rs | 12 +-- crates/map/src/symbology.rs | 8 ++ crates/map/src/tiles.rs | 17 +++- crates/render/src/block.rs | 2 +- crates/render/src/layout.rs | 19 ++-- crates/render/src/line_labels.rs | 16 ++-- crates/render/src/terrain.rs | 3 +- crates/ui-egui/src/icons.rs | 21 +++++ crates/ui-egui/src/labelpane.rs | 87 +++++++++++++++++++ crates/ui-egui/src/panes.rs | 4 +- crates/ui-egui/src/ribbon.rs | 9 +- docs/maintaining.md | 1 + docs/user-guide/analysis.md | 12 +-- docs/user-guide/cartography.md | 9 ++ .../terrain_block_walls_layer_v2.rgis | 1 + schema/project.schema.json | 2 + 41 files changed, 552 insertions(+), 192 deletions(-) create mode 100644 schema/fixtures/terrain_block_walls_layer_v2.rgis diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 7a3679cc89..2ccaeda174 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -46,6 +46,25 @@ struct Network { adj: Vec>, segs: Vec, skipped_segments: usize, + /// Lines whose cost times a segment's length is past the largest number: closed, as a + /// search would never take an edge of infinite cost. + overflowing: usize, +} + +/// Whether a segment of a line in `parts` costs no finite number at `weight` a metre. Segments +/// left out for their coordinates don't count. +fn cost_overflows(parts: &[Vec], weight: f64) -> bool { + // No segment is longer than half the Earth's circumference: a weight finite at that length + // is finite on every segment, so the segments are measured only past it. + if (weight * 2.1e7).is_finite() { + return false; + } + parts.iter().flat_map(|part| part.windows(2)).any(|w| match (w.first(), w.get(1)) { + (Some(a), Some(b)) if a.is_finite() && b.is_finite() && a.y.abs() <= 90.0 && b.y.abs() <= 90.0 => { + !(wgs84_distance_m(*a, *b) * weight).is_finite() + } + _ => false, + }) } impl Network { @@ -53,6 +72,7 @@ impl Network { fn build(ds: &Dataset, rows: &[usize], cost_field: Option) -> Result { let route_error = |reason, skipped| route_error(ds, reason, skipped); let mut skipped_segments = 0; + let mut overflowing = 0; let mut ids: HashMap<(i64, i64), usize> = HashMap::new(); let mut nodes: Vec = Vec::new(); let mut adj: Vec> = Vec::new(); @@ -77,6 +97,10 @@ impl Network { Some(Some(_)) => continue, _ => 1.0, }; + if cost_overflows(parts, weight) { + overflowing += 1; + continue; + } for part in parts { for w in part.windows(2) { if pace.stop(4096) { @@ -109,7 +133,7 @@ impl Network { return Err(route_error("no usable network remains".into(), skipped_segments)); } crate::control::finish(); - Ok(Self { nodes, adj, segs, skipped_segments }) + Ok(Self { nodes, adj, segs, skipped_segments, overflowing }) } /// Heap storage retained by the cache, including spare capacity in every adjacency list. @@ -489,6 +513,12 @@ impl Graph { self.0.skipped_segments } + /// Lines left out of the network as their cost times a segment's length is past the largest + /// number. + pub(crate) fn overflowing(&self) -> usize { + self.0.overflowing + } + /// Segment `i`, in the order the lines and their vertices were read; None past the last. pub(crate) fn segment(&self, i: usize) -> Option { let &(a, b, weight, row) = self.0.segs.get(i)?; diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 357c227ea7..c0e82c9169 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1957,9 +1957,9 @@ impl MaskCache { /// coordinates while the masks are unioned, then twice the largest input feature's, a list of /// the masks (or the index's references to them), and the larger of the largest mask and the /// largest size of the masks one feature meets, together (found for each batch first, standing -/// for their union); the threads are as many as half the scratch -/// memory work may take holds of that, and their recent unions of several masks share -/// `cache_bytes` (by default the other half of [`crate::parallel::scratch_budget`]). +/// for their union); as many threads run as fit, at that much work each, in half the scratch +/// budget, and their recent unions of several masks share `cache_bytes` (by default the other +/// half of [`crate::parallel::scratch_budget`]). fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Option) -> Result { let ds = input(inp, p, "input")?; let clip_ds = input(inp, p, "clip")?; @@ -4936,8 +4936,8 @@ fn merge_coincident(mut points: Vec<(Coord, f64)>) -> Result, Ok(kept.into_iter().map(|(c, sum, count)| (c, sum / count as f64)).collect()) } -/// The cell [`merge_coincident`] files a coordinate `v` under: below 2^24, which 4e-9 of the -/// axis, numbered from zero (under 2^53, an i64 exactly); from 2^24 on, the coordinate's own bits, +/// The cell [`merge_coincident`] files a coordinate `v` under: below 2^24, the index of its +/// 4e-9-wide cell, numbered from zero (under 2^53, an i64 exactly); from 2^24 on, the coordinate's own bits, /// whose magnitude (an exponent of 24 or more) is past 2^60, beyond every number below. fn coincident_cell(v: f64) -> i64 { const CELL: f64 = 4e-9; @@ -6620,7 +6620,13 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result = zone.key.iter().map(ToString::to_string).collect(); + let class_key: Vec = class.key.iter().map(ToString::to_string).collect(); + return Err(format!( + "Tabulate Intersection: in zone '{}' and class '{}': {message}", + zone_key.join(", "), + class_key.join(", ") + )); } row.push(Value::Float(ground_area_perimeter(covered).0 / area_divisor)); let covered_area = map_area_m2(covered); @@ -11523,7 +11529,7 @@ mod tests { let far = [16_777_216.0, -16_777_216.0, 1.0e11, -1.0e11, 1.0e300, -1.0e300, f64::MAX, -f64::MAX]; let near = [16_777_215.999_999_998, -16_777_215.999_999_998, 0.0, -0.0]; for f in far { - assert_eq!(coincident_cell(f), coincident_cell(f)); + assert_ne!(coincident_cell(f), coincident_cell(-f), "{f}"); for n in near { assert!(coincident_cell(f).abs_diff(coincident_cell(n)) > 1, "{f} {n}"); } diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index 74e0e166a0..4700845ac8 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -80,6 +80,14 @@ fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result, } } let graph = Graph::of(ds, &rows, cost_field)?; + if graph.overflowing() > 0 { + let field = cost_field.and_then(|fi| ds.fields.get(fi)).map_or("", |f| f.name.as_str()); + notes.push(format!( + "{tool}: {} line(s) of '{}' cost so much in {field} that a segment's cost is past the largest number, and are closed", + graph.overflowing(), + ds.name + )); + } if graph.skipped_segments() > 0 { notes.push(format!( "{tool}: {} segment(s) of '{}' with invalid coordinates were left out of the network", @@ -699,6 +707,18 @@ mod tests { "{:?}", r.messages ); + assert!(!r.messages.iter().any(|m| m.contains("past the largest number")), "{:?}", r.messages); + // A cost so large its segments' costs overflow closes the line too, counted apart. + let mut huge = roads(); + huge.features[3].attrs[0] = Value::Float(1e306); + let inputs = map(vec![huge, points("shops", &[Some(c(0.005, 0.0))])]); + let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "5", "costField": "cost"})).unwrap(); + assert!( + r.messages.iter().any(|m| m + .contains("1 line(s) of 'roads' cost so much in cost that a segment's cost is past the largest number, and are closed")), + "{:?}", + r.messages + ); } /// A point just across ±180° from a line is moved onto it, about 110 m away, not left out as diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index 7798759f72..26470bc055 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -103,18 +103,8 @@ pub fn write_source_in(src: &dyn FeatureSource, layer: &Dataset, path: &Path, cr } /// As [`write_source_in`], a GeoPackage's table placed as `gpkg` says (see -/// [`crate::io::write_path_to`]): also returns the table written. -pub fn write_source_to( - src: &dyn FeatureSource, - layer: &Dataset, - path: &Path, - crs: Crs, - gpkg: &GpkgTable, -) -> Result<(Exported, Option)> { - write_chunks_to(src, layer, path, crs, gpkg, CHUNK_BYTES, None) -} - -/// As [`write_source_to`], applying the layer's query before projecting or serializing each chunk. +/// [`crate::io::write_path_to`]), applying the layer's query before projecting or serializing each +/// chunk: also returns the table written. pub fn write_source_filtered( src: &dyn FeatureSource, layer: &Dataset, @@ -134,7 +124,7 @@ fn write_chunks_in(src: &dyn FeatureSource, layer: &Dataset, path: &Path, crs: C write_chunks_to(src, layer, path, crs, &GpkgTable::default(), bytes, None).map(|(e, _)| e) } -/// [`write_source_to`], `bytes` of features a chunk. +/// [`write_source_filtered`], `bytes` of features a chunk. fn write_chunks_to( src: &dyn FeatureSource, layer: &Dataset, diff --git a/crates/data/src/source/duckdb.rs b/crates/data/src/source/duckdb.rs index 5ad7f20cc9..e361e42821 100644 --- a/crates/data/src/source/duckdb.rs +++ b/crates/data/src/source/duckdb.rs @@ -42,11 +42,14 @@ const KEEP: std::time::Duration = std::time::Duration::from_secs(30 * 24 * 3600) /// The column added to sort rows into geometry families; never in a result. const DIM: &str = "__rustgis_dim"; +/// The column added to count the rows whose geometry had Z or M values, which the conversion +/// drops; never in a result. +const ZM: &str = "__rustgis_zm"; /// What a converted table is written as: raised when that changes (dates as dates in 2, nanosecond -/// timestamps as timestamps in 3), so a table converted before is converted again rather than -/// kept as it was. -const CONVERSION: u32 = 3; +/// timestamps as timestamps in 3, the rows that lost Z or M values counted in 4), so a table +/// converted before is converted again rather than kept as it was. +const CONVERSION: u32 = 4; /// A database named by commands: DuckDB files, PostgreSQL connections (also queryable through /// DuckDB's `postgres` extension), or live-only MySQL, MariaDB and SQL Server connections. @@ -320,6 +323,8 @@ pub struct Part { pub path: PathBuf, pub family: Family, pub count: u64, + /// Its rows whose geometry had Z or M values, written with x and y only. + pub zm_dropped: u64, } /// A result: a part per geometry family it holds. @@ -718,8 +723,9 @@ fn type_crs(ty: &str) -> Option<&str> { } /// The SELECT that turns a result into what is written: the first geometry column in -/// longitude/latitude, other geometry columns as WKT, types the provider doesn't read as text, and -/// each row's geometry family; and the geometry column's name. +/// longitude/latitude, x and y only, other geometry columns as WKT, types the provider doesn't +/// read as text, each row's geometry family and whether its geometry had Z or M values; and the +/// geometry column's name. fn select(columns: &[Column], crs: Option<&str>, from: &str) -> Result<(String, String)> { let geom = columns .iter() @@ -734,7 +740,7 @@ fn select(columns: &[Column], crs: Option<&str>, from: &str) -> Result<(String, (None, Some(_)) => format!("ST_Transform({g}, 'EPSG:4326')"), (None, None) => g.clone(), }; - let list: Vec = columns + let mut list: Vec = columns .iter() .map(|c| { let n = ident(&c.name); @@ -752,6 +758,7 @@ fn select(columns: &[Column], crs: Option<&str>, from: &str) -> Result<(String, } }) .collect(); + list.push(format!("(ST_HasZ({g}::GEOMETRY) OR ST_HasM({g}::GEOMETRY)) AS {ZM}")); Ok((format!("SELECT *, ST_Dimension({g}) AS {DIM} FROM (SELECT {} FROM {from})", list.join(", ")), geom.name.clone())) } @@ -918,8 +925,8 @@ fn run_selected_in(dir: &Path, q: &Query<'_>, confined: bool, selected: Option, confined: bool, selected: Option 0 => { let path = dir.join(format!("{run_tag}.{}.parquet", family.label())); - out.parts.push(Part { path, family, count }); + out.parts.push(Part { path, family, count, zm_dropped }); } Some(_) => {} None => out.skipped = out.skipped.saturating_add(count), @@ -976,7 +989,7 @@ fn run_selected_in(dir: &Path, q: &Query<'_>, confined: bool, selected: Option 0 || out.skipped == 0) { // COPY wrote a valid empty GeoParquet for every family, even when the selected // family disappeared while rows of another family remain. - out.parts.push(Part { path: dir.join(format!("{run_tag}.{}.parquet", family.label())), family, count: 0 }); + out.parts.push(Part { path: dir.join(format!("{run_tag}.{}.parquet", family.label())), family, count: 0, zm_dropped: 0 }); } } if out.parts.is_empty() { @@ -1127,11 +1140,11 @@ fn convert_table_in(dir: &Path, database: &Path, table: &Table, crs: Option<&str // A database is hostile input: its tables are read confined to the cache. let out = run_in(dir, &Query { sql: &table.sql(), database: Some(&Database::File(full.clone())), crs }, true)?; // The key goes last, vouching for the parts written before it: the key, then a line per part - // (its family, rows and file) and the rows left out. + // (its family, rows, file and rows that lost Z or M values) and the rows left out. let mut text = key.clone(); for p in &out.parts { let file = p.path.file_name().and_then(|f| f.to_str()).unwrap_or_default(); - text.push_str(&format!("\npart {} {} {file}", p.family.label(), p.count)); + text.push_str(&format!("\npart {} {} {file} {}", p.family.label(), p.count, p.zm_dropped)); } text.push_str(&format!("\nskipped {}", out.skipped)); std::fs::write(&keyfile, text)?; @@ -1144,17 +1157,17 @@ fn cached(dir: &Path, key: &str, stored: &str) -> Option { let mut out = Output::default(); for line in rest.lines() { let mut w = line.split(' '); - match (w.next(), w.next(), w.next(), w.next()) { + match (w.next(), w.next(), w.next(), w.next(), w.next(), w.next()) { // Only a file of this module's, in the cache folder. - (Some("part"), Some(f), Some(n), Some(file)) if ours(file) && file.ends_with(&format!(".{f}.parquet")) => { + (Some("part"), Some(f), Some(n), Some(file), Some(zm), None) if ours(file) && file.ends_with(&format!(".{f}.parquet")) => { let family = Family::ALL.into_iter().find(|x| x.label() == f)?; let path = dir.join(file); if !path.is_file() { return None; } - out.parts.push(Part { path, family, count: n.parse().ok()? }); + out.parts.push(Part { path, family, count: n.parse().ok()?, zm_dropped: zm.parse().ok()? }); } - (Some("skipped"), Some(n), None, None) => out.skipped = n.parse().ok()?, + (Some("skipped"), Some(n), None, None, None, None) => out.skipped = n.parse().ok()?, _ => return None, } } @@ -1499,6 +1512,7 @@ mod tests { assert!(s.contains("CAST(\"l\" AS VARCHAR)"), "{s}"); assert!(s.contains("CAST(\"s\" AS TIMESTAMP) AS \"s\""), "{s}"); assert!(s.contains(", \"n\",") && s.contains("ST_AsText(\"g2\")"), "{s}"); + assert!(s.contains(&format!("(ST_HasZ(\"geom\"::GEOMETRY) OR ST_HasM(\"geom\"::GEOMETRY)) AS {ZM}")), "{s}"); // A geometry that says its coordinate system is converted; one given is used. let (s, _) = select(&cols(&[("g", "GEOMETRY('EPSG:3857')")]), None, "x").unwrap(); assert!(s.contains("ST_Transform(\"g\", 'EPSG:4326')"), "{s}"); @@ -1583,6 +1597,13 @@ mod tests { let lines = out.parts.iter().find(|p| p.family == Family::Lines).unwrap(); assert_eq!(points.count, 2); assert_eq!(lines.count, 1); + assert_eq!((points.zm_dropped, lines.zm_dropped), (0, 0), "x and y only: nothing dropped"); + // Rows with Z or M values are counted, as their values are dropped (#1505). + let sql = "SELECT ST_GeomFromText('POINT Z (1 2 3)') AS geom UNION ALL SELECT ST_GeomFromText('POINT M (1 2 4)') \ + UNION ALL SELECT ST_Point(5, 6) UNION ALL SELECT ST_GeomFromText('LINESTRING Z (0 0 1, 1 1 2)')"; + let zm = run_in(&cache, &Query { sql, ..Query::default() }, false).unwrap(); + let dropped = |f: Family| zm.parts.iter().find(|p| p.family == f).map(|p| (p.count, p.zm_dropped)); + assert_eq!((dropped(Family::Points), dropped(Family::Lines)), (Some((3, 2)), Some((1, 1)))); let line_source = open(&lines.path); let line_batch = line_source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); assert_eq!(line_batch.features.len(), 1); diff --git a/crates/engine/src/cmd/block_model.rs b/crates/engine/src/cmd/block_model.rs index fccca2b692..3a42c220d1 100644 --- a/crates/engine/src/cmd/block_model.rs +++ b/crates/engine/src/cmd/block_model.rs @@ -172,7 +172,7 @@ struct Model { /// that box, which the model's walls go down from, not of the circle's only. fn as_box(map: &mut rustgis_map::Map) -> Result<(), String> { let ground = Ground::of(map, &map.camera) - .ok_or("the map's terrain shows on a Web Mercator map with its DEM layer, so the block can't be read")?; + .ok_or("the block can't be read: the map's terrain needs a Web Mercator map and its DEM layer loaded")?; let b = ground.block(map).ok_or("the block's box can't be read (over elevation tiles it needs an extent)")?; if let Some(block) = map.view.terrain.as_mut().and_then(|t| t.block.as_mut()) { block.shape = rustgis_map::view::BlockShape::Box; @@ -188,7 +188,7 @@ fn read_ground(map: &rustgis_map::Map, texture: f64) -> Result<(Ground, terrain: loop { let drawn_at = rustgis_render::rustgis_tiles::cache::generation(); let ground = Ground::of(map, &map.camera) - .ok_or("the map's terrain shows on a Web Mercator map with its DEM layer, so the block can't be read")?; + .ok_or("the block can't be read: the map's terrain needs a Web Mercator map and its DEM layer loaded")?; let block = ground.block(map).ok_or("the block's box can't be read (over elevation tiles it needs an extent)")?; let model = build(&ground, &block, texture); let left = TILE_WAIT.saturating_sub(start.elapsed()); diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 189f7b3b27..2a8eea750d 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -100,7 +100,7 @@ pub fn commands() -> Vec { s.notify(format!("New Style: the style takes the first {MAX_STYLE_NAME} characters of the layer's name"), false); } if left_out > 0 { - s.notify(format!("Style {name} from {layer}: {left_out} fill(s) No Fill hid couldn't be put back in it, as their classes have fills of their own now, are gone or their opacity wasn't kept; it draws them as the layer does now"), false); + s.notify(format!("Style {name} from {layer}: {left_out} fill(s) No Fill hid couldn't be put back in it, as their classes have fills of their own now, are gone or their opacity wasn't kept; the style is saved without them"), false); } Ok(json!({"style": name})) }).roles(&[]).effects(crate::policy::Effects::NONE) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3f39ae7c58..082a178684 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -810,6 +810,8 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { // The mapping's own where it is of the same field, else the field's range. let had = l.size_by.as_ref().filter(|h| l.dataset.field_index(&h.field) == Some(fi)); let (min, max) = (min.or(had.map(|h| h.min)), max.or(had.map(|h| h.max))); + // Both bounds read from the field: one with a single value has no range to scale over. + let both_read = min.is_none() && max.is_none(); let range = if min.is_none() || max.is_none() { // A streamed layer holds the view's features only, so their range would be the view's. if l.is_streamed() { @@ -824,6 +826,7 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { } match ahead { Some(a) if a.field == fi && a.dataset.fields == l.dataset.fields && a.dataset.features.shares(&l.dataset.features) => a.range?, + Some(a) if a.field != fi => return Err("the range read was for another field: ask again".into()), Some(_) => return Err("the layer changed while its size range was read: ask again".into()), None => size_range(&l.dataset, fi)?, } @@ -832,6 +835,9 @@ fn size_by(s: &mut Session, p: &Value) -> CmdResult { }; let min = min.or(range.map(|r| r.0)).ok_or_else(|| format!("'{field}' has no numeric values: give min and max"))?; let max = max.or(range.map(|r| r.1)).ok_or_else(|| format!("'{field}' has no numeric values: give min and max"))?; + if max <= min && both_read { + return Err(format!("'{field}' has one value ({min}): give min and max")); + } if max <= min { return Err(format!("max ({max}) must be above min ({min})")); } @@ -3505,6 +3511,7 @@ pub(crate) fn gdal_parts(mut converted: Vec 0 { s.notify(format!("{name}: {} rows without a geometry were left out", out.skipped), false); } + // Z and M values are dropped as DuckDB writes the result: one notice for all its parts. + let zm = out.parts.iter().fold(0u64, |n, p| n.saturating_add(p.zm_dropped)); + if zm > 0 { + s.notify(format!("{name}: {}", rustgis_data::zm_note(Some(zm))), false); + } let mixed = out.parts.len() > 1; out.parts.sort_by_key(|p| bottom_first(p.family)); out.parts @@ -4274,6 +4286,7 @@ pub(crate) fn duckdb_parts( // A geometry that says no coordinate system is usually longitude/latitude: only // coordinates past it are pointed out (in add_converted). unprojected: false, + zm_dropped: part.zm_dropped > 0, origin: ConvertedOrigin::Duckdb(origin(part.family)), }) .collect() @@ -4286,6 +4299,9 @@ pub(crate) struct Converted { name: String, /// Its coordinates are the source's own, in a coordinate system it doesn't say. unprojected: bool, + /// The conversion dropped Z or M values (said as it ran), kept with the layer so an export + /// says so too. + zm_dropped: bool, origin: ConvertedOrigin, } @@ -4345,6 +4361,7 @@ pub(crate) fn add_converted(s: &mut Session, p: &Value, label: &str, original: & for id in r["layers"].as_array().into_iter().flatten().filter_map(Value::as_u64).filter_map(|i| u32::try_from(i).ok()) { if let Some(l) = s.map_mut().layer_mut(id) { l.dataset.source = Some(original.to_string()); + l.dataset.zm_dropped |= c.zm_dropped; if let Some(src) = &mut l.source { match &c.origin { ConvertedOrigin::Gdal(g) => src.gdal = Some(g.clone()), @@ -6938,7 +6955,7 @@ fn square_labels_follow_removal(s: &mut Session, names: &[String]) { if !squared.is_empty() { let (count, names) = (squared.len(), squared.join(", ")); s.notify( - format!("Labels: {count} perpendicular labels' line layer(s) {names} removed, so their labels are placed as auto until a layer of that name comes back"), + format!("Labels: the line layer(s) {names} that perpendicular labels turn to ({count}) were removed; those labels are placed as auto until a layer of that name comes back"), false, ); } diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index de240c9114..8e40e83a65 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -35,7 +35,7 @@ pub fn commands() -> Vec { r#"{"name"?: string, "page"?: "letter"|"legal"|"tabloid"|"a5"|"a4"|"a3"|"a2"|"a1"|"a0", "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "template"?: "map" (frame, title, legend, north arrow, scale bar; the default)|"blank"}"#, ), C::new("layout.publication", "New Publication Layout", "Publish › Layout", publication).inputs(publication_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"profile"?: "a4" (the default) | "letter"|"legal"|"tabloid"|"a5"|"a3"|"a2"|"a1"|"a0" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | a size with its orientation: "a4-portrait"|"a4-landscape"|"letter-portrait"|"tabloid-landscape"|… for each of those sizes (a sheet: frame, title, subtitle, the map, a boxed footer, all scaled to the sheet)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets, but for a map on the globe with no extent, the globe seen whole, which has none and no scale bar either, the globe filling its frame) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster with a colour scale, not drawn by classes, gets one, under the legend in its box; a raster drawn by classes has them in the legend's rows instead) | "none" (no colorbar, and the legend's box has no room for one), "veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "contextInLegend"?: false (the default: layers the placement takes as context around the data, polygons only outlined or, beside a layer drawn by classes or a raster, in one colour and running on past the frame, are left out of the legend, which a warning names) | true (the legend lists them), "northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none", "legendBox"?: "auto" (the default: over the map, the legend has no box where the map shows nothing under it but its light plain paper or water, with no layer, context, basemap shape or graticule line there and no veil; the answer's "legendBox" says whether it has one) | "always", "style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite, each arrangement by name and each saved with layout.arrangement laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name (built in or saved) or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves), "coverage"?: "*.png" (writes the coverage grid the placement searched, as it settled on it, three pixels a cell: what the map draws dark, the free cells white, both tinted blue in the strips the graticule's labels keep, the surrounds placed over the map outlined in red; the answer gives its path)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, + r#"{"profile"?: "a4" (the default) | "letter"|"legal"|"tabloid"|"a5"|"a3"|"a2"|"a1"|"a0" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | a size with its orientation: "a4-portrait"|"a4-landscape"|"letter-portrait"|"tabloid-landscape"|… for each of those sizes (a sheet: frame, title, subtitle, the map, a boxed footer, all scaled to the sheet)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets, but for a map on the globe with no extent, the globe seen whole, which has no locator and no scale bar, the globe filling its frame) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster with a colour scale, not drawn by classes, gets one, under the legend in its box; a raster drawn by classes has them in the legend's rows instead) | "none" (no colorbar, and the legend's box has no room for one), "veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "contextInLegend"?: false (the default: layers the placement takes as context around the data, polygons only outlined or, beside a layer drawn by classes or a raster, in one colour and running on past the frame, are left out of the legend, which a warning names) | true (the legend lists them), "northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none", "legendBox"?: "auto" (the default: over the map, the legend has no box where the map shows nothing under it but its light plain paper or water, with no layer, context, basemap shape or graticule line there and no veil; the answer's "legendBox" says whether it has one) | "always", "style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite, each arrangement by name and each saved with layout.arrangement laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name (built in or saved) or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves), "coverage"?: "*.png" (writes the coverage grid the placement searched, as it settled on it, three pixels a cell: what the map draws dark, the free cells white, both tinted blue in the strips the graticule's labels keep, the surrounds placed over the map outlined in red; the answer gives its path)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, ), C::new("layout.arrangement", "Favourite Arrangement", "Publish › Layout", arrangement).roles(&[]).effects(crate::policy::Effects::NONE).view().params( r#"{"favourite"?: "classic" (the locator top left, the north arrow top right, the legend bottom left, the scale bar bottom right) | "mirrored" | "legendRight" | "legendTop" | {"locator", "northArrow", "legend", "scaleBar": "top-left"|"top-right"|"bottom-left"|"bottom-right", each a corner of its own} | a saved arrangement's name, "save"?: a name (1 to 40 characters, not a built-in one nor "best", "favourite", "custom" or "veil"; one saved under it already, case aside, is replaced) to save "arrangement" under (at most 20 saved), "arrangement"?: what "save" saves: an arrangement by name, or a corner for each surround as "favourite" takes them (refused without "save"), "remove"?: a saved arrangement's name (a favourite named after it keeps its corners, unless "favourite" gives another)} → the favourite arrangement of publication layouts and those saved by name (kept with the app's preferences), the favourite's corners, the arrangements by name and the saved ones' corners; a removal, then a save, then the favourite; with none of them given, they are only shown"#, @@ -2497,8 +2497,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { } } if let Some(at_scale) = unknown_at { + let or_veiled = if may_veil { " or veiled" } else { "" }; warnings.push(format!( - "the map isn't moved or veiled at 1:{at_scale:.0} for the legend's room: a layer there is still reading, a legend picture still loading, or a layer's source can't be read through (exporting says why)" + "the map isn't moved{or_veiled} at 1:{at_scale:.0} for the legend's room: a layer there is still reading, a legend picture still loading, or a layer's source can't be read through (exporting says why)" )); } // A move changes what the frame shows past the extent, so it is said, as the veil and @@ -2725,7 +2726,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { // unveiled map; the map under them stays unveiled, which is said too. if let Some((x, y, w, h)) = veiled { warnings.push( - "what the map draws outside the extent is veiled, for the legend's room, but for the strips under the graticule's labels, and the surrounds sit there: \"veil\": false leaves it unveiled" + "what the map draws outside the extent is veiled to make room for the legend (except the strips under the graticule's labels), and the surrounds are grouped there: \"veil\": false leaves it unveiled" .into(), ); let (x0, y0) = (x.max(area.0), y.max(area.1)); @@ -3499,7 +3500,7 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { // A grid's "labels" is a bool and a legend's an object (read with it); on any other kind, or as // anything else on a grid, it is refused rather than left unread. match p.get("labels").filter(|v| !v.is_null()) { - Some(v) if kind == "grid" && !v.is_boolean() => return Err("a grid's labels is true or false".into()), + Some(v) if kind == "grid" && !v.is_boolean() => return Err("a grid's \"labels\" is true or false".into()), Some(_) if kind != "legend" && kind != "grid" => return Err(ONLY_LEGEND_LABELS.into()), _ => {} } @@ -4738,7 +4739,7 @@ fn legend_labels( let Some(v) = p.get("labels").filter(|v| !v.is_null()) else { return Ok(None) }; let given = v.as_object().ok_or(LABELS_SHAPE)?; if given.len() > MAX_LEGEND_LABELS { - return Err(format!("a legend labels at most {MAX_LEGEND_LABELS} layers")); + return Err(format!("a legend can label at most {MAX_LEGEND_LABELS} layers")); } let map = legend_map(input, l, frame)?; let mut out: Vec<(String, Option)> = Vec::new(); @@ -4774,7 +4775,7 @@ fn with_labels(labels: &BTreeMap, given: Vec<(String, Option MAX_LEGEND_LABELS { - return Err(format!("a legend labels at most {MAX_LEGEND_LABELS} layers")); + return Err(format!("a legend can label at most {MAX_LEGEND_LABELS} layers")); } Ok(out) } @@ -5477,7 +5478,7 @@ fn scale_box_basis(s: &Session, li: usize) -> Option { /// or in another font, naming a map series page (which differs from page to page), or of a frame /// other than the first (whose map the page fills the text from) is left as it is; so is a text /// longer than the widest box a publication gives. Only a box as wide as `before` (what it was -/// measured from before the change: its frame, bar and text) makes it is measured again: one set +/// measured from before the change: its frame, bar and text) is measured again: one set /// by hand keeps its width. A change to the text under the bar or to the bar's units or divisions /// measures it again too. A box that would then cover the legend, locator or north arrow, which /// it didn't, stays as it was, which is said. @@ -5952,8 +5953,10 @@ pub(crate) fn georeference_notices( let n = corners.len(); s.notify( format!( - "The PDF georeferences {n} map frame{} by its corners in longitude/latitude, as its coordinate system can't be written as WKT: on a 9 × 9 grid over each, it puts places within 0.5 mm of where they are drawn, not proven between them ({})", + "The PDF georeferences {n} map frame{} by {} corners in longitude/latitude, as {} can't be written as WKT: on a 9 × 9 grid over each, it puts places within 0.5 mm of where they are drawn, not proven between them ({})", plural(n), + if n == 1 { "its" } else { "their" }, + if n == 1 { "its coordinate system" } else { "their coordinate systems" }, listed(corners) ), false, diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 949d9efdf2..70f0001f56 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -292,7 +292,7 @@ pub(super) fn off_dem(extent: Option<[f64; 4]>, dem: Option<&(String, Option<[f6 let d = (*footprint)?; (e[2] <= d[0] || e[0] >= d[2] || e[3] <= d[1] || e[1] >= d[3]).then(|| { format!( - "block's extent doesn't overlap '{n}' (its corners are [{:.0}, {:.0}, {:.0}, {:.0}] in Web Mercator metres)", + "the block's box doesn't overlap '{n}', whose footprint spans [{:.0}, {:.0}, {:.0}, {:.0}] in Web Mercator metres", d[0], d[1], d[2], d[3] ) }) @@ -441,7 +441,9 @@ fn reset(s: &mut Session, p: Project) { if !uncut.is_empty() { s.notify( format!( - "{}: the layer a block diagram is cut to is missing, isn't a polygon layer, is read a view at a time, shares its name with another layer or picks no polygon with an area, so no block is drawn", + "{} block diagram{} cut to a layer that is missing, isn't a polygon layer, holds its features only a view at a time, shares its name with another layer or picks no polygon with an area, so no block is drawn: {}", + uncut.len(), + if uncut.len() == 1 { "" } else { "s" }, uncut.join(", ") ), false, @@ -451,12 +453,12 @@ fn reset(s: &mut Session, p: Project) { match plain.as_slice() { [] => {} [one] => s.notify( - format!("{one}: the block diagram's walls layer is missing, not a polygon layer, read a view at a time or of a name another layer shares, so its walls are one colour"), + format!("{one}: the block diagram's walls layer is missing, isn't a polygon layer, holds its features only a view at a time, or shares its name with another layer, so its walls are one colour"), false, ), _ => s.notify( format!( - "{} block diagrams have a walls layer missing, not a polygon layer, read a view at a time or of a name another layer shares, so their walls are one colour: {}", + "{} block diagrams have a walls layer that is missing, isn't a polygon layer, holds its features only a view at a time, or shares its name with another layer, so their walls are one colour: {}", plain.len(), plain.join(", ") ), diff --git a/crates/engine/src/cmd/terrain_blocks.rs b/crates/engine/src/cmd/terrain_blocks.rs index aafea65452..52dd850b4e 100644 --- a/crates/engine/src/cmd/terrain_blocks.rs +++ b/crates/engine/src/cmd/terrain_blocks.rs @@ -229,7 +229,7 @@ fn landed_impl(session: &mut Session, restoring: bool) { if !uncut.is_empty() { session.notify( format!( - "Terrain: the polygons a block diagram is cut to can't be read (none with an area) on {}: no block is drawn until they can", + "Terrain: the polygons a block diagram is cut to can't be read on {}: no block is drawn until they can", uncut.join(", ") ), false, diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index d16c36997e..bd8be5e09a 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -656,19 +656,10 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { } _ => None, }; - let refused = match (&dem_box, own) { - // A DEM whose corners give no box (one off the map's world, say) would draw no block. - (Some((n, None, _)), None) => Some(format!( - "no box fits inside '{n}'s extent on the map: give the block an extent [xmin, ymin, xmax, ymax]{kept} (Terrain stays as it was)" - )), - // A box off the DEM would draw nothing. A box inside its footprint but off its inner box - // still draws the ground it reaches (a DEM turned by its projection has corners beyond it). - (Some((n, _, Some(d))), Some(e)) if e[2] <= d[0] || e[0] >= d[2] || e[3] <= d[1] || e[1] >= d[3] => Some(format!( - "block's extent doesn't overlap '{n}' (its corners are [{:.0}, {:.0}, {:.0}, {:.0}] in Web Mercator metres{kept}; Terrain stays as it was)", - d[0], d[1], d[2], d[3] - )), - _ => None, - }; + // A DEM whose corners give no box (one off the map's world, say) would draw no block, nor + // would a box off the DEM. A box inside its footprint but off its inner box still draws the + // ground it reaches (a DEM turned by its projection has corners beyond it). + let refused = super::project::off_dem(own, dem_box.as_ref()).map(|e| format!("{e}{kept} (Terrain stays as it was)")); if let Some(e) = refused { if let Some(old) = old_terrain { m.view.terrain = Some(old); diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 058b8e74e5..e7fcb0103c 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -77,6 +77,7 @@ pub const CAPABILITIES: &[&str] = &[ "terrain-water", "terrain-water-shore", "terrain-block-water", + "terrain-block-walls-layer", "shaded-relief-effects", "normalized-legend-urls", "field-origin", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index f2591c9559..68040645a1 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -529,6 +529,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static mut water, mut shore, mut block_water, + mut walls_layer, mut relief, mut light, mut legends, @@ -538,7 +539,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static mut mgrs, mut on_top, mut grid_color, - ) = (false, false, false, false, false, false, false, false, false, false, false, false, false, false); + ) = (false, false, false, false, false, false, false, false, false, false, false, false, false, false, false); let mut polygon = false; let (mut offline_area_id, mut paper, mut native, mut guided) = (false, false, false, false); for map in maps { @@ -563,6 +564,8 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static shore |= t.water.as_ref().is_some_and(|w| w.shore != rustgis_map::view::WATER_SHORE); // The water in a block's walls (#2317), which an older reader would save away. block_water |= t.block.as_ref().is_some_and(|b| b.water.is_some()); + // The layer a block's walls are coloured by (#2173), which an older reader would save away. + walls_layer |= t.block.as_ref().is_some_and(|b| b.walls_layer.is_some()); } relief |= map.layers.iter().any(relief_effects); light |= map.layers.iter().any(relief_light); @@ -581,6 +584,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (water, "terrain-water"), (shore, "terrain-water-shore"), (block_water, "terrain-block-water"), + (walls_layer, "terrain-block-walls-layer"), (relief, "shaded-relief-effects"), (light, "shaded-relief-light"), (legends, "normalized-legend-urls"), @@ -698,6 +702,22 @@ mod tests { assert!(serde_json::to_value(&plain).unwrap().get("requires").is_none()); } + /// A block diagram's walls layer reads back as it was and saving names it in `requires`; a + /// block without one doesn't (#2173). + #[test] + fn terrain_block_walls_layer_fixture_requires_it() { + let fixture = Project::from_json(include_str!("../../../schema/fixtures/terrain_block_walls_layer_v2.rgis")).unwrap(); + let block = fixture.maps[0].view.terrain.as_ref().and_then(|t| t.block.as_ref()); + assert_eq!(block.and_then(|b| b.walls_layer.as_deref()), Some("geologia")); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["terrain-block", "terrain-block-walls-layer"])); + let mut plain = fixture; + if let Some(b) = plain.maps[0].view.terrain.as_mut().and_then(|t| t.block.as_mut()) { + b.walls_layer = None; + } + assert_eq!(serde_json::to_value(&plain).unwrap()["requires"], json!(["terrain-block"])); + } + /// A saved image marker reads back as the image it was, and saving names it again. #[test] fn picture_markers_fixture_reads_its_image() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f4a026cc68..f741231074 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5008,7 +5008,7 @@ fn removing_a_perpendicular_label_line_says_so() { s.run("layer.remove", &json!({"layer": "Rivers"})).unwrap(); let notes = said(&s, mark); assert_eq!(notes.len(), 1, "{notes:?}"); - assert!(notes[0].contains("1 perpendicular labels' line layer(s) 'Rivers' removed"), "{notes:?}"); + assert!(notes[0].contains("the line layer(s) 'Rivers' that perpendicular labels turn to (1) were removed"), "{notes:?}"); let c = s.map().layer_by_name("Cities").unwrap().labels.default.clone(); assert_eq!((c.placement, c.square_to.unwrap().layer.as_str()), (crate::map::LabelPlacement::Perpendicular, "Rivers")); } @@ -21104,6 +21104,59 @@ fn duckdb_queries_and_databases() { let _ = std::fs::remove_dir_all(dir); } +/// Size by a field with one value, its bounds read from the field, names the field and its value, +/// not bounds the caller never gave (#2130). +#[test] +fn size_by_a_field_of_one_value_says_so() { + use base64::Engine; + let mut s = Session::new(Project::default()); + let fc = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"v": 5, "k": "a"}, "geometry": {"type": "Point", "coordinates": [0, 0]}}, + {"type": "Feature", "properties": {"v": 5, "k": "b"}, "geometry": {"type": "Point", "coordinates": [1, 1]}}, + ]}); + let data = base64::engine::general_purpose::STANDARD.encode(fc.to_string().as_bytes()); + s.run("layer.addDataBytes", &json!({"fileName": "same.geojson", "data": data})).unwrap(); + s.run("layer.symbology", &json!({"layer": "same", "type": "unique", "field": "k"})).unwrap(); + let err = s.run("layer.sizeBy", &json!({"layer": "same", "field": "v"})).unwrap_err(); + assert_eq!(err, "'v' has one value (5): give min and max"); + let err = s.run("layer.sizeBy", &json!({"layer": "same", "field": "v", "min": 5, "max": 5})).unwrap_err(); + assert!(err.contains("max (5) must be above min (5)"), "{err}"); + assert!(s.run("layer.sizeBy", &json!({"layer": "same", "field": "v", "min": 0, "max": 10})).is_ok()); +} + +/// A DuckDB result whose rows had Z or M values, which its conversion drops, says how many, once, +/// and its layer keeps the loss for an export to say; one with x and y only says nothing (#1505). +/// DuckDB isn't needed: the part is a GeoParquet file as DuckDB writes one. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_duckdb_result_says_the_z_and_m_values_it_dropped() { + use crate::cmd::layer::{add_converted, duckdb_parts}; + use rustgis_data::source::{Family, duckdb}; + let dir = std::env::temp_dir().join(format!("rustgis-duckdb-zm-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let json = r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [10, 50]}}]}"#; + let (ds, _) = rustgis_data::io::read_bytes("part.geojson", json.as_bytes()).unwrap(); + let origin = + |family| rustgis_map::source::DuckdbOrigin { sql: Some("SELECT 1".into()), database: None, table: None, crs: None, family }; + for (zm, said) in [(2u64, true), (0, false)] { + let path = dir.join(format!("zm-{zm}.parquet")); + rustgis_data::io::write_path(&ds, &path).unwrap(); + let mut s = Session::new(Project::default()); + let parts = vec![duckdb::Part { path, family: Family::Points, count: 1, zm_dropped: zm }]; + let parts = duckdb_parts(&mut s, "Trip", duckdb::Output { parts, ..Default::default() }, origin); + add_converted(&mut s, &json!({}), "the query", "DuckDB query", parts).unwrap(); + let notes: Vec<_> = s.notices.iter().filter(|n| n.text.contains("Z or M")).collect(); + if said { + assert_eq!(notes.len(), 1, "{notes:?}"); + assert_eq!(notes[0].text, format!("Trip: {}", rustgis_data::zm_note(Some(2)))); + } else { + assert!(notes.is_empty(), "{notes:?}"); + } + assert_eq!(s.map().layers.first().map(|l| l.dataset.zm_dropped), Some(said)); + } + let _ = std::fs::remove_dir_all(dir); +} + /// A source split by geometry type is added polygons first, so its points end on top and none hides /// under its own polygons, whether DuckDB or GDAL split it (#1488). Neither program is needed: the /// parts use each program's conversion format: GeoParquet for DuckDB, FlatGeobuf for GDAL. @@ -21132,7 +21185,8 @@ fn split_sources_keep_their_points_on_top() { // A DuckDB query. let mut s = Session::new(Project::default()); - let parts = Family::ALL.iter().map(|f| duckdb::Part { path: write("query", *f, "parquet"), family: *f, count: 1 }).collect(); + let parts = + Family::ALL.iter().map(|f| duckdb::Part { path: write("query", *f, "parquet"), family: *f, count: 1, zm_dropped: 0 }).collect(); let origin = |family| rustgis_map::source::DuckdbOrigin { sql: Some("SELECT 1".into()), database: None, table: None, crs: None, family }; let parts = duckdb_parts(&mut s, "Trip", duckdb::Output { parts, skipped: 0, other_family: 0 }, origin); @@ -21165,7 +21219,7 @@ fn split_sources_keep_their_points_on_top() { assert!(!s.notices.iter().any(|n| n.text.contains("converted layer parts keep their generated names")), "no ignored name was supplied"); let mut single = Session::new(Project::default()); let output = duckdb::Output { - parts: vec![duckdb::Part { path: write("single", Family::Points, "parquet"), family: Family::Points, count: 1 }], + parts: vec![duckdb::Part { path: write("single", Family::Points, "parquet"), family: Family::Points, count: 1, zm_dropped: 0 }], skipped: 0, other_family: 0, }; @@ -42266,7 +42320,7 @@ fn legends_label_layers() { assert!(s.run("layout.addElement", &json!({"kind": "scaleBar", "labels": v})).unwrap_err().contains("only legends"), "{v}"); } let err = s.run("layout.addElement", &json!({"kind": "grid", "labels": "no"})).unwrap_err(); - assert!(err.contains("a grid's labels is true or false"), "{err}"); + assert!(err.contains("a grid's \"labels\" is true or false"), "{err}"); assert_eq!(s.project.layouts[0].elements.len(), count); // A grid's own "labels" (a bool) is still its. let frame = s.run("layout.addElement", &json!({"kind": "grid", "labels": false})).unwrap()["element"].as_u64().unwrap() as u32; @@ -45519,7 +45573,7 @@ fn session_log_duckdb_inputs_exclude_conversion_cache() { let added = s .command_epilogue("layer.addSql", ¶ms, |s| { let out = duckdb::Output { - parts: vec![duckdb::Part { path: cache.clone(), family: Family::Points, count: 1 }], + parts: vec![duckdb::Part { path: cache.clone(), family: Family::Points, count: 1, zm_dropped: 0 }], skipped: 0, other_family: 0, }; diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 29bb9b3ef6..edadf6e3b9 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -535,8 +535,12 @@ fn exercise(fixture: &Session, command: &str, p: &Value, kind: Kind, dir: &std:: } assert!(s.undo(), "{what}: lost Undo"); if added_step { - // Table ids are never reused: undo keeps the counter (see the standalone-table removal regression). + // Table ids are never reused: undo keeps the counter, which only grows + // (`table_remove_takes_a_standalone_table_out_of_the_project` in tests.rs). Checked so, + // then set back, so only the counter is excused. let mut undone = contents(&s.project); + let id = |v: &Value| v["project"]["next_table_id"].as_u64(); + assert!(id(&undone) >= id(&before), "{what}: undo lowered next_table_id"); undone["project"]["next_table_id"] = before["project"]["next_table_id"].clone(); assert!(undone == before, "{what}: undo didn't restore the map"); assert!(!s.dirty(), "{what}: undo didn't return to the saved state"); diff --git a/crates/engine/tests/integration/project_save_roundtrip.rs b/crates/engine/tests/integration/project_save_roundtrip.rs index 0772c51742..e4b7f3e838 100644 --- a/crates/engine/tests/integration/project_save_roundtrip.rs +++ b/crates/engine/tests/integration/project_save_roundtrip.rs @@ -1,8 +1,8 @@ //! Saving a project and opening it again gives back the same project, as a property: a project //! built with commands from a few small layers (Project › Save As, then Project › Open) opens with -//! the same layers, symbology, labels, groups, layouts, bookmarks, time and map settings, or the -//! save or open says what changed. What a project file doesn't keep is listed in [`LIMITS`], with -//! the reason. Projects lean on edges: unicode, long and blank names, every renderer kind, nested +//! the same layers, symbology, labels, groups, layouts, bookmarks, time and map settings, but for +//! what a project file doesn't keep, listed in [`LIMITS`] with the reason: any other change fails, +//! even one the save or open says. Projects lean on edges: unicode, long and blank names, every renderer kind, nested //! groups, an empty layer, and values that aren't finite numbers, as a reader may leave them. //! //! A second property: a saved file with fields this version doesn't know opens as it would diff --git a/crates/map/src/diagram.rs b/crates/map/src/diagram.rs index 3359b72fb5..3262f5dc37 100644 --- a/crates/map/src/diagram.rs +++ b/crates/map/src/diagram.rs @@ -300,19 +300,48 @@ impl DiagramLabel { /// not a diagram, as an empty one draws nothing. [`DiagramAudit`] counts what this changes, for /// the project reader's notices. pub fn de_diagram<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + read_diagram(d).map(|(kept, _)| kept) +} + +/// A saved diagram as [`de_diagram`] keeps it, and what reading it so changed: the one place +/// both read it, so the notices can't drift from what is read. A missing or null diagram is none +/// and changes nothing. +fn read_diagram<'de, D: serde::Deserializer<'de>>(d: D) -> Result<(Option, DiagramAudit), D::Error> { #[derive(Deserialize)] #[serde(untagged)] enum Read { Settings(DiagramSettings), Other(serde::de::IgnoredAny), } - Ok(match Option::::deserialize(d)? { - Some(Read::Settings(s)) => { - let s = s.clamped(); - (!s.categories.is_empty()).then_some(s) + let dropped = DiagramAudit { dropped: 1, ..DiagramAudit::default() }; + let s = match Option::::deserialize(d)? { + None => return Ok((None, DiagramAudit::default())), + Some(Read::Other(_)) => return Ok((None, dropped)), + Some(Read::Settings(s)) => s, + }; + let kept = s.clone().clamped(); + if kept.categories.is_empty() { + return Ok((None, dropped)); + } + let mut seen: Vec<&str> = Vec::with_capacity(kept.categories.len()); + let mut repeated_fields = 0usize; + for c in &kept.categories { + if seen.iter().any(|f| f.eq_ignore_ascii_case(&c.field)) { + repeated_fields = repeated_fields.saturating_add(1); + } else { + seen.push(&c.field); } - _ => None, - }) + } + // Any finite angle names the same direction after a whole number of turns: not counted. + let angle_adjusted = !s.start_angle.is_finite(); + let adjusted = kept.size != s.size || angle_adjusted || kept.stroke_width != s.stroke_width; + let audit = DiagramAudit { + dropped: 0, + categories_removed: s.categories.len().saturating_sub(kept.categories.len()), + repeated_fields, + adjusted: usize::from(adjusted), + }; + Ok((Some(kept), audit)) } /// What reading a layer's saved diagram through [`de_diagram`] changed, counted without keeping @@ -348,39 +377,7 @@ impl<'de> Deserialize<'de> for DiagramAudit { /// Reads a saved diagram as [`de_diagram`] does and counts what that changes; a missing or /// null diagram changes nothing. fn deserialize>(d: D) -> Result { - #[derive(Deserialize)] - #[serde(untagged)] - enum Read { - Settings(DiagramSettings), - Other(serde::de::IgnoredAny), - } - let s = match Option::::deserialize(d)? { - None => return Ok(DiagramAudit::default()), - Some(Read::Other(_)) => return Ok(DiagramAudit { dropped: 1, ..DiagramAudit::default() }), - Some(Read::Settings(s)) => s, - }; - let kept = s.clone().clamped(); - if kept.categories.is_empty() { - return Ok(DiagramAudit { dropped: 1, ..DiagramAudit::default() }); - } - let mut seen: Vec<&str> = Vec::with_capacity(kept.categories.len()); - let mut repeated_fields = 0usize; - for c in &kept.categories { - if seen.iter().any(|f| f.eq_ignore_ascii_case(&c.field)) { - repeated_fields = repeated_fields.saturating_add(1); - } else { - seen.push(&c.field); - } - } - // Any finite angle names the same direction after a whole number of turns: not counted. - let angle_adjusted = !s.start_angle.is_finite(); - let adjusted = kept.size != s.size || angle_adjusted || kept.stroke_width != s.stroke_width; - Ok(DiagramAudit { - dropped: 0, - categories_removed: s.categories.len().saturating_sub(kept.categories.len()), - repeated_fields, - adjusted: usize::from(adjusted), - }) + read_diagram(d).map(|(_, audit)| audit) } } diff --git a/crates/map/src/effects.rs b/crates/map/src/effects.rs index ad2b0fb186..51038aad90 100644 --- a/crates/map/src/effects.rs +++ b/crates/map/src/effects.rs @@ -128,24 +128,16 @@ impl Extrusion { } } - /// How high (metres) feature `row` of `ds` is extruded: its height field, else `height`, times `factor`. - pub fn metres(&self, ds: &rustgis_data::Dataset, row: usize) -> f64 { - self.metres_at(ds, row, self.columns(ds)) - } - - /// `metres` with the columns found already. + /// How high (metres) feature `row` of `ds` is extruded, with its columns `c` found already: + /// its height field, else `height`, times `factor`. pub fn metres_at(&self, ds: &rustgis_data::Dataset, row: usize, c: ExtrusionColumns) -> f64 { c.height.and_then(|i| ds.value(row, i).as_f64()).filter(|v| v.is_finite()).unwrap_or(self.height) * self.factor } /// How high (metres) the walls of feature `row` of `ds` start: its base field, else `base` /// when the value is no number (empty, or text that isn't one), like the height; times - /// `factor`. The result is 0 when it is no finite number or negative. - pub fn base_metres(&self, ds: &rustgis_data::Dataset, row: usize) -> f64 { - self.base_metres_at(ds, row, self.columns(ds)) - } - - /// `base_metres` with the columns found already. + /// `factor`, with its columns `c` found already. The result is 0 when it is no finite number + /// or negative. pub fn base_metres_at(&self, ds: &rustgis_data::Dataset, row: usize, c: ExtrusionColumns) -> f64 { let b = c.base.and_then(|i| ds.value(row, i).as_f64()).filter(|v| v.is_finite()).unwrap_or(self.base) * self.factor; if b.is_finite() && b > 0.0 { b } else { 0.0 } @@ -177,14 +169,21 @@ mod extrusion_tests { fn a_base_comes_from_its_field_else_the_constant_times_the_factor() { let ds = rows(vec![Value::Float(10.0), Value::Null, Value::Text("4".into())]); let x = Extrusion { base_field: Some("b".into()), base: 3.0, factor: 2.0, ..Extrusion::default() }; - assert_eq!(x.base_metres(&ds, 0), 20.0, "from the field, with the factor"); - assert_eq!(x.base_metres(&ds, 1), 6.0, "no value: the constant, with the factor"); - assert_eq!(x.base_metres(&ds, 2), 8.0, "a number in text"); + assert_eq!(x.base_metres_at(&ds, 0, x.columns(&ds)), 20.0, "from the field, with the factor"); + assert_eq!(x.base_metres_at(&ds, 1, x.columns(&ds)), 6.0, "no value: the constant, with the factor"); + assert_eq!(x.base_metres_at(&ds, 2, x.columns(&ds)), 8.0, "a number in text"); let constant = Extrusion { base: 5.0, ..Extrusion::default() }; - assert_eq!(constant.base_metres(&ds, 0), 5.0, "no field: the constant"); + assert_eq!(constant.base_metres_at(&ds, 0, constant.columns(&ds)), 5.0, "no field: the constant"); let unknown = Extrusion { base_field: Some("nope".into()), base: 5.0, ..Extrusion::default() }; - assert_eq!(unknown.base_metres(&ds, 0), 5.0, "a field the layer lacks: the constant"); - assert_eq!(Extrusion::default().base_metres(&ds, 0), 0.0, "no base: the ground"); + assert_eq!(unknown.base_metres_at(&ds, 0, unknown.columns(&ds)), 5.0, "a field the layer lacks: the constant"); + assert_eq!( + { + let none = Extrusion::default(); + none.base_metres_at(&ds, 0, none.columns(&ds)) + }, + 0.0, + "no base: the ground" + ); } #[test] @@ -192,11 +191,11 @@ mod extrusion_tests { let ds = rows(vec![Value::Text("tall".into()), Value::Float(f64::NAN), Value::Null, Value::Float(-4.0)]); let x = Extrusion { base_field: Some("b".into()), ..Extrusion::default() }; for row in 0..4 { - assert_eq!(x.base_metres(&ds, row), 0.0, "row {row}"); + assert_eq!(x.base_metres_at(&ds, row, x.columns(&ds)), 0.0, "row {row}"); } for (base, factor) in [(-1.0, 1.0), (f64::NAN, 1.0), (f64::INFINITY, 1.0), (5.0, -1.0), (5.0, f64::NAN)] { let x = Extrusion { base, factor, ..Extrusion::default() }; - assert_eq!(x.base_metres(&ds, 0), 0.0, "base {base}, factor {factor}"); + assert_eq!(x.base_metres_at(&ds, 0, x.columns(&ds)), 0.0, "base {base}, factor {factor}"); } } diff --git a/crates/map/src/geolibre/style.rs b/crates/map/src/geolibre/style.rs index 0a6d3a4a42..d4e05686c0 100644 --- a/crates/map/src/geolibre/style.rs +++ b/crates/map/src/geolibre/style.rs @@ -119,7 +119,11 @@ pub fn apply(layer: &mut Layer, record: &Value, report: &mut Report) { if layer.dataset.field_index(field).and_then(|fi| layer.dataset.fields.get(fi)).is_some_and(|f| f.ty.is_numeric()) { layer.renderer = Renderer::Proportional { field: field.into(), base: symbol, min, max, min_size, max_size }; sized = true; - report.approximated(&name, "proportional sizes use area scaling instead of MapLibre linear radius scaling"); + if max <= min { + report.approximated(&name, "proportional size range is empty (its largest value isn't above its smallest); every point is drawn at the middle size"); + } else { + report.approximated(&name, "proportional sizes use area scaling instead of MapLibre linear radius scaling"); + } } else { report.approximated(&name, format!("size field {field} is absent or not numeric; using a fixed size")); } diff --git a/crates/map/src/lod.rs b/crates/map/src/lod.rs index ec9fc1bca9..6ed46da2bf 100644 --- a/crates/map/src/lod.rs +++ b/crates/map/src/lod.rs @@ -407,8 +407,9 @@ fn keep_mask(run: &[Coord], tol: f64, extremes: bool) -> Vec { /// Marks the vertices of `run[first..=last]` (all finite) Douglas–Peucker keeps at `tol`. It works /// from a stack, not by recursion, so a long run can't overflow the thread's stack, and its work is /// bounded: Douglas–Peucker is quadratic on a shape that splits unevenly at every step (a zigzag), -/// so past [`DP_WORK`] distances a vertex the spans still open are thinned by distance instead -/// (a vertex every `tol` along them), which keeps every dropped vertex within `tol` too. +/// so once it has worked out [`DP_WORK`] distances for each vertex of the run (on average), the +/// spans still open are thinned by distance instead (a vertex every `tol` along them), which +/// keeps every dropped vertex within `tol` too. fn douglas_peucker(run: &[Coord], first: usize, last: usize, tol: f64, keep: &mut [bool]) { for i in [first, last] { if let Some(k) = keep.get_mut(i) { @@ -423,7 +424,8 @@ fn douglas_peucker(run: &[Coord], first: usize, last: usize, tol: f64, keep: &mu } let (Some(&pa), Some(&pb)) = (run.get(a), run.get(b)) else { continue }; if budget < b - a { - // Out of work: keep a vertex each `tol` (|dx| + |dy|) from the last kept, as `thin` does. + // Out of work: keep a vertex each `tol` (|dx| + |dy|) from the last kept, the distance + // rule thinning used before #1750. let mut kept = pa; for i in a + 1..b { let Some(&c) = run.get(i) else { break }; @@ -454,8 +456,9 @@ fn douglas_peucker(run: &[Coord], first: usize, last: usize, tol: f64, keep: &mu } } -/// How many distances a vertex Douglas–Peucker may work out, on average, before it thins the rest of -/// a run by distance: an even split takes about log2 of the run's length (under 32). +/// How many distances Douglas–Peucker may work out for each vertex of a run, on average, before it +/// thins the rest of the run by distance: an even split takes about log2 of the run's length +/// (under 32). const DP_WORK: usize = 48; /// The distance from `p` to the segment `a`–`b` (to `a` when they are the same point, as a diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 22db0bfde5..c6ba48aff3 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -56,6 +56,9 @@ pub struct Report { /// thousands of different notes, and a repeat is found without going through them all. #[serde(skip)] index: HashMap<(String, NoteKind, String), usize>, + /// Different notes past [`MAX_NOTES`], not kept but counted in a last note. + #[serde(skip)] + more: usize, /// Raster image markers' images by their `imageFile`, read before the symbols showing them /// (`symbol::read_images`): each kept picture with its height over its width, or why it isn't /// drawn. Carried here because every symbol reader already takes the report; passing them @@ -100,6 +103,15 @@ impl Report { self.index.insert(key.clone(), self.notes.len()); let (layer, kind, text) = key; self.notes.push(Note { layer, kind, text, count: 1 }); + } else { + // Past the cap, a new note is counted in one closing note, never listed itself. The + // closing note stays last: nothing is added after it. + let text = format!("{} more note(s) not listed", self.more.saturating_add(1)); + match self.notes.last_mut().filter(|_| self.more > 0) { + Some(last) => last.text = text, + None => self.notes.push(Note { layer: String::new(), kind: NoteKind::Skipped, text, count: 1 }), + } + self.more = self.more.saturating_add(1); } } diff --git a/crates/map/src/qgis/source.rs b/crates/map/src/qgis/source.rs index ba7f76842c..678c18705b 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -241,12 +241,12 @@ pub fn read(provider: &str, datasource: &str, dir: &str) -> Source { let kv = conninfo(head); // What QGIS always writes and RustGIS reads or needn't. const READ_OR_HARMLESS: [&str; 7] = ["dbname", "table", "key", "srid", "type", "estimatedmetadata", "checkPrimaryKeyUnicity"]; - let ignored = kv - .iter() - .filter(|(k, _)| !READ_OR_HARMLESS.iter().any(|r| r.eq_ignore_ascii_case(k))) - .take(32) - .map(|(k, v)| noted_option(&format!("{k}={v}"))) - .collect(); + let ignored = named_options( + kv.iter() + .filter(|(k, _)| !READ_OR_HARMLESS.iter().any(|r| r.eq_ignore_ascii_case(k))) + .map(|(k, v)| noted_option(&format!("{k}={v}"))), + 0, + ); match (kv.iter().find(|(k, _)| k == "dbname"), table_of(head)) { (Some((_, db)), Some(t)) => Source::File { path: absolute(db, dir), layer: Some(t), subset, ignored }, _ => Source::Other { provider: provider.into() }, @@ -516,13 +516,14 @@ fn file(datasource: &str, dir: &str) -> Source { let mut parts = datasource.split('|'); let path = parts.next().unwrap_or_default().trim(); let (mut layer, mut subset, mut ignored) = (None, None, Vec::new()); - // Every part is read for the layer and the filter; at most 32 others are kept for the note. + // Every part is read for the layer and the filter; at most 32 others are named in the note, + // the rest counted. for p in parts { if let Some(v) = p.strip_prefix("layername=") { layer = Some(v.to_string()); } else if let Some(v) = p.strip_prefix("subset=") { subset = Some(v.to_string()).filter(|s| !s.trim().is_empty()); - } else if !p.trim().is_empty() && p.trim() != "layerid=0" && ignored.len() < 32 { + } else if !p.trim().is_empty() && p.trim() != "layerid=0" { // (layerid=0 is the first layer, which is what opens.) ignored.push(noted_option(p.trim())); } @@ -531,7 +532,24 @@ fn file(datasource: &str, dir: &str) -> Source { if layer.is_some() { ignored.retain(|o: &String| !o.starts_with("layerid=")); } - Source::File { path: absolute(path, dir), layer, subset, ignored } + Source::File { path: absolute(path, dir), layer, subset, ignored: named_options(ignored.into_iter(), 0) } +} + +/// At most 32 of a file source's unread `options`, as its note names them, and the rest, with +/// `unread` more the source holds past what was read, counted in a last entry ("and 3 more"). +fn named_options(options: impl Iterator, unread: usize) -> Vec { + let (mut named, mut more) = (Vec::new(), unread); + for o in options { + if named.len() < 32 { + named.push(o); + } else { + more += 1; + } + } + if more > 0 { + named.push(format!("and {more} more")); + } + named } /// A source option as the import notes it: with its value only for the options known to carry @@ -1193,7 +1211,12 @@ mod tests { // The layer and the filter are read past the options kept for the note. let many = format!("./m.gpkg|{}|layername=late|subset=a = 1", vec!["x=1"; 40].join("|")); let Source::File { layer, subset, ignored, .. } = read("ogr", &many, dir) else { panic!() }; - assert_eq!((layer.as_deref(), subset.as_deref(), ignored.len()), (Some("late"), Some("a = 1"), 32)); + assert_eq!((layer.as_deref(), subset.as_deref(), ignored.len()), (Some("late"), Some("a = 1"), 33)); + assert_eq!(ignored.last().map(String::as_str), Some("and 8 more"), "past 32, the rest counted"); + let many = + format!("dbname='/a.sqlite' {} table=\"t\" (geom) sql=", (0..40).map(|i| format!("o{i}=1")).collect::>().join(" ")); + let Source::File { ignored, .. } = read("spatialite", &many, dir) else { panic!() }; + assert_eq!((ignored.len(), ignored.last().map(String::as_str)), (33, Some("and 8 more")), "{ignored:?}"); assert_eq!( read("gdal", "GPKG:./m.gpkg:relief", dir), Source::File { path: "/data/project/m.gpkg".into(), layer: Some("relief".into()), subset: None, ignored: Vec::new() } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 4d1a2fcf32..6afb14fa94 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -277,13 +277,20 @@ fn hostile_files_are_refused_or_bounded() { for i in 0..(MAX_NOTES + 500) { r.approximated("a", format!("note {i}")); } - assert_eq!(r.notes.len(), MAX_NOTES); + // Those past it are counted in one closing note, after the kept ones. + assert_eq!(r.notes.len(), MAX_NOTES + 1); + let last = r.notes.last().unwrap(); + assert_eq!((last.text.as_str(), last.kind, last.layer.as_str()), ("501 more note(s) not listed", NoteKind::Skipped, "")); r.approximated("a", "note 7"); r.approximated("b", "note 7"); r.skipped("a", "note 7"); let at = r.notes.iter().position(|n| n.text == "note 7").unwrap(); assert_eq!((r.notes[at].count, r.notes[at].kind), (2, NoteKind::Approximated)); assert!(!r.notes.iter().any(|n| n.layer == "b"), "past the cap, a new note isn't kept"); + assert_eq!(r.notes.last().map(|n| n.text.as_str()), Some("503 more note(s) not listed")); + let mut few = Report::default(); + few.skipped("a", "one"); + assert!(!few.notes.iter().any(|n| n.text.contains("not listed")), "under the cap, nothing is counted apart"); } #[test] diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index ebc3719365..728ba522ed 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1013,6 +1013,9 @@ impl SourceLayer { conversion_notes.push(format!("DuckDB: {} rows of another geometry type were left out", out.other_family)); } let part = out.parts.first().ok_or_else(|| format!("{path}: the table returns no {}", d.family.label()))?; + if part.zm_dropped > 0 { + conversion_notes.push(rustgis_data::zm_note(Some(part.zm_dropped))); + } declared_empty = part.count == 0; new.path = Some(part.path.display().to_string()); let handle = rustgis_data::source::parquet::ParquetSource::open_converted_path( @@ -1023,7 +1026,7 @@ impl SourceLayer { ) .map_err(|e| format!("{path}: {e}"))?; new.handle = Some(Arc::new(handle)); - conversion_zm_dropped = false; + conversion_zm_dropped = part.zm_dropped > 0; new.duckdb = Some(d); } } else { diff --git a/crates/map/src/symbol_by.rs b/crates/map/src/symbol_by.rs index 378905f1f6..98485571b4 100644 --- a/crates/map/src/symbol_by.rs +++ b/crates/map/src/symbol_by.rs @@ -96,7 +96,8 @@ pub struct SizeBy { impl SizeBy { /// The marker size for a value: clamped to the range's ends, and with no range (`max` not - /// above `min`) the size halfway, as Proportional Symbols draw it. + /// above `min`) the size for the middle value (halfway by radius, `√0.5` of the way by area), + /// as Proportional Symbols draw it. pub fn size(&self, v: f64) -> f32 { scaled_size(v, self.min, self.max, self.min_size, self.max_size, self.scaling).clamp(0.0, MAX_SIZE) } @@ -109,9 +110,10 @@ impl SizeBy { && matches!(l.renderer, crate::Renderer::Unique { .. } | crate::Renderer::Graduated { .. }) } - /// Legend rows for the sizes: the smallest, middle and largest value, each drawn with `like` - /// and its mark stack at the mapped size and labelled with the field. Marks of a `like` sized 0 - /// have nothing to scale against and stay as set. + /// Legend rows for the sizes: the smallest, middle and largest value, each drawn with `like`'s + /// marks in the grey of "all other values" (deliberately, as the rows show sizes, not + /// classes) and its mark stack at the mapped size and labelled with the field. Marks of a + /// `like` sized 0 have nothing to scale against and stay as set. pub fn legend(&self, like: Symbol, strokes: &[LineStroke]) -> Vec { let like = Symbol { fill: crate::symbology::OTHER_FILL, ..like }; let (lo, hi) = if self.max > self.min { (self.min, self.max) } else { (self.min, self.min) }; @@ -172,7 +174,7 @@ fn scaled_marks(strokes: &[LineStroke], k: f32) -> Vec { /// A size for `v` between `min_size` and `max_size` as it falls between `min` and `max`, by /// `scaling`; values past an end take that end's size, and with no range (`max` not above `min`, -/// or one too wide to divide) the size halfway. +/// or one too wide to divide) the size for the middle value. pub fn scaled_size(v: f64, min: f64, max: f64, min_size: f32, max_size: f32, scaling: SizeScaling) -> f32 { let width = max - min; let t = if max > min && width.is_finite() { (v - min) / width } else { 0.5 }; diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index ba92fcb99f..77a13ef592 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1313,6 +1313,11 @@ impl Renderer { ramp: Ramp, base: Symbol, ) -> Result { + // The lowest number is how an open first class says it is open (`range_label`), so it + // can't be a bound of closed classes either. + if breaks.contains(&OPEN_BELOW) { + return Err(format!("manual breaks must be above {OPEN_BELOW:e}")); + } Self::graduated_by(ds, rows, field, ClassMethod::Manual, ramp, base, |vals| { manual_bounds(breaks, f64::is_finite, vals.last().copied()) }) @@ -4540,6 +4545,9 @@ mod tests { assert_eq!(breaks(open(&b).unwrap()), b); // The lowest number marks the open first class, so as a bound it is refused, not dropped. assert_eq!(open(&[0.0, f64::MIN]).unwrap_err(), "manual breaks must be above -1.7976931348623157e308"); + // Closed classes refuse it too: it would read as an open first class. + let closed = Renderer::graduated_manual(&heights(&[Some(1.0), Some(5.0)]), &[], "height", &[f64::MIN, 3.0], Ramp::Ember, base); + assert_eq!(closed.unwrap_err(), "manual breaks must be above -1.7976931348623157e308"); // The open class alone stays one class of every value. let one = open(&[OPEN_ABOVE]).unwrap(); assert_eq!(labels_of(&one), ["every value"]); diff --git a/crates/map/src/tiles.rs b/crates/map/src/tiles.rs index 0314e7aab1..07c36c2b1c 100644 --- a/crates/map/src/tiles.rs +++ b/crates/map/src/tiles.rs @@ -521,7 +521,8 @@ impl TileLayer { /// Applies the same checks, returning losses for a reader or command to report on success. pub fn repair_counted(&mut self) -> Result { let mut repairs = TileRepairs::default(); - repairs.text += usize::from(self.url.trim().len() != self.url.len()); + // Spaces round the address or the name are trimmed without a word: only text cut short + // is counted. let dated = self.time_urls.len() + usize::from(self.time_url.is_some()); self.url = self.url.trim().to_string(); // A dated address is a web address whose date is filled in after the scheme and host. @@ -547,7 +548,7 @@ impl TileLayer { } else { check_url(&self.url)?; } - repairs.text += usize::from(self.name.trim().len() != self.name.len() || self.name.chars().nth(120).is_some()); + repairs.text += usize::from(self.name.trim().chars().nth(120).is_some()); self.name = self.name.trim().chars().take(120).collect(); if self.name.is_empty() { let file = || { @@ -863,6 +864,18 @@ mod tests { } } + /// Spaces round a name or an address are trimmed without counting as text shortened; a name + /// cut to its limit is counted. + #[test] + fn trimming_isnt_counted_as_shortening() { + let mut padded = TileLayer::new(" Streets ", TileKind::Raster, " https://a.tile.example.com/{z}/{x}/{y}.png "); + assert_eq!(padded.repair_counted().map(|r| r.text), Ok(0)); + assert_eq!((padded.name.as_str(), padded.url.as_str()), ("Streets", "https://a.tile.example.com/{z}/{x}/{y}.png")); + let mut long = TileLayer::new(&format!(" {} ", "n".repeat(121)), TileKind::Raster, "https://a.tile.example.com/{z}/{x}/{y}.png"); + assert_eq!(long.repair_counted().map(|r| r.text), Ok(1)); + assert_eq!(long.name.chars().count(), 120); + } + #[test] fn invalid_coverage_does_not_hide_tiles() { let mut t = TileLayer::new("WMS", TileKind::Raster, "https://maps.example.com/wms"); diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index 1caff4af95..c29abe6d7a 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -2123,7 +2123,7 @@ mod tests { #[test] fn a_pattern_round_a_round_blocks_wall_holds_whole_periods_so_it_meets_itself_at_the_east_point() { let hatch = |angle| FillPattern::Hatch { angle, spacing: 6.0, width: 1.0, offset: 0.0 }; - // At 30° the lines repeat every 12 px across: 1000 px round holds 83 of them, stretched by 0.4%. + // At 30° the lines repeat every 12 px across: 1000 px round holds 83 of them, shrunk by 0.4%. let f = closing(hatch(30.0), 1000.0); assert!(((1000.0 * f / 12.0) - 83.0).abs() < 1e-9 && (f - 1.0).abs() < 0.01, "{f}"); assert!(((1000.0 * closing(hatch(-75.0), 1000.0) / (6.0 / 75f64.to_radians().sin())).fract()).abs() < 1e-9); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 83e5bfe1e9..abedb86fe7 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1048,9 +1048,9 @@ fn frame_outline_lonlat(map: &Map, cam: &rustgis_map::Camera, w: f64, h: f64) -> Some(g) => g.inverse(sx, sy), None => map.to_lonlat(cam.to_map(sx, sy, w, h)), }; - // A frame on the globe's longitudes kept continuous, a turn added or taken where they cross - // ±180°, so on a flat frame the outline doesn't jump across the map there. A flat frame's are - // drawn where they are. + // A frame on the globe has its longitudes kept continuous, a turn added or taken where they + // cross ±180°, so on a flat frame the outline doesn't jump across the map there. A flat + // frame's are drawn where they are. let mut last: Option = None; let mut ring = Vec::with_capacity(4 * n + 8); let mut push = |c: Option| { @@ -1351,10 +1351,10 @@ fn frame_viewport( /// points go on the map's world, whose middle (its camera's centre) is at `mid`. `from_globe`: the /// ring is a frame on the globe's, its longitudes run on across ±180° rather than kept in a world. /// -/// A frame on the globe's ring the whole ring a turn east or west if that brings the middle of its -/// longitudes nearer the map's middle, as they run on from its first point (#2348), which can be on -/// the other side of ±180° from it: one shift for all keeps it in one piece on a map that doesn't -/// wrap. A flat frame's ring is placed where it is. Then a ring that a map can't show in one piece +/// A frame on the globe has its whole ring shifted a turn east or west if that brings the middle +/// of its longitudes nearer the map's middle, as they run on from its first point (#2348), which +/// can be on the other side of ±180° from it: one shift for all keeps it in one piece on a map +/// that doesn't wrap. A flat frame's ring is placed where it is. Then a ring that a map can't show in one piece /// is cut at the map's edge as the map cuts features (#209), each piece brought into the map's /// world and running to the edge (#2369): any ring on a world projection, which wraps at its edge /// (on Robinson centred on 150°E at -30°, with its datum's margin), and on Web Mercator, which @@ -2046,8 +2046,9 @@ fn scale_number(v: f64, step: f64) -> String { /// The share of its element's width a scale bar's length may take. const BAR_SHARE: f64 = 0.85; -/// A scale bar's labels' size, and how far its bar starts in from the element's left edge, in -/// pixels: at most as many points at a pixel a point or more, which [`scale_bar_width_pt`] counts. +/// A scale bar's labels' size, in points, and how far its bar starts in from the element's left +/// edge, in pixels. [`scale_bar_width_pt`] measures the labels at that size and counts the inset as +/// that many points, never less than the bar is drawn in by when a point is a pixel or more. const BAR_LABEL_PT: f32 = 8.0; const BAR_INSET: f32 = 2.0; diff --git a/crates/render/src/line_labels.rs b/crates/render/src/line_labels.rs index e171beeca0..88dd5f1fe8 100644 --- a/crates/render/src/line_labels.rs +++ b/crates/render/src/line_labels.rs @@ -799,21 +799,23 @@ mod tests { assert!(glyphs.iter().all(|g| g.1.abs() < 1e-3 && g.2.abs() < 1e-4), "{glyphs:?}"); } - /// A bend of nearly half a turn under a label whose start-to-end direction is steep: none of - /// its characters stand upside down, though each is within a right angle of that direction. + /// A bend of nearly half a turn under a label whose start-to-end direction is steep: one whose + /// characters would stand upside down is refused; one that is placed has none upside down. #[test] - fn curved_text_round_a_half_turn_never_stands_upside_down() { + fn curved_text_past_the_turn_bound_is_refused() { // Its course turns from -0.5 to 2.9 radians, so the text's ends are -0.3 and 2.7 and its - // start-to-end direction about 1.2. + // start-to-end direction about 1.2: its far characters turn past the bound, so it is + // left out. A shorter text round the middle of the turn is placed, every character + // within the bound. let arc: Vec<(f32, f32)> = (0..=340) .map(|i| { let t = -0.5 + i as f32 / 100.0; (200.0 + 58.0 * t.sin(), 200.0 - 58.0 * t.cos()) }) .collect(); - if let Some((_, glyphs)) = curved(&arc, &[7.0; 25], 0.0, 0.0, None) { - assert!(glyphs.iter().all(|g| g.2.abs() <= std::f32::consts::FRAC_PI_2 + MAX_TURN), "upside down: {glyphs:?}"); - } + assert!(curved(&arc, &[7.0; 25], 0.0, 0.0, None).is_none()); + let (_, glyphs) = curved(&arc, &[7.0; 8], 0.0, 0.0, None).expect("a short text round the turn is placed"); + assert!(glyphs.iter().all(|g| g.2.abs() <= std::f32::consts::FRAC_PI_2 + MAX_TURN), "upside down: {glyphs:?}"); } /// A hairpin tighter than the text, sharper than [`MAX_TURN`] over a text's height: still left out. diff --git a/crates/render/src/terrain.rs b/crates/render/src/terrain.rs index 521ae15fce..490b9bcec1 100644 --- a/crates/render/src/terrain.rs +++ b/crates/render/src/terrain.rs @@ -98,7 +98,8 @@ enum Heights { } /// A map's block diagram as a frame draws it (#1914, `TerrainBlock`): the box the ground is cut -/// to (Web Mercator) and the height of its base. +/// to (Web Mercator; for a round block the square round its circle, for one cut to polygons the +/// box round their outline) and the height of its base. #[derive(Clone, Debug, PartialEq)] pub struct Block { pub x0: f64, diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 54684e9d09..76d9d470fa 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -1143,6 +1143,25 @@ pub fn paint(painter: &Painter, r: Rect, name: &str, ink: Color32, accent: Color p.line(&[(8.0, 16.0), (7.0, 20.0), (9.0, 22.0)], 1.3, ink); } "no_fill" => p.rect(3.0, 4.0, 18.0, 16.0, None, Some((1.6, ink)), 0.0), + "restore_fill" => { + // No Fill's outline filled again, and Undo's arrow over its corner: the fill put back. + p.rect(3.0, 8.0, 14.0, 13.0, Some(p.tint(150)), Some((1.6, ink)), 0.0); + paint(painter, Rect::from_min_size(p.pt(10.0, 0.0), r.size() * 0.6), "undo", ink, accent); + } + "reload" => { + // Two arrows chasing round a circle: read again from the source. + p.arc(12.0, 12.0, 7.5, 200.0, 340.0, 1.8, ink); + p.arc(12.0, 12.0, 7.5, 20.0, 160.0, 1.8, ink); + let head = |a: f32, turn: f32| { + let (c, s) = (a.to_radians().cos(), a.to_radians().sin()); + let (x, y) = (12.0 + 7.5 * c, 12.0 + 7.5 * s); + // Pointing along the circle, the way it turns. + let (tx, ty) = (-s * turn, c * turn); + p.fill(&[(x + tx * 3.5, y + ty * 3.5), (x + c * 2.6, y + s * 2.6), (x - c * 2.6, y - s * 2.6)], accent); + }; + head(340.0, 1.0); + head(160.0, 1.0); + } "g_rect" => { p.rect(3.0, 6.0, 18.0, 12.0, Some(p.tint(70)), Some((1.4, ink)), 0.5); } @@ -1349,6 +1368,8 @@ pub const ALL: &[&str] = &[ "new", "undo", "redo", + "reload", + "restore_fill", "delete", "create", "edit", diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 2c43057dbb..b424934995 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -876,6 +876,7 @@ fn position(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { if ui.checkbox(&mut on, tl!("Try other places round the point")).on_hover_text(help).changed() { run(app, "labels.placement", c.params(json!({"otherPositions": on}))); } + square_to(app, ui, l, c); } // Lines: the text along them, straight or bending with them. if l.geometry_type() == rustgis_engine::data::GeometryType::Polyline { @@ -906,6 +907,60 @@ fn position(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { crowding(app, ui, l, c); } +/// Points: the label square to the nearest line of another layer (#2263), as a river's or a +/// road's crossing is named: the Perpendicular choice, then the layer its lines come from. It +/// needs a line or polygon layer, so it starts on the first one the map has. +fn square_to(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { + use rustgis_engine::data::GeometryType; + let lines: Vec = app + .session + .map() + .layers + .iter() + .filter(|o| o.id != l.id && matches!(o.geometry_type(), GeometryType::Polyline | GeometryType::Polygon)) + .map(|o| o.name.clone()) + .collect(); + let on = c.it.placement == LabelPlacement::Perpendicular; + let to = c.it.square_to.as_ref(); + ui.add_space(4.0); + ui.label(RichText::new(tl!("Square to a line")).size(11.5)); + let first = to.map(|t| t.layer.clone()).or_else(|| lines.first().cloned()); + let button = egui::Button::selectable(on, tl!(LabelPlacement::Perpendicular.label())).truncate(); + let clicked = ui + .add_enabled_ui(first.is_some(), |ui| ui.add_sized(vec2(92.0, 22.0), button)) + .inner + .on_hover_text(tl!("The label starts at the point and runs square to the nearest line of the layer chosen below.")) + .on_disabled_hover_text(tl!("The map has no line or polygon layer to be square to.")) + .clicked(); + if clicked + && !on + && let Some(layer) = first + { + run(app, "labels.placement", c.params(json!({"position": "perpendicular", "to": {"layer": layer}}))); + } + if !on { + return; + } + let cur = to.map(|t| t.layer.clone()).unwrap_or_default(); + grid(ui, "square_to", |ui| { + let input_label = ui.label(tl!("Line layer")); + egui::ComboBox::from_id_salt("label_pane_square_to") + .selected_text(cur.clone()) + .width(180.0) + .show_ui(ui, |ui| { + for name in &lines { + if ui.selectable_label(*name == cur, name).clicked() && *name != cur { + let within = to.map(|t| t.within); + run(app, "labels.placement", c.params(json!({"to": {"layer": name, "within": within}}))); + } + } + }) + .response + .labelled_by(input_label.id); + ui.end_row(); + }); +} + /// Where labels crowd: every one shown, over the others, rather than some left out; and /// callouts, which move a crowded label to a free spot nearby with a line back to its feature, /// no longer than so far. @@ -1459,6 +1514,38 @@ mod tests { assert!(h.query_by_role_and_label(Role::CheckBox, BOX).is_none(), "not for polygons"); } + /// A point's label placed square to a line (#2263) is chosen in the pane, starting on a line + /// layer of the map, and shows as chosen however it was set. + #[test] + fn perpendicular_placement_is_chosen_and_shown_in_the_pane() { + use egui::accesskit::{Role, Toggled}; + use rustgis_engine::map::LabelPlacement; + let mut h = harness(with_cities()); + h.run(); + open_tab(&mut h, "Position"); + let chosen = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.get_by_role_and_label(Role::Button, "Perpendicular").accesskit_node().toggled() == Some(Toggled::True) + }; + assert!(!chosen(&h)); + assert!(h.query_by_role_and_label(Role::ComboBox, "Line layer").is_none(), "no layer to choose before it is chosen"); + h.get_by_role_and_label(Role::Button, "Perpendicular").click(); + h.run(); + let labels = + |h: &egui_kittest::Harness<'_, RustGisApp>| h.state().session.map().layer_by_name("Cities").unwrap().labels.default.clone(); + assert_eq!(labels(&h).placement, LabelPlacement::Perpendicular); + assert!(labels(&h).square_to.is_some()); + assert!(chosen(&h)); + // Set by a command, as a project or the Assistant sets it: shown chosen, with its layer. + h.state_mut().session.run("labels.placement", &json!({"position": "auto"})).unwrap(); + h.run(); + assert!(!chosen(&h)); + h.state_mut().session.run("labels.placement", &json!({"position": "perpendicular", "to": {"layer": "Rivers"}})).unwrap(); + h.run(); + assert!(chosen(&h)); + assert!(h.query_by_role_and_label(Role::ComboBox, "Line layer").is_some()); + assert!(h.query_by_label("Rivers").is_some()); + } + /// A line layer's labels sit a distance from the line (#1187): the row is there for a placement /// along the line, the side waits for a distance, and Below puts the label under the line. #[test] diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index fa9e138008..cf6ce2f60d 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -1809,9 +1809,11 @@ fn tile_row(app: &mut RustGisApp, ui: &mut Ui, i: usize, moves: [bool; 2], reord ui.close(); } // Its raster tiles over the view, as a GeoTIFF placed on the ground. - // Not a vector archive (one whose source layers its header names). + // Not a vector archive (one whose source layers its header names), and not in the web + // app (which downloads), which has no thread to fetch the tiles on. if matches!(tile.kind, TileKind::Raster | TileKind::PmTiles | TileKind::MbTiles) && sources.is_none() + && app.services.download.is_none() && ui.button(tl!("Export Raster…")).clicked() { action = Some(("ui.exportRaster", json!({"tiles": i}))); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 989eae4ac6..2105ecc922 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1895,7 +1895,8 @@ fn graticule_menu(ui: &mut Ui, app: &mut RustGisApp) { } } ui.separator(); - // Under the layers, filled ones hide the lines; over them, only the labels are on top. + // Under the layers, filled ones hide the lines; on top, the lines are drawn over the layers, + // and only the labels over them. let mut on_top = app.session.map().graticule_on_top; if ui .checkbox(&mut on_top, tl!("Draw on top of layers")) @@ -1995,7 +1996,7 @@ fn view_tab(app: &mut RustGisApp, ui: &mut Ui) { app, "graticule", "Graticule", - "Show or hide the graticule over the basemap: latitudes and longitudes, a measured grid, the UTM zones or the MGRS grid.", + "Show or hide the graticule over the basemap, or over the layers when drawn on top: latitudes and longitudes, a measured grid, the UTM zones or the MGRS grid.", "map.graticule", Value::Null, g, @@ -2607,7 +2608,7 @@ fn data_source_group(app: &mut RustGisApp, ui: &mut Ui) { ); #[cfg(not(target_arch = "wasm32"))] if active_layer(app).is_some_and(crate::reloaddata::supported) { - big(ui, app, "redo", "Reload\nData", crate::reloaddata::HELP, "ui.reloadData", Value::Null, false, false); + big(ui, app, "reload", "Reload\nData", crate::reloaddata::HELP, "ui.reloadData", Value::Null, false, false); } }); } @@ -4999,7 +5000,7 @@ fn drawing_group(app: &mut RustGisApp, ui: &mut Ui, layer: &rustgis_engine::map: small( ui, app, - if hidden { "symbology" } else { "no_fill" }, + if hidden { "restore_fill" } else { "no_fill" }, if hidden { "Restore Fill" } else { "No Fill" }, if hidden { "Restore polygon fills hidden by No Fill, keeping their colors and outlines." diff --git a/docs/maintaining.md b/docs/maintaining.md index d90e275d14..c8296c48bb 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -108,6 +108,7 @@ diagram cut to a circle or to polygons), `terrain-block-polygon` (one cut to pol `terrain-water`, `terrain-water-shore` (a terrain water's shore band other than the default), `terrain-block-water` (water in a block diagram's walls), +`terrain-block-walls-layer` (the layer a block diagram's walls are coloured by), `shaded-relief-effects` (cast shadows, sky visibility, fill light or rock colour), `shaded-relief-light` (a Shaded Relief's ambient or balanced light), `blank-paper` (a blank basemap's paper colour) and diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 1920cb81f4..13ae732fc4 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -265,8 +265,9 @@ around a pole spans their longitudes (a flat polygon with no area, for points on and the tool says how many hulls have no area), not the cap they enclose on the ground. For the same reason a polygon whose ring goes around a pole without reaching it (written all the way round a parallel, say, rather than cut at ±180° and closed along the pole) -is another shape in these coordinates, a line along that parallel; the overlays, joins, containment, -zone, buffer and distance tools say how many such rings they read, and in which layers, and leave +is another shape in these coordinates, a line along that parallel; the tools that read areas in +the plane (the overlays, joins, containment, zone, buffer and distance tools, Dissolve, Feature To +Point, Count Points and Tabulate Intersection) say how many such rings they read, and in which layers, and leave the data as it is. The globe draws a long edge along the great circle between its ends, so near a pole it shows a little poleward of where the tools take it: about 850 m at the middle of a 10° edge along 88°N (as everywhere, the tools take an edge as straight on the map, not on the globe). @@ -1288,8 +1289,9 @@ gp.run={"tool":"checkGeometry","params":{"input":"Parcels"}} ### Repairing geometry **Repair Geometry** (`repairGeometry`) writes every feature to a new layer, `_repaired` -unless you name it, with its geometry made valid by the rules Check Geometry checks. Only the -selected features are processed when some are selected. Each output row keeps its feature id, +unless you name it, with its geometry made valid where it can be (see the table below) by the +rules Check Geometry checks. Only the selected features are processed when some are selected. +Each output row keeps its feature id, fields, attributes and CRS, and adds a text field `repairs`: the codes of what was repaired, separated by `, ` and in the order of the table above, or empty for a feature that needed nothing. Features with nothing wrong are copied exactly as stored. If the input already has a @@ -1364,7 +1366,7 @@ that narrow in any direction is dropped: `no_area` is added after the other code the tool says how many holes and parts were dropped this way, from how many features. A feature that can't be repaired stays in the output without geometry, with its attributes, and -`repairs` says why. One the tool couldn't repair is written unchanged, never dropped: +`repairs` says why. A feature the tool can't repair is written as the table says, never dropped: | Code | Written | Why | | --- | --- | --- | diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 5fed893670..959c74af2d 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -683,6 +683,15 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: A feature with no guide line its text fits along is labelled as without a guide (`labels.placement={"layer": "Serras", "guide": {"layer": "Cumeadas", "field": "nome"}}`; `"guide": null` removes it). +- **Square to a line**: a point's label can start at the point and run square to the nearest line + of another layer, as the name of a bridge or a gauge reads across its river (Labeling pane › + Position › Square to a line › **Perpendicular**, then the **Line layer**, a line or polygon + layer; the button starts on the map's first). `to` names the layer and `within` how near its + line must be, 1 to 500 points (20 by default); `side` runs the text `"away"` from the line, to + the side the point isn't on (the default), or to its `"left"` or `"right"` as the line runs. A + point with no line that near is labelled as automatic, and so is every point while the layer is + missing (`labels.placement={"layer": "Gauges", "position": "perpendicular", "to": {"layer": + "Rivers", "within": 30}, "side": "left"}`; another position takes it off). - **Other places round points**: a point's label whose place another label takes tries the other places round the point, corners first (above right, above left, below right, below left, right, left, above, below, leaving out its own), and goes to the first where diff --git a/schema/fixtures/terrain_block_walls_layer_v2.rgis b/schema/fixtures/terrain_block_walls_layer_v2.rgis new file mode 100644 index 0000000000..7e581490b4 --- /dev/null +++ b/schema/fixtures/terrain_block_walls_layer_v2.rgis @@ -0,0 +1 @@ +{"format":2,"name":"Terrain block walls layer","maps":[{"name":"Map","layers":[],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"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":{"source":{"Layer":"dem"},"exaggeration":2.0,"block":{"extent":[-500000.0,1500000.0,500000.0,2500000.0],"depth":150.0,"walls":[128,96,64,255],"walls_layer":"geologia"}}},"animation":[],"next_layer_id":1}],"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":["terrain-block","terrain-block-walls-layer"]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 1254f284f1..58eeee8d0f 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1085,6 +1085,7 @@ "terrain-water", "terrain-water-shore", "terrain-block-water", + "terrain-block-walls-layer", "shaded-relief-effects", "normalized-legend-urls", "field-origin", @@ -1184,6 +1185,7 @@ "terrain-water", "terrain-water-shore", "terrain-block-water", + "terrain-block-walls-layer", "shaded-relief-effects", "normalized-legend-urls", "field-origin", From 99ee93d3d523ffcd44d7bd1daa53ebf7cb5aff91 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 00:03:47 -0500 Subject: [PATCH 2/7] test(sweep): follow the reworded walls notice; clippy --- crates/engine/src/tests.rs | 2 +- crates/map/src/tiles.rs | 2 +- crates/ui-egui/src/labelpane.rs | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f741231074..3061c1e3c7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -14925,7 +14925,7 @@ fn terrain_block_walls_follow_a_polygon_layer() { twice.maps[0].layers.push(copy); let mut opened = Session::new(Project::default()); crate::cmd::project::reset_to(&mut opened, twice); - assert!(opened.notices.iter().any(|n| n.text.contains("of a name another layer shares")), "{:?}", opened.notices); + assert!(opened.notices.iter().any(|n| n.text.contains("shares its name with another layer")), "{:?}", opened.notices); let mut clean = Session::new(Project::default()); crate::cmd::project::reset_to(&mut clean, s.project.clone()); assert!(!clean.notices.iter().any(|n| n.text.contains("walls layer")), "{:?}", clean.notices); diff --git a/crates/map/src/tiles.rs b/crates/map/src/tiles.rs index 07c36c2b1c..914d9f196a 100644 --- a/crates/map/src/tiles.rs +++ b/crates/map/src/tiles.rs @@ -871,7 +871,7 @@ mod tests { let mut padded = TileLayer::new(" Streets ", TileKind::Raster, " https://a.tile.example.com/{z}/{x}/{y}.png "); assert_eq!(padded.repair_counted().map(|r| r.text), Ok(0)); assert_eq!((padded.name.as_str(), padded.url.as_str()), ("Streets", "https://a.tile.example.com/{z}/{x}/{y}.png")); - let mut long = TileLayer::new(&format!(" {} ", "n".repeat(121)), TileKind::Raster, "https://a.tile.example.com/{z}/{x}/{y}.png"); + let mut long = TileLayer::new(format!(" {} ", "n".repeat(121)), TileKind::Raster, "https://a.tile.example.com/{z}/{x}/{y}.png"); assert_eq!(long.repair_counted().map(|r| r.text), Ok(1)); assert_eq!(long.name.chars().count(), 120); } diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index b424934995..f6ed4c03ac 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -1543,7 +1543,6 @@ mod tests { h.run(); assert!(chosen(&h)); assert!(h.query_by_role_and_label(Role::ComboBox, "Line layer").is_some()); - assert!(h.query_by_label("Rivers").is_some()); } /// A line layer's labels sit a distance from the line (#1187): the row is there for a placement From 4d5a255f7ad4a096ef7d31e8a2347ca19fcdd32d Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 00:07:10 -0500 Subject: [PATCH 3/7] fix(ui): Perpendicular's button fits its label --- crates/ui-egui/src/labelpane.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index f6ed4c03ac..0b9c3b2ddc 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -927,7 +927,7 @@ fn square_to(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { let first = to.map(|t| t.layer.clone()).or_else(|| lines.first().cloned()); let button = egui::Button::selectable(on, tl!(LabelPlacement::Perpendicular.label())).truncate(); let clicked = ui - .add_enabled_ui(first.is_some(), |ui| ui.add_sized(vec2(92.0, 22.0), button)) + .add_enabled_ui(first.is_some(), |ui| ui.add_sized(vec2(124.0, 22.0), button)) .inner .on_hover_text(tl!("The label starts at the point and runs square to the nearest line of the layer chosen below.")) .on_disabled_hover_text(tl!("The map has no line or polygon layer to be square to.")) From 02e18b26868ace28ebe6560d65bb7032344d6084 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 01:06:07 -0500 Subject: [PATCH 4/7] Address CodeRabbit review feedback - network: the overflow scan looks at Cancel every 4096 segments - network: a route reports lines closed for an overflowing cost, in its result, its notice and its errors - network analysis: the no-lines refusal keeps the notes that say why - duckdb: reserved column names are refused in any case - layout.publication: a whole-globe map omits the locator by default - GeoLibre style: an empty range says points without a value draw at the base size - QGIS: the closing note counts its occurrences; SpatiaLite options past the 100 pairs read are counted - Labels pane: targets follow the engine's rule, a kept target is reused only while eligible, with its distance - analysis guide: unrepaired features keep or lose geometry per table --- crates/analysis/src/network.rs | 68 +++++++++++++------ crates/analysis/src/tools/network_analysis.rs | 12 +++- crates/data/src/source/duckdb.rs | 2 +- crates/engine/src/cmd/layout.rs | 2 +- crates/engine/src/cmd/workflows.rs | 9 +++ crates/map/src/geolibre/style.rs | 2 +- crates/map/src/qgis/mod.rs | 5 +- crates/map/src/qgis/source.rs | 31 ++++++--- crates/map/src/qgis/tests.rs | 2 +- crates/ui-egui/src/labelpane.rs | 10 ++- docs/user-guide/analysis.md | 4 +- 11 files changed, 106 insertions(+), 41 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 2ccaeda174..090e1687e1 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -16,6 +16,8 @@ pub struct Route { pub rows: Vec, /// Segments omitted because an endpoint has non-finite coordinates or an invalid latitude. pub skipped_segments: usize, + /// Lines closed because their cost times a segment's length is past the largest number. + pub overflowing: usize, } #[derive(PartialEq)] @@ -52,25 +54,35 @@ struct Network { } /// Whether a segment of a line in `parts` costs no finite number at `weight` a metre. Segments -/// left out for their coordinates don't count. -fn cost_overflows(parts: &[Vec], weight: f64) -> bool { +/// left out for their coordinates don't count. It looks at Cancel as `build` does, every 4096 +/// segments measured. +fn cost_overflows(parts: &[Vec], weight: f64, pace: &mut crate::control::Pace) -> Result { // No segment is longer than half the Earth's circumference: a weight finite at that length // is finite on every segment, so the segments are measured only past it. if (weight * 2.1e7).is_finite() { - return false; + return Ok(false); } - parts.iter().flat_map(|part| part.windows(2)).any(|w| match (w.first(), w.get(1)) { - (Some(a), Some(b)) if a.is_finite() && b.is_finite() && a.y.abs() <= 90.0 && b.y.abs() <= 90.0 => { - !(wgs84_distance_m(*a, *b) * weight).is_finite() + for w in parts.iter().flat_map(|part| part.windows(2)) { + if pace.stop(4096) { + return Err(crate::control::Cancelled.into()); } - _ => false, - }) + if let (Some(a), Some(b)) = (w.first(), w.get(1)) + && a.is_finite() + && b.is_finite() + && a.y.abs() <= 90.0 + && b.y.abs() <= 90.0 + && !(wgs84_distance_m(*a, *b) * weight).is_finite() + { + return Ok(true); + } + } + Ok(false) } impl Network { /// Builds edges in source order, preserving shortest-path tie breaking and arithmetic. fn build(ds: &Dataset, rows: &[usize], cost_field: Option) -> Result { - let route_error = |reason, skipped| route_error(ds, reason, skipped); + let route_error = |reason, skipped, overflowing| route_error(ds, reason, skipped, overflowing); let mut skipped_segments = 0; let mut overflowing = 0; let mut ids: HashMap<(i64, i64), usize> = HashMap::new(); @@ -97,7 +109,7 @@ impl Network { Some(Some(_)) => continue, _ => 1.0, }; - if cost_overflows(parts, weight) { + if cost_overflows(parts, weight, &mut pace)? { overflowing += 1; continue; } @@ -124,13 +136,13 @@ impl Network { segs.push((ia, ib, weight, *r)); // Checked per segment, so one huge feature can't grow the network unbounded. if segs.len() > 10_000_000 || nodes.len() > 5_000_000 { - return Err(route_error("the network is too large".into(), skipped_segments)); + return Err(route_error("the network is too large".into(), skipped_segments, overflowing)); } } } } if segs.is_empty() && skipped_segments > 0 { - return Err(route_error("no usable network remains".into(), skipped_segments)); + return Err(route_error("no usable network remains".into(), skipped_segments, overflowing)); } crate::control::finish(); Ok(Self { nodes, adj, segs, skipped_segments, overflowing }) @@ -203,13 +215,20 @@ fn network_keyed( Ok(graph) } -/// Preserve clean-network errors; failed partial routes must still disclose omissions. -fn route_error(ds: &Dataset, reason: String, skipped_segments: usize) -> String { - if skipped_segments == 0 { - reason - } else { - format!("{reason}; {skipped_segments} segments with invalid coordinates were omitted from '{}'", ds.name) +/// Preserve clean-network errors; failed partial routes must still disclose omissions: segments +/// with invalid coordinates and lines closed for a cost past the largest number. +fn route_error(ds: &Dataset, reason: String, skipped_segments: usize, overflowing: usize) -> String { + let mut said = reason; + if skipped_segments > 0 { + said.push_str(&format!("; {skipped_segments} segments with invalid coordinates were omitted from '{}'", ds.name)); + } + if overflowing > 0 { + said.push_str(&format!( + "; {overflowing} lines of '{}' cost so much that a segment's cost is past the largest number, and were closed", + ds.name + )); } + said } /// The shortest route between two points over the lines of `rows`, joining where vertices @@ -356,7 +375,7 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) let mut adj = graph.adj.clone(); let segs = &graph.segs; let skipped_segments = graph.skipped_segments; - let route_error = |reason, skipped| route_error(ds, reason, skipped); + let route_error = |reason, skipped| route_error(ds, reason, skipped, graph.overflowing); let nearest = |p: Coord, nodes: &[Coord]| nearest_segment(segs, nodes, p, None); // Each end becomes a node on its segment, joined to the segment's two ends. let attach = |p: Coord, nodes: &mut Vec, adj: &mut Vec>| -> Result<(usize, usize, f64), String> { @@ -462,7 +481,7 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) used.reverse(); used.dedup(); crate::control::finish(); - Ok(Route { path, length_m: length, cost, rows: used, skipped_segments }) + Ok(Route { path, length_m: length, cost, rows: used, skipped_segments, overflowing: graph.overflowing }) } // --------------------------------------------------------------------------------------------- @@ -1545,6 +1564,15 @@ mod tests { let cheap = shortest_route(&ds, &rows, Coord::new(0.0, 0.0), Coord::new(1.0, 1.0), Some(0), 1000.0).unwrap_or_else(|e| panic!("{e}")); assert_eq!(cheap.rows, vec![0, 1], "by cost the two sides win"); + assert_eq!((short.overflowing, cheap.overflowing), (0, 0)); + // A cost whose segments' costs overflow closes its line, and the route says so. + let mut huge = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("cost", FieldType::Double)]); + huge.push(l((0.0, 0.0), (1.0, 0.0)), vec![Value::Float(1.0)]); + huge.push(l((1.0, 0.0), (1.0, 1.0)), vec![Value::Float(1.0)]); + huge.push(l((0.0, 0.0), (1.0, 1.0)), vec![Value::Float(1e306)]); + let around = + shortest_route(&huge, &rows, Coord::new(0.0, 0.0), Coord::new(1.0, 1.0), Some(0), 1000.0).unwrap_or_else(|e| panic!("{e}")); + assert_eq!((around.rows, around.overflowing), (vec![0, 1], 1)); assert!(shortest_route(&ds, &rows, Coord::new(5.0, 5.0), Coord::new(1.0, 1.0), None, 1000.0).is_err()); let mut poly = Dataset::new("p", GeometryType::Polygon, vec![]); poly.push( diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index 4700845ac8..d54496c7b2 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -96,7 +96,9 @@ fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result, )); } if graph.segments() == 0 { - return Err(format!("'{}' has no lines to search", ds.name)); + // What left no lines is said with it: the notes would be lost with the run. + let why = if notes.is_empty() { String::new() } else { format!(" ({})", notes.join("; ")) }; + return Err(format!("'{}' has no lines to search{why}", ds.name)); } Ok(Network { ds, graph, unit_m, snap_m, notes }) } @@ -719,6 +721,14 @@ mod tests { "{:?}", r.messages ); + // Every line closed so: the refusal says why. + let mut all = roads(); + for f in all.features.iter_mut() { + f.attrs[0] = Value::Float(1e306); + } + let inputs = map(vec![all, points("shops", &[Some(c(0.005, 0.0))])]); + let e = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "5", "costField": "cost"})).unwrap_err(); + assert!(e.contains("has no lines to search") && e.contains("4 line(s) of 'roads' cost so much"), "{e}"); } /// A point just across ±180° from a line is moved onto it, about 110 m away, not left out as diff --git a/crates/data/src/source/duckdb.rs b/crates/data/src/source/duckdb.rs index e361e42821..92bafa6729 100644 --- a/crates/data/src/source/duckdb.rs +++ b/crates/data/src/source/duckdb.rs @@ -925,7 +925,7 @@ fn run_selected_in(dir: &Path, q: &Query<'_>, confined: bool, selected: Option Vec { r#"{"name"?: string, "page"?: "letter"|"legal"|"tabloid"|"a5"|"a4"|"a3"|"a2"|"a1"|"a0", "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "template"?: "map" (frame, title, legend, north arrow, scale bar; the default)|"blank"}"#, ), C::new("layout.publication", "New Publication Layout", "Publish › Layout", publication).inputs(publication_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"profile"?: "a4" (the default) | "letter"|"legal"|"tabloid"|"a5"|"a3"|"a2"|"a1"|"a0" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | a size with its orientation: "a4-portrait"|"a4-landscape"|"letter-portrait"|"tabloid-landscape"|… for each of those sizes (a sheet: frame, title, subtitle, the map, a boxed footer, all scaled to the sheet)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets, but for a map on the globe with no extent, the globe seen whole, which has no locator and no scale bar, the globe filling its frame) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster with a colour scale, not drawn by classes, gets one, under the legend in its box; a raster drawn by classes has them in the legend's rows instead) | "none" (no colorbar, and the legend's box has no room for one), "veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "contextInLegend"?: false (the default: layers the placement takes as context around the data, polygons only outlined or, beside a layer drawn by classes or a raster, in one colour and running on past the frame, are left out of the legend, which a warning names) | true (the legend lists them), "northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none", "legendBox"?: "auto" (the default: over the map, the legend has no box where the map shows nothing under it but its light plain paper or water, with no layer, context, basemap shape or graticule line there and no veil; the answer's "legendBox" says whether it has one) | "always", "style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite, each arrangement by name and each saved with layout.arrangement laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name (built in or saved) or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves), "coverage"?: "*.png" (writes the coverage grid the placement searched, as it settled on it, three pixels a cell: what the map draws dark, the free cells white, both tinted blue in the strips the graticule's labels keep, the surrounds placed over the map outlined in red; the answer gives its path)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, + r#"{"profile"?: "a4" (the default) | "letter"|"legal"|"tabloid"|"a5"|"a3"|"a2"|"a1"|"a0" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | a size with its orientation: "a4-portrait"|"a4-landscape"|"letter-portrait"|"tabloid-landscape"|… for each of those sizes (a sheet: frame, title, subtitle, the map, a boxed footer, all scaled to the sheet)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets, but for a map on the globe with no extent, the globe seen whole, which by default has no locator (one asked for by name is drawn) and no scale bar, the globe filling its frame) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster with a colour scale, not drawn by classes, gets one, under the legend in its box; a raster drawn by classes has them in the legend's rows instead) | "none" (no colorbar, and the legend's box has no room for one), "veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "contextInLegend"?: false (the default: layers the placement takes as context around the data, polygons only outlined or, beside a layer drawn by classes or a raster, in one colour and running on past the frame, are left out of the legend, which a warning names) | true (the legend lists them), "northArrow"?: "auto" (the default: none when the extent spans 20° or more on its longer side, where the graticule gives north, which a warning says) | "always" | "none", "legendBox"?: "auto" (the default: over the map, the legend has no box where the map shows nothing under it but its light plain paper or water, with no layer, context, basemap shape or graticule line there and no veil; the answer's "legendBox" says whether it has one) | "always", "style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite, each arrangement by name and each saved with layout.arrangement laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name (built in or saved) or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves), "coverage"?: "*.png" (writes the coverage grid the placement searched, as it settled on it, three pixels a cell: what the map draws dark, the free cells white, both tinted blue in the strips the graticule's labels keep, the surrounds placed over the map outlined in red; the answer gives its path)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, ), C::new("layout.arrangement", "Favourite Arrangement", "Publish › Layout", arrangement).roles(&[]).effects(crate::policy::Effects::NONE).view().params( r#"{"favourite"?: "classic" (the locator top left, the north arrow top right, the legend bottom left, the scale bar bottom right) | "mirrored" | "legendRight" | "legendTop" | {"locator", "northArrow", "legend", "scaleBar": "top-left"|"top-right"|"bottom-left"|"bottom-right", each a corner of its own} | a saved arrangement's name, "save"?: a name (1 to 40 characters, not a built-in one nor "best", "favourite", "custom" or "veil"; one saved under it already, case aside, is replaced) to save "arrangement" under (at most 20 saved), "arrangement"?: what "save" saves: an arrangement by name, or a corner for each surround as "favourite" takes them (refused without "save"), "remove"?: a saved arrangement's name (a favourite named after it keeps its corners, unless "favourite" gives another)} → the favourite arrangement of publication layouts and those saved by name (kept with the app's preferences), the favourite's corners, the arrangements by name and the saved ones' corners; a removal, then a save, then the favourite; with none of them given, they are only shown"#, diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index ce64d92a5a..7e5e266d83 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1778,6 +1778,15 @@ fn route(s: &mut Session, p: &Value) -> CmdResult { false, ); } + if r.overflowing > 0 { + s.notify( + format!( + "{source_name}: {} lines cost so much that a segment's cost is past the largest number, and were closed in the route network", + r.overflowing + ), + false, + ); + } Ok(json!({"layer": nid, "lengthKm": r.length_m / 1000.0, "cost": r.cost, "segments": r.rows.len()})) } diff --git a/crates/map/src/geolibre/style.rs b/crates/map/src/geolibre/style.rs index d4e05686c0..f4c3834b18 100644 --- a/crates/map/src/geolibre/style.rs +++ b/crates/map/src/geolibre/style.rs @@ -120,7 +120,7 @@ pub fn apply(layer: &mut Layer, record: &Value, report: &mut Report) { layer.renderer = Renderer::Proportional { field: field.into(), base: symbol, min, max, min_size, max_size }; sized = true; if max <= min { - report.approximated(&name, "proportional size range is empty (its largest value isn't above its smallest); every point is drawn at the middle size"); + report.approximated(&name, "proportional size range is empty (its largest value isn't above its smallest); every point with a value is drawn at the middle size, one without at the base symbol's"); } else { report.approximated(&name, "proportional sizes use area scaling instead of MapLibre linear radius scaling"); } diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index c6ba48aff3..48cecfcc37 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -108,7 +108,10 @@ impl Report { // closing note stays last: nothing is added after it. let text = format!("{} more note(s) not listed", self.more.saturating_add(1)); match self.notes.last_mut().filter(|_| self.more > 0) { - Some(last) => last.text = text, + Some(last) => { + last.text = text; + last.count = last.count.saturating_add(1); + } None => self.notes.push(Note { layer: String::new(), kind: NoteKind::Skipped, text, count: 1 }), } self.more = self.more.saturating_add(1); diff --git a/crates/map/src/qgis/source.rs b/crates/map/src/qgis/source.rs index 678c18705b..2a1aeed189 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -238,15 +238,13 @@ pub fn read(provider: &str, datasource: &str, dir: &str) -> Source { // any, runs to the end. let (head, sql) = datasource.rsplit_once(" sql=").unwrap_or((datasource, "")); let subset = Some(sql.trim().to_string()).filter(|q| !q.is_empty()); - let kv = conninfo(head); // What QGIS always writes and RustGIS reads or needn't. const READ_OR_HARMLESS: [&str; 7] = ["dbname", "table", "key", "srid", "type", "estimatedmetadata", "checkPrimaryKeyUnicity"]; - let ignored = named_options( - kv.iter() - .filter(|(k, _)| !READ_OR_HARMLESS.iter().any(|r| r.eq_ignore_ascii_case(k))) - .map(|(k, v)| noted_option(&format!("{k}={v}"))), - 0, - ); + let harmless = |k: &str| READ_OR_HARMLESS.iter().any(|r| r.eq_ignore_ascii_case(k)); + // Options past the 100 pairs read are counted with those not named (the table is read + // from the text itself). + let (kv, past, _) = conninfo_counted(head, |k| !harmless(k)); + let ignored = named_options(kv.iter().filter(|(k, _)| !harmless(k)).map(|(k, v)| noted_option(&format!("{k}={v}"))), past); match (kv.iter().find(|(k, _)| k == "dbname"), table_of(head)) { (Some((_, db)), Some(t)) => Source::File { path: absolute(db, dir), layer: Some(t), subset, ignored }, _ => Source::Other { provider: provider.into() }, @@ -919,12 +917,20 @@ fn conninfo(s: &str) -> Vec<(String, String)> { /// [`conninfo`], and how many pairs it doesn't keep: those past the 100 it reads, and one for text /// it can't read as a pair (which stops it). fn conninfo_rest(s: &str) -> (Vec<(String, String)>, usize) { + let (out, past, stopped) = conninfo_counted(s, |_| true); + (out, past + usize::from(stopped)) +} + +/// [`conninfo`], with the pairs past the 100 it reads whose name `counts`, apart from whether it +/// stopped at text it can't read as a pair (as a SpatiaLite source's `(geom)` after its table). +fn conninfo_counted(s: &str, counts: impl Fn(&str) -> bool) -> (Vec<(String, String)>, usize, bool) { let mut out = Vec::new(); let mut unread = 0usize; + let mut stopped = false; let mut rest = s.trim(); while !rest.is_empty() { let Some((k, after)) = rest.split_once('=') else { - unread += 1; + stopped = true; break; }; let k = k.trim().to_string(); @@ -950,12 +956,12 @@ fn conninfo_rest(s: &str) -> (Vec<(String, String)>, usize) { }; if out.len() < 100 { out.push((k, v)); - } else { + } else if counts(&k) { unread += 1; } rest = next.trim_start(); } - (out, unread) + (out, unread, stopped) } /// A connection text's `table="schema"."table" (geom)`, as `schema.table` (or `table`). @@ -1217,6 +1223,11 @@ mod tests { format!("dbname='/a.sqlite' {} table=\"t\" (geom) sql=", (0..40).map(|i| format!("o{i}=1")).collect::>().join(" ")); let Source::File { ignored, .. } = read("spatialite", &many, dir) else { panic!() }; assert_eq!((ignored.len(), ignored.last().map(String::as_str)), (33, Some("and 8 more")), "{ignored:?}"); + // Past the 100 pairs a connection text is read to, the rest are counted too. + let many = + format!("dbname='/a.sqlite' {} table=\"t\" (geom) sql=", (0..110).map(|i| format!("o{i}=1")).collect::>().join(" ")); + let Source::File { ignored, .. } = read("spatialite", &many, dir) else { panic!() }; + assert_eq!(ignored.last().map(String::as_str), Some("and 78 more"), "{ignored:?}"); assert_eq!( read("gdal", "GPKG:./m.gpkg:relief", dir), Source::File { path: "/data/project/m.gpkg".into(), layer: Some("relief".into()), subset: None, ignored: Vec::new() } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 6afb14fa94..a66dc56bcd 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -287,7 +287,7 @@ fn hostile_files_are_refused_or_bounded() { let at = r.notes.iter().position(|n| n.text == "note 7").unwrap(); assert_eq!((r.notes[at].count, r.notes[at].kind), (2, NoteKind::Approximated)); assert!(!r.notes.iter().any(|n| n.layer == "b"), "past the cap, a new note isn't kept"); - assert_eq!(r.notes.last().map(|n| n.text.as_str()), Some("503 more note(s) not listed")); + assert_eq!(r.notes.last().map(|n| (n.text.as_str(), n.count)), Some(("503 more note(s) not listed", 503))); let mut few = Report::default(); few.skipped("a", "one"); assert!(!few.notes.iter().any(|n| n.text.contains("not listed")), "under the cap, nothing is counted apart"); diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 0b9c3b2ddc..caf4b8e5a9 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -917,14 +917,17 @@ fn square_to(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { .map() .layers .iter() - .filter(|o| o.id != l.id && matches!(o.geometry_type(), GeometryType::Polyline | GeometryType::Polygon)) + // As `labels.placement` takes them: a layer with any line or polygon. + .filter(|o| o.id != l.id && (o.has_geometry(GeometryType::Polyline) || o.has_geometry(GeometryType::Polygon))) .map(|o| o.name.clone()) .collect(); let on = c.it.placement == LabelPlacement::Perpendicular; let to = c.it.square_to.as_ref(); ui.add_space(4.0); ui.label(RichText::new(tl!("Square to a line")).size(11.5)); - let first = to.map(|t| t.layer.clone()).or_else(|| lines.first().cloned()); + // The layer kept from before when it can still be one (with its distance), else the first. + let kept = to.filter(|t| lines.iter().any(|n| n.eq_ignore_ascii_case(&t.layer))); + let first = kept.map(|t| t.layer.clone()).or_else(|| lines.first().cloned()); let button = egui::Button::selectable(on, tl!(LabelPlacement::Perpendicular.label())).truncate(); let clicked = ui .add_enabled_ui(first.is_some(), |ui| ui.add_sized(vec2(124.0, 22.0), button)) @@ -936,7 +939,8 @@ fn square_to(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { && !on && let Some(layer) = first { - run(app, "labels.placement", c.params(json!({"position": "perpendicular", "to": {"layer": layer}}))); + let within = kept.map(|t| t.within); + run(app, "labels.placement", c.params(json!({"position": "perpendicular", "to": {"layer": layer, "within": within}}))); } if !on { return; diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 13ae732fc4..15934da2ce 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1365,8 +1365,8 @@ at an angle. So before the overlay takes out a part's holes or merges the parts, that narrow in any direction is dropped: `no_area` is added after the other codes in `repairs`, and the tool says how many holes and parts were dropped this way, from how many features. -A feature that can't be repaired stays in the output without geometry, with its attributes, and -`repairs` says why. A feature the tool can't repair is written as the table says, never dropped: +A feature that can't be repaired stays in the output with its attributes, without its geometry +or with it unchanged as the table says, and `repairs` says why; none is dropped: | Code | Written | Why | | --- | --- | --- | From a6c13350a2f3fc0dd64184a657add7fb253a72d3 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 01:16:08 -0500 Subject: [PATCH 5/7] Address review feedback - QGIS: notes past the cap are counted in a closing note of their own kind, so approximations stay approximations - network: a route whose costs only add up past the largest number says so instead of "not connected" - GeoLibre style: the empty-range note says the middle value is scaled by area, not MapLibre's linear radius --- crates/analysis/src/network.rs | 16 ++++++++++++++++ crates/map/src/geolibre/style.rs | 2 +- crates/map/src/qgis/mod.rs | 28 ++++++++++++++++++++-------- crates/map/src/qgis/tests.rs | 10 +++++++--- 4 files changed, 44 insertions(+), 12 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 090e1687e1..68e2154434 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -426,6 +426,7 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) let mut dist = vec![f64::INFINITY; n]; let mut prev: Vec> = vec![None; n]; let mut heap = BinaryHeap::new(); + let mut summed_past = false; if let Some(d) = dist.get_mut(s) { *d = 0.0; } @@ -448,6 +449,9 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) return Err(crate::control::Cancelled.into()); } let nd = d + c; + // Each edge's cost is finite, but a path's sum of them can pass the largest number: + // never taken, and said if the route then has none. + summed_past |= c.is_finite() && !nd.is_finite(); if nd < dist.get(v).copied().unwrap_or(f64::INFINITY) { if let Some(x) = dist.get_mut(v) { *x = nd; @@ -460,6 +464,12 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) } } let cost = dist.get(t).copied().unwrap_or(f64::INFINITY); + if !cost.is_finite() && summed_past { + return Err(route_error( + "no route costs less than the largest number: the costs along the network add up past it (give the lines smaller costs)".into(), + skipped_segments, + )); + } if !cost.is_finite() { return Err(route_error("the two points aren't connected by the network".into(), skipped_segments)); } @@ -1573,6 +1583,12 @@ mod tests { let around = shortest_route(&huge, &rows, Coord::new(0.0, 0.0), Coord::new(1.0, 1.0), Some(0), 1000.0).unwrap_or_else(|e| panic!("{e}")); assert_eq!((around.rows, around.overflowing), (vec![0, 1], 1)); + // Each edge finite, their sum past the largest number: said, not "not connected". + let mut summed = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("cost", FieldType::Double)]); + let two = vec![Coord::new(0.0, 0.0), Coord::new(0.00001, 0.0), Coord::new(0.00002, 0.0)]; + summed.push(Some(Geometry::Line(vec![two])), vec![Value::Float(1e308)]); + let e = shortest_route(&summed, &[0], Coord::new(0.0, 0.0), Coord::new(0.00002, 0.0), Some(0), 1000.0).unwrap_err(); + assert!(e.contains("add up past it"), "{e}"); assert!(shortest_route(&ds, &rows, Coord::new(5.0, 5.0), Coord::new(1.0, 1.0), None, 1000.0).is_err()); let mut poly = Dataset::new("p", GeometryType::Polygon, vec![]); poly.push( diff --git a/crates/map/src/geolibre/style.rs b/crates/map/src/geolibre/style.rs index f4c3834b18..12b2dc6c96 100644 --- a/crates/map/src/geolibre/style.rs +++ b/crates/map/src/geolibre/style.rs @@ -120,7 +120,7 @@ pub fn apply(layer: &mut Layer, record: &Value, report: &mut Report) { layer.renderer = Renderer::Proportional { field: field.into(), base: symbol, min, max, min_size, max_size }; sized = true; if max <= min { - report.approximated(&name, "proportional size range is empty (its largest value isn't above its smallest); every point with a value is drawn at the middle size, one without at the base symbol's"); + report.approximated(&name, "proportional size range is empty (its largest value isn't above its smallest); every point with a value is drawn at the size for the middle value, scaled by area (not MapLibre's linear radius), one without at the base symbol's"); } else { report.approximated(&name, "proportional sizes use area scaling instead of MapLibre linear radius scaling"); } diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 48cecfcc37..7f357774e9 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -56,9 +56,10 @@ pub struct Report { /// thousands of different notes, and a repeat is found without going through them all. #[serde(skip)] index: HashMap<(String, NoteKind, String), usize>, - /// Different notes past [`MAX_NOTES`], not kept but counted in a last note. + /// Different notes past [`MAX_NOTES`], not kept but counted in a closing note of their kind: + /// approximated, then skipped. #[serde(skip)] - more: usize, + more: [usize; 2], /// Raster image markers' images by their `imageFile`, read before the symbols showing them /// (`symbol::read_images`): each kept picture with its height over its width, or why it isn't /// drawn. Carried here because every symbol reader already takes the report; passing them @@ -104,17 +105,28 @@ impl Report { let (layer, kind, text) = key; self.notes.push(Note { layer, kind, text, count: 1 }); } else { - // Past the cap, a new note is counted in one closing note, never listed itself. The - // closing note stays last: nothing is added after it. - let text = format!("{} more note(s) not listed", self.more.saturating_add(1)); - match self.notes.last_mut().filter(|_| self.more > 0) { + // Past the cap, a new note is counted in a closing note of its kind, never listed + // itself. The closing notes are the last two at most: nothing else is added after them. + let (_, kind, _) = key; + let k = usize::from(kind == NoteKind::Skipped); + let more = self.more.get(k).copied().unwrap_or(0).saturating_add(1); + let text = format!("{more} more note(s) not listed"); + let closing = self + .notes + .iter_mut() + .rev() + .take(2) + .find(|n| n.kind == kind && n.layer.is_empty() && more > 1 && n.text.ends_with(" more note(s) not listed")); + match closing { Some(last) => { last.text = text; last.count = last.count.saturating_add(1); } - None => self.notes.push(Note { layer: String::new(), kind: NoteKind::Skipped, text, count: 1 }), + None => self.notes.push(Note { layer: String::new(), kind, text, count: 1 }), + } + if let Some(m) = self.more.get_mut(k) { + *m = more; } - self.more = self.more.saturating_add(1); } } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index a66dc56bcd..ed228c6490 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -277,17 +277,21 @@ fn hostile_files_are_refused_or_bounded() { for i in 0..(MAX_NOTES + 500) { r.approximated("a", format!("note {i}")); } - // Those past it are counted in one closing note, after the kept ones. + // Those past it are counted in a closing note of their kind, after the kept ones. assert_eq!(r.notes.len(), MAX_NOTES + 1); let last = r.notes.last().unwrap(); - assert_eq!((last.text.as_str(), last.kind, last.layer.as_str()), ("501 more note(s) not listed", NoteKind::Skipped, "")); + assert_eq!((last.text.as_str(), last.kind, last.layer.as_str()), ("501 more note(s) not listed", NoteKind::Approximated, "")); r.approximated("a", "note 7"); r.approximated("b", "note 7"); r.skipped("a", "note 7"); let at = r.notes.iter().position(|n| n.text == "note 7").unwrap(); assert_eq!((r.notes[at].count, r.notes[at].kind), (2, NoteKind::Approximated)); assert!(!r.notes.iter().any(|n| n.layer == "b"), "past the cap, a new note isn't kept"); - assert_eq!(r.notes.last().map(|n| (n.text.as_str(), n.count)), Some(("503 more note(s) not listed", 503))); + // "b"'s approximation joins the approximated closing note; the skipped one has its own. + let closing = |kind| r.notes.iter().rev().take(2).find(|n| n.kind == kind).map(|n| (n.text.clone(), n.count)); + assert_eq!(closing(NoteKind::Approximated), Some(("502 more note(s) not listed".to_string(), 502))); + assert_eq!(closing(NoteKind::Skipped), Some(("1 more note(s) not listed".to_string(), 1))); + assert_eq!(r.notes.len(), MAX_NOTES + 2); let mut few = Report::default(); few.skipped("a", "one"); assert!(!few.notes.iter().any(|n| n.text.contains("not listed")), "under the cap, nothing is counted apart"); From 8e2bb9289393b74d586d10ecda5490e325974469 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 01:24:47 -0500 Subject: [PATCH 6/7] Address Claude review feedback - network: a route left without a finite cost after a sum overflowed says both causes, overflow or not connected - QGIS: a file source's unread options past 32 are counted, not kept - route notices count lines as line(s) --- crates/analysis/src/network.rs | 21 +++++++++++++-------- crates/engine/src/cmd/workflows.rs | 2 +- crates/map/src/qgis/source.rs | 13 +++++++++++-- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 68e2154434..ff43859333 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -224,7 +224,7 @@ fn route_error(ds: &Dataset, reason: String, skipped_segments: usize, overflowin } if overflowing > 0 { said.push_str(&format!( - "; {overflowing} lines of '{}' cost so much that a segment's cost is past the largest number, and were closed", + "; {overflowing} line(s) of '{}' cost so much that a segment's cost is past the largest number, and were closed", ds.name )); } @@ -464,14 +464,15 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) } } let cost = dist.get(t).copied().unwrap_or(f64::INFINITY); - if !cost.is_finite() && summed_past { - return Err(route_error( - "no route costs less than the largest number: the costs along the network add up past it (give the lines smaller costs)".into(), - skipped_segments, - )); - } if !cost.is_finite() { - return Err(route_error("the two points aren't connected by the network".into(), skipped_segments)); + // A sum past the largest number seen anywhere in the search may or may not be on the + // way to the target: both are said. + let why = if summed_past { + "the two points aren't joined by a route whose costs stay within the largest number: the costs along the network add up past it, or they aren't connected (give the lines smaller costs)" + } else { + "the two points aren't connected by the network" + }; + return Err(route_error(why.into(), skipped_segments)); } let mut path = Vec::new(); let mut length = 0.0; @@ -1589,6 +1590,10 @@ mod tests { summed.push(Some(Geometry::Line(vec![two])), vec![Value::Float(1e308)]); let e = shortest_route(&summed, &[0], Coord::new(0.0, 0.0), Coord::new(0.00002, 0.0), Some(0), 1000.0).unwrap_err(); assert!(e.contains("add up past it"), "{e}"); + // The same beside a target on a line of its own: either may be why, so both are said. + summed.push(Some(Geometry::Line(vec![vec![Coord::new(1.0, 1.0), Coord::new(1.001, 1.0)]])), vec![Value::Float(1.0)]); + let e = shortest_route(&summed, &[0, 1], Coord::new(0.0, 0.0), Coord::new(1.001, 1.0), Some(0), 1000.0).unwrap_err(); + assert!(e.contains("add up past it, or they aren't connected"), "{e}"); assert!(shortest_route(&ds, &rows, Coord::new(5.0, 5.0), Coord::new(1.0, 1.0), None, 1000.0).is_err()); let mut poly = Dataset::new("p", GeometryType::Polygon, vec![]); poly.push( diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 7e5e266d83..46a57ecbaf 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1781,7 +1781,7 @@ fn route(s: &mut Session, p: &Value) -> CmdResult { if r.overflowing > 0 { s.notify( format!( - "{source_name}: {} lines cost so much that a segment's cost is past the largest number, and were closed in the route network", + "{source_name}: {} line(s) cost so much that a segment's cost is past the largest number, and were closed in the route network", r.overflowing ), false, diff --git a/crates/map/src/qgis/source.rs b/crates/map/src/qgis/source.rs index 2a1aeed189..6cdea893db 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -516,6 +516,9 @@ fn file(datasource: &str, dir: &str) -> Source { let (mut layer, mut subset, mut ignored) = (None, None, Vec::new()); // Every part is read for the layer and the filter; at most 32 others are named in the note, // the rest counted. + // Only the named ones are kept (a project file is hostile input: the rest are only counted), + // the `layerid=` ones among the counted apart. + let (mut more, mut more_ids) = (0usize, 0usize); for p in parts { if let Some(v) = p.strip_prefix("layername=") { layer = Some(v.to_string()); @@ -523,14 +526,20 @@ fn file(datasource: &str, dir: &str) -> Source { subset = Some(v.to_string()).filter(|s| !s.trim().is_empty()); } else if !p.trim().is_empty() && p.trim() != "layerid=0" { // (layerid=0 is the first layer, which is what opens.) - ignored.push(noted_option(p.trim())); + if ignored.len() < 32 { + ignored.push(noted_option(p.trim())); + } else { + more += 1; + more_ids += usize::from(p.trim().starts_with("layerid=")); + } } } // A layer named as well as numbered: the name is what's read. if layer.is_some() { ignored.retain(|o: &String| !o.starts_with("layerid=")); + more = more.saturating_sub(more_ids); } - Source::File { path: absolute(path, dir), layer, subset, ignored: named_options(ignored.into_iter(), 0) } + Source::File { path: absolute(path, dir), layer, subset, ignored: named_options(ignored.into_iter(), more) } } /// At most 32 of a file source's unread `options`, as its note names them, and the rest, with From 5d05aad755fb298e66a60a998f8f52be310fe5fa Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 22 Nov 2026 03:46:36 -0500 Subject: [PATCH 7/7] Address review feedback - QGIS: each kind's closing note is tracked by position and kept in step when a note is withdrawn, so a kind never gets a second one - render: clearer BAR_LABEL_PT / BAR_INSET doc --- crates/map/src/qgis/mod.rs | 38 ++++++++++++++++++++++++------------ crates/map/src/qgis/tests.rs | 11 +++++++++++ crates/render/src/layout.rs | 4 ++-- 3 files changed, 38 insertions(+), 15 deletions(-) diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index ab03327ec0..954983afad 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -60,6 +60,9 @@ pub struct Report { /// approximated, then skipped. #[serde(skip)] more: [usize; 2], + /// Where each kind's closing note is in `notes`, kept in step by [`Report::forget`]. + #[serde(skip)] + closing: [Option; 2], /// Raster image markers' images by their `imageFile`, read before the symbols showing them /// (`symbol::read_images`): each kept picture with its height over its width, or why it isn't /// drawn. Carried here because every symbol reader already takes the report; passing them @@ -105,24 +108,24 @@ impl Report { let (layer, kind, text) = key; self.notes.push(Note { layer, kind, text, count: 1 }); } else { - // Past the cap, a new note is counted in a closing note of its kind, never listed - // itself. The closing notes are the last two at most: nothing else is added after them. + // Past the cap, a new note is counted in the one closing note of its kind, never + // listed itself. let (_, kind, _) = key; let k = usize::from(kind == NoteKind::Skipped); let more = self.more.get(k).copied().unwrap_or(0).saturating_add(1); let text = format!("{more} more note(s) not listed"); - let closing = self - .notes - .iter_mut() - .rev() - .take(2) - .find(|n| n.kind == kind && n.layer.is_empty() && more > 1 && n.text.ends_with(" more note(s) not listed")); - match closing { - Some(last) => { - last.text = text; - last.count = last.count.saturating_add(1); + let at = self.closing.get(k).copied().flatten(); + match at.and_then(|i| self.notes.get_mut(i)) { + Some(closing) => { + closing.text = text; + closing.count = closing.count.saturating_add(1); + } + None => { + self.notes.push(Note { layer: String::new(), kind, text, count: 1 }); + if let Some(c) = self.closing.get_mut(k) { + *c = Some(self.notes.len() - 1); + } } - None => self.notes.push(Note { layer: String::new(), kind, text, count: 1 }), } if let Some(m) = self.more.get_mut(k) { *m = more; @@ -156,6 +159,15 @@ impl Report { } self.notes.retain(|n| n.layer != layer || n.kind != kind || n.text != text); self.index = self.notes.iter().enumerate().map(|(i, n)| ((n.layer.clone(), n.kind, n.text.clone()), i)).collect(); + // The closing notes moved up with the rest. + for (k, kind) in [NoteKind::Approximated, NoteKind::Skipped].into_iter().enumerate() { + let more = self.more.get(k).copied().unwrap_or(0); + let text = format!("{more} more note(s) not listed"); + let at = self.notes.iter().rposition(|n| n.kind == kind && n.layer.is_empty() && n.text == text); + if let Some(c) = self.closing.get_mut(k) { + *c = at.filter(|_| more > 0); + } + } } } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index ed228c6490..b60cc0ef85 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -292,6 +292,17 @@ fn hostile_files_are_refused_or_bounded() { assert_eq!(closing(NoteKind::Approximated), Some(("502 more note(s) not listed".to_string(), 502))); assert_eq!(closing(NoteKind::Skipped), Some(("1 more note(s) not listed".to_string(), 1))); assert_eq!(r.notes.len(), MAX_NOTES + 2); + // A note withdrawn below the cap moves the closing notes up; a later overflow still finds its + // kind's one closing note. + for i in 9..12 { + r.forget("a", NoteKind::Approximated, &format!("note {i}")); + } + r.approximated("a", "fresh below the cap"); + r.approximated("a", "past the cap again"); + let closers = r.notes.iter().filter(|n| n.text.ends_with(" more note(s) not listed")).count(); + assert_eq!(closers, 2, "one closing note a kind"); + let approximated = r.notes.iter().find(|n| n.kind == NoteKind::Approximated && n.text.ends_with(" more note(s) not listed")); + assert_eq!(approximated.map(|n| (n.text.as_str(), n.count)), Some(("503 more note(s) not listed", 503))); let mut few = Report::default(); few.skipped("a", "one"); assert!(!few.notes.iter().any(|n| n.text.contains("not listed")), "under the cap, nothing is counted apart"); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 70289431d9..8591a2770b 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2101,8 +2101,8 @@ fn scale_number(v: f64, step: f64) -> String { /// The share of its element's width a scale bar's length may take. const BAR_SHARE: f64 = 0.85; /// A scale bar's labels' size, in points, and how far its bar starts in from the element's left -/// edge, in pixels. [`scale_bar_width_pt`] measures the labels at that size and counts the inset as -/// that many points, never less than the bar is drawn in by when a point is a pixel or more. +/// edge, in pixels. [`scale_bar_width_pt`] counts that inset as as many points: when a point is a +/// pixel or more, a pixel is no larger than a point, so the box is never too narrow. const BAR_LABEL_PT: f32 = 8.0; const BAR_INSET: f32 = 2.0;