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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 29 additions & 10 deletions apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1190,16 +1190,7 @@ fn cli() -> ExitCode {
Ok(())
}
"explain" => {
// The common options (`--threads 2`, `--use-saved-secrets`) are taken, and their values.
let mut words = Vec::new();
let mut rest = args.iter().skip(1);
while let Some(arg) = rest.next() {
if VALUE_FLAGS.contains(&arg.as_str()) {
rest.next();
} else if !arg.starts_with("--") {
words.push(arg.as_str());
}
}
let words = explain_words(&args)?;
match words.as_slice() {
[] => explain(None),
[code] => explain(Some(code)),
Expand Down Expand Up @@ -1345,10 +1336,38 @@ fn cli() -> ExitCode {
}
}

/// The words `explain` is given (`args` from the subcommand on): the common options
/// (`--threads 2`, `--threads=2`, `--use-saved-secrets`, `--no-plugins`) are taken, and their
/// values; any other option is refused, so a typo isn't passed over without a word.
fn explain_words(args: &[String]) -> Result<Vec<&str>, String> {
const COMMON: &[&str] = &["--use-saved-secrets", "--no-plugins"];
Comment thread
giswqs marked this conversation as resolved.
Resolved
let mut words = Vec::new();
let mut rest = args.iter().skip(1);
while let Some(arg) = rest.next() {
let joined = arg.split_once('=').is_some_and(|(flag, _)| VALUE_FLAGS.contains(&flag));
if VALUE_FLAGS.contains(&arg.as_str()) {
rest.next();
} else if !arg.starts_with("--") {
words.push(arg.as_str());
} else if !joined && !COMMON.contains(&arg.as_str()) {
return Err(format!("explain: unknown option {arg}"));
}
}
Ok(words)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn explain_refuses_an_unknown_option_and_takes_the_common_ones() {
let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(explain_words(&args(&["explain", "--strcit", "dropped.value"])), Err("explain: unknown option --strcit".into()));
assert_eq!(explain_words(&args(&["explain", "--threads", "2", "dropped.value"])), Ok(vec!["dropped.value"]));
assert_eq!(explain_words(&args(&["explain", "--threads=2", "--use-saved-secrets", "--no-plugins"])), Ok(vec![]));
}

#[test]
fn ask_takes_up_to_four_pictures_and_says_what_it_refuses() {
// A 1 × 1 PNG.
Expand Down
2 changes: 1 addition & 1 deletion crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17571,7 +17571,7 @@ mod tests {
assert!(!one.messages.iter().any(|m| m.contains("uses the raster projection")));
assert!(said(&one).iter().any(|m| m == "2 zone feature(s) had no polygon with an area and were excluded"), "{:?}", said(&one));
assert!(
said(&one).iter().any(|m| m == "DroppedGeometry: 1 zone feature(s) had invalid polygon geometry and were excluded"),
said(&one).iter().any(|m| m == "DroppedFeature: 1 zone feature(s) had invalid polygon geometry and were excluded"),
"{:?}",
said(&one)
);
Expand Down
3 changes: 2 additions & 1 deletion crates/analysis/src/tools/tabulate_area.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,9 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Resu
}
let mut losses = Vec::new();
if unreadable > 0 {
// A whole feature left out, coded as the clip codes the same loss.
losses.push(LossMessage {
code: LossCode::DroppedGeometry,
code: LossCode::DroppedFeature,
text: format!("{unreadable} zone feature(s) had invalid polygon geometry and were excluded"),
});
}
Expand Down
2 changes: 1 addition & 1 deletion crates/data/src/loss.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ loss_codes! {
"dropped.calculation-result",
Dropped,
"A calculation gave no result for some rows, so the field was left empty there. The input may have no place that can be given in longitude and latitude, or the result may be too large to hold.",
"Correct the expression or check the input rows named in the notice."
"Check the rows the notice names (or its expression, for a calculated field)."
),
DroppedZm => (
"dropped.zm",
Expand Down
47 changes: 44 additions & 3 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1350,18 +1350,34 @@ impl Raster {
if wrapped < w { wrapped } else { c }
}

/// The width in columns of a geographic grid spanning exactly one turn of 360°, whose columns
/// go round (its last is next to its first); `None` for any other grid. Its span is compared,
/// rather than truncating `360 / pixel_width`: a regional grid can end partway through that
/// column. The map's relief and [`Raster::bilinear`] both read across the seam by it.
pub fn full_turn_width(&self) -> Option<i64> {
let span = f64::from(self.width) * self.transform.pixel_width.abs();
(self.transformer.is_geographic() && (span - 360.0).abs() <= 360.0 * 16.0 * f64::EPSILON).then_some(i64::from(self.width))
}

/// The value of `band` at a longitude/latitude point, read bilinearly between the four cell
/// centres around it, in the raster's own system: the nearest cell's where one of the four is
/// no-data or off the grid, and `None` where that one is too. A grid stored from 0 to 360° is
/// read at a western longitude in its columns past 180° ([`Raster::wrap_col`]). The elevation profiles read
/// this (`profile.*`, and a layout's profiles beside a map frame, #2863).
/// read at a western longitude in its columns past 180° ([`Raster::wrap_col`]); a geographic
/// grid spanning exactly one turn is read across its seam, between its last column and its
/// first, as the map draws it. The elevation profiles read this (`profile.*`, and a layout's
/// profiles beside a map frame, #2863).
pub fn bilinear(&self, band: usize, lonlat: Coord) -> Option<f64> {
let w = self.transformer.from_lonlat(lonlat)?;
let (x, y) = self.transform.to_pixel(w);
let (x, y) = (self.wrap_col(x) - 0.5, y - 0.5);
let (c0, r0) = (x.floor() as i64, y.floor() as i64);
let (fx, fy) = (x - c0 as f64, y - r0 as f64);
let v = |c: i64, r: i64| self.value(band, c, r).map(f64::from);
// One turn wide: its columns go round.
let turn = self.full_turn_width();
let v = |c: i64, r: i64| {
let c = turn.map_or(c, |w| if c < 0 || c >= w { c.rem_euclid(w) } else { c });
self.value(band, c, r).map(f64::from)
};
match (v(c0, r0), v(c0 + 1, r0), v(c0, r0 + 1), v(c0 + 1, r0 + 1)) {
(Some(a), Some(b), Some(c), Some(d)) => {
Some(a * (1.0 - fx) * (1.0 - fy) + b * fx * (1.0 - fy) + c * (1.0 - fx) * fy + d * fx * fy)
Expand Down Expand Up @@ -2810,6 +2826,31 @@ pub(crate) mod tests {
assert!(at(-100.1).is_some_and(|v| (v - 519.8).abs() < 1e-6), "259.9°: {:?}", at(-100.1));
}

/// A grid one turn wide is read across its seam: between its last column's centre and 360°
/// (or its first column's centre and 0°), the blend of its last and first columns, not the
/// nearest cell's value.
#[test]
fn a_grid_one_turn_wide_is_read_bilinearly_across_its_seam() {
let gt = GeoTransform { origin_x: 0.0, origin_y: 90.0, pixel_width: 90.0, pixel_height: -90.0 };
let row = [10.0, 20.0, 30.0, 40.0];
let data = row.iter().chain(&row).copied().collect();
let r = Raster::new("g", 4, 2, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap();
let at = |lon: f64| r.bilinear(0, Coord::new(lon, 0.0));
// A quarter of a cell past the last column's centre (315°), and a quarter short of the
// first's (45°).
for (lon, blend) in [(-22.5, 32.5), (337.5, 32.5), (22.5, 17.5)] {
assert!(at(lon).is_some_and(|v| (v - blend).abs() < 1e-9), "{lon}: {:?}", at(lon));
}
// Inside, as before.
assert!(at(90.0).is_some_and(|v| (v - 15.0).abs() < 1e-9), "{:?}", at(90.0));
// A grid short of a turn keeps the nearest cell there.
let gt = GeoTransform { pixel_width: 80.0, ..gt };
let short =
Raster::new("s", 4, 2, vec![row.iter().chain(&row).copied().collect()], gt, Crs::LonLat, None, ColorHint::Gray, "Float32")
.unwrap();
assert_eq!(short.bilinear(0, Coord::new(5.0, 0.0)), Some(10.0));
}

#[test]
fn geographic_extent_uses_greenwich_not_the_native_prime_meridian() {
let crs = Crs::parse("+proj=longlat +datum=WGS84 +pm=paris +no_defs").unwrap();
Expand Down
21 changes: 21 additions & 0 deletions crates/data/src/source/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,14 @@ pub fn forget_file(url: &str) {
files().lock().unwrap_or_else(|e| e.into_inner()).retain(|r| r.url != url);
}

/// Forgets the fetched parts of every file of `urls`, going through the files once for them all.
pub fn forget_files(urls: &std::collections::HashSet<String>) {
if urls.is_empty() {
return;
}
files().lock().unwrap_or_else(|e| e.into_inner()).retain(|r| !urls.contains(&r.url));
}

/// The error a read that needs bytes gives (it runs again once they are fetched).
pub fn need() -> DataError {
DataError::Format(NEED.into())
Expand Down Expand Up @@ -1004,6 +1012,19 @@ pub(crate) mod testing {
mod tests {
use super::*;

/// Forgetting files together drops each of them and keeps the others.
#[test]
fn forgetting_files_together_drops_each_and_keeps_the_rest() {
let urls = ["https://forget-files.test/a.fgb", "https://forget-files.test/b.fgb", "https://forget-files.test/c.fgb"];
for url in urls {
file(url);
}
forget_files(&std::collections::HashSet::from([urls[0].to_string(), urls[1].to_string()]));
let held: Vec<String> = files().lock().unwrap().iter().map(|r| r.url.clone()).filter(|u| u.contains("forget-files.test")).collect();
assert_eq!(held, [urls[2]]);
forget_file(urls[2]);
}

#[test]
fn held_ranges_and_late_publications_are_revoked() {
crate::login_address::set_validator(testing::validate_login);
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/catalogs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{CmdResult, CommandSpec as C, Session};
pub fn commands() -> Vec<C> {
vec![
C::new("overture.add", "Add Overture Maps Data", "Home › Add › Web Data", overture_add).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params(
r#"{"theme": "buildings"|"places"|"transportation"|"divisions"|"base"|"addresses", "type"?: "the theme's type (building, building_part; place; segment, connector; division_area, division, division_boundary; land_use, land, land_cover, water, infrastructure, bathymetry; address)", "release"?: "such as 2026-09-23.1 (default: the latest)", "bbox"?: [west, south, east, north] | "view" (the map's extent, the default), "tiles"?: bool (the whole world as map tiles, from the theme's PMTiles archive, instead of the features in view), "files"?: [the files' GeoParquet addresses, when already found and opened (the app's background requests)]} (in a plugin's command in the app the files are left to download: it answers pending, with the layers already in, and the command runs again once they are added; see docs/plugins.md)"#,
r#"{"theme": "buildings"|"places"|"transportation"|"divisions"|"base"|"addresses", "type"?: "the theme's type (building, building_part; place; segment, connector; division_area, division, division_boundary; land_use, land, land_cover, water, infrastructure, bathymetry; address)", "release"?: "such as 2026-09-23.1 (default: the latest)", "bbox"?: [west, south, east, north] | "view" (the map's extent, the default), "tiles"?: bool (the whole world as map tiles, from the theme's PMTiles archive, instead of the features in view), "files"?: [the files' GeoParquet addresses, when already found and opened (the app's background requests)]}"#,
),
C::new("sourcecoop.products", "List Source Cooperative Products", "Home › Add › Web Data", sourcecoop_products).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network))
.view()
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ fn paste(s: &mut Session, p: &Value) -> CmdResult {
let mut keep = placed.into_iter();
src.features.retain_rows(|_| keep.next().unwrap_or(true));
if src.features.is_empty() {
return Err(format!("Paste: the copied feature(s) have a place {} ({}) can't hold", l.name, own.label()));
return Err(format!("Paste: the copied feature(s) have a place that layer {} ({}) can't hold", l.name, own.label()));
}
}
// Ids for every feature the layer takes (one of another shape is left out below), above every id
Expand Down
12 changes: 6 additions & 6 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3161,6 +3161,12 @@ pub(crate) fn topology_ahead(s: &Session, p: &Json) -> Option<super::reads::Read
}))
}

/// One issue as `topology.validate` answers it. `located` is false for an issue at a place that
/// can't be given in longitude/latitude, whose `lon` and `lat` are then null.
fn issue_json(e: &crate::TopologyIssue) -> Json {
json!({"rule": e.rule, "layer": e.layer, "rows": e.rows, "lon": e.lon, "lat": e.lat, "located": e.lon.is_finite() && e.lat.is_finite()})
}

/// Checks every topology rule; the errors are kept for the Error Inspector. The work grows with
/// the layers, so the desktop app checks them on a thread of its own first ([`topology_ahead`]),
/// with the status bar's progress and **Cancel**, and the command takes that check as it lands;
Expand All @@ -3169,12 +3175,6 @@ pub(crate) fn topology_ahead(s: &Session, p: &Json) -> Option<super::reads::Read
/// command line call commands one at a time on the session and use each answer before the next,
/// so they check where they ask, with the work limit of a run that can't be cancelled. A registered
/// window owner refuses an unprepared nonempty check instead of computing it inline.
/// One issue as `topology.validate` answers it. `located` is false for an issue at a place that
/// can't be given in longitude/latitude, whose `lon` and `lat` are then null.
fn issue_json(e: &crate::TopologyIssue) -> Json {
json!({"rule": e.rule, "layer": e.layer, "rows": e.rows, "lon": e.lon, "lat": e.lat, "located": e.lon.is_finite() && e.lat.is_finite()})
}

fn topology_validate(s: &mut Session, p: &Json) -> CmdResult {
let tol = topology_tolerance(p);
let inputs = topology_checks(s);
Expand Down
5 changes: 2 additions & 3 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,16 +846,15 @@ fn convert(v: Value, ty: FieldType) -> (Value, Cut, Option<f64>) {
Ok(i) => (Value::Int(i), Cut::None, None),
Err(_) => match (decimal_text(t.trim()), t.trim().parse::<f64>()) {
(Some((v, cut)), Ok(f)) => (v, cut, Some(f)),
// A word the decimal reader takes ("inf", "NaN") isn't a number written as text:
// null, and said so, as not a number.
// A fraction the decimal rounded away (`2.0000000000000000001e0`) is still one.
// A fraction the decimal rounded away (`2.0000000000000000001e0`) is still one, and
// digits past those it holds (`9007199254740993e0`) are rounded.
(None, Ok(f)) if f.is_finite() || t.bytes().any(|b| b.is_ascii_digit()) => match whole(f) {
(v @ Value::Int(_), Cut::None, x) if Value::text_has_fraction(&t) => (v, Cut::Fraction, x),
(v @ Value::Int(_), Cut::None, x) if !rustgis_data::io::double_holds(t.trim()) => (v, Cut::Rounded, x),
held => held,
},
// A word the decimal reader takes ("inf", "NaN") isn't a number written as text:
// null, and said so, as not a number.
(None, Ok(f)) if f.is_infinite() => (Value::Null, Cut::NotFinite, None),
(None, Ok(_)) => (Value::Null, Cut::NotANumber, None),
_ => (Value::parse(&t, ty), Cut::None, None),
Expand Down
21 changes: 11 additions & 10 deletions crates/engine/src/cmd/exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,13 @@ const CJK_PENDING: &str = "CJK font folder scan is still running; try exporting
/// What is said of an export during which that scan started.
const CJK_STARTED: &str = "CJK font folder scan started during this export; re-run it once the scan finishes if CJK text is missing.";

/// `build`'s result, and whether a CJK font folder scan started while it ran: watched only for a
/// `command` that draws with installed fonts ([`uses_fonts`]). The caller says [`CJK_STARTED`]
/// when one did.
fn built_with_fonts<T>(command: &str, build: impl FnOnce() -> T) -> (T, bool) {
if uses_fonts(command) { rustgis_render::fonts::track_pending_cjk(build) } else { (build(), false) }
}

#[cfg(test)]
thread_local! {
static TEST_CJK_SCAN_PENDING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
Expand Down Expand Up @@ -421,12 +428,8 @@ pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult
let control = if s.stoppable { rustgis_analysis::control::Control::stoppable() } else { rustgis_analysis::control::Control::new() };
let (mut wrote, pending_cjk) = crate::render::rustgis_tiles::cache::with_still(still, || {
let work = start(s, &p)?;
if uses_fonts(command) {
let (res, hit) = rustgis_render::fonts::track_pending_cjk(|| written_under(name, &control, work));
Ok::<_, String>((res?, hit))
} else {
Ok((written_under(name, &control, work)?, false))
}
let (res, hit) = built_with_fonts(command, || written_under(name, &control, work));
Ok::<_, String>((res?, hit))
})?;
if pending_cjk {
wrote.diagnostics.push((rustgis_data::diagnostics::Severity::Warning, CJK_STARTED.into()));
Expand Down Expand Up @@ -484,8 +487,7 @@ pub(crate) fn file_command(
let mark = s.notice_mark();
let path = super::ps(p, "path").ok_or("path is required")?;
let out = Output { path, room: None };
let (made, pending_cjk) =
if uses_fonts(command) { rustgis_render::fonts::track_pending_cjk(|| build(s, out)) } else { (build(s, out), false) };
let (made, pending_cjk) = built_with_fonts(command, || build(s, out));
let made = made?;
rustgis_data::io::write_atomic(std::path::Path::new(path), &made.bytes).map_err(|e| format!("{path}: {e}"))?;
for note in made.notes {
Expand Down Expand Up @@ -523,8 +525,7 @@ pub(crate) fn download_command(
let out = Output { path: &name, room: s.download_room()? };
// What making the file says waits with it.
let (made, held) = s.holding_notices(|s| {
let (made, pending_cjk) =
if uses_fonts(command) { rustgis_render::fonts::track_pending_cjk(|| build(s, out)) } else { (build(s, out), false) };
let (made, pending_cjk) = built_with_fonts(command, || build(s, out));
let mut made = made?;
for note in std::mem::take(&mut made.notes) {
s.say(note);
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/gp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2265,7 +2265,7 @@ fn inputs_in(
// Counted over each whole layer, before the run's rows are narrowed to a selection: some may
// be rows the tool doesn't read, so it isn't a coded loss.
said.push(rustgis_data::loss::Note::plain(format!(
"{name}: {n} feature(s) of {layers} have a place that can't be given in longitude/latitude, so the tool reads them without their geometry"
"{name}: {n} feature(s) of {layers} have a place that can't be given in longitude/latitude, so any of them the tool reads have no geometry"
)));
}
if !bent.is_empty() {
Expand Down
Loading
Loading