diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 092f2d2a29..4acf725637 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -16,7 +16,8 @@ of use. | File | Author / source | Licence | |---|---|---| | Interface themes (`crates/ui-egui/themes/light.json`, `dark.json`) | The RustGIS project | Apache-2.0 | -| Sample data (`countries`, `countries_chn`, `cities`, `rivers`, `lakes` GeoJSON), embedded at build time from [rustgis-assets](https://github.com/opengeos/rustgis-assets/tree/main/data) | Natural Earth 1:110m, attributes trimmed; `countries_chn` is Natural Earth's China point of view (1:10m, simplified) | Public domain | +| Sample data (`countries`, `cities`, `rivers`, `lakes` GeoJSON), embedded at build time from [rustgis-assets](https://github.com/opengeos/rustgis-assets/tree/main/data) | Natural Earth 1:110m, attributes trimmed | Public domain | +| Worldviews (`countries_.geojson` and `original/countries_.geojson.gz` on [source.coop](https://source.coop/opengeos/data/rustgis/worldviews)), downloaded by the app when one is chosen, not part of it | Natural Earth's Admin 0 Countries (1:10m) and its points of view, with the sample countries' attributes by `scripts/worldviews.py` in [rustgis-assets](https://github.com/opengeos/rustgis-assets): simplified to 1:110m density, or at their original detail | Public domain | | QGIS screenshot (`qgis-world-atlas.webp` in [rustgis-assets](https://github.com/opengeos/rustgis-assets/tree/main/images)), on the [RustGIS and QGIS](docs/comparison/qgis.md) page | Taken by the RustGIS project: [QGIS](https://qgis.org) 4.2 showing the Natural Earth sample data above | QGIS is GPL-2.0-or-later; the data is public domain | | QGIS test corpus (`crates/map/testdata/qgis/generated/`: styles, projects and their sample data) | Dominik Strebel ([@pick2510](https://github.com/pick2510)) for the RustGIS project: written by [QGIS](https://qgis.org) 4.2.3 through its API, from `generate.py` there; the data is made up | Apache-2.0 | | JAXA Earth catalog test copy (`crates/tiles/tests/data/jaxa_catalog.v2.md`), read only by tests | JAXA: the [JAXA Earth API](https://data.earth.jaxa.jp/) dataset catalog ([catalog.v2.md](https://data.earth.jaxa.jp/app/mcp/catalog.v2.md)), copied on 2026-11-08 | JAXA's [terms of use](https://earth.jaxa.jp/en/data/policy/): free to use and redistribute, with credit to JAXA | diff --git a/Cargo.lock b/Cargo.lock index 46229d6fb5..a3bf4c98dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4796,6 +4796,7 @@ dependencies = [ "iana-time-zone", "image", "log", + "miniz_oxide 0.9.1", "postgres", "rusqlite", "rustgis-analysis", diff --git a/README.md b/README.md index 7d8ee7a1ab..ed7863a94b 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ Every screenshot is RustGIS itself, rendered offscreen by `cargo run -p rustgis- | **Data** | GeoJSON, CSV/TSV with x/y columns in other coordinate systems or WKT geometry, Excel and OpenDocument spreadsheets, GeoRSS, LandXML, encoded polylines, Shapefile (zipped too, in the browser as well), GeoPackage, GeoParquet, FlatGeobuf, KML/KMZ (with styles), GPX, GML, MapInfo MIF/MID, OpenStreetMap PBF, TopoJSON, CityJSON, AutoCAD DXF, LiDAR point clouds (LAS, LAZ, COPC) and geotagged photos (large GeoPackage, GeoParquet and FlatGeobuf files, and Shapefiles on the desktop, are read in place), files by their web address, every vector format GDAL reads when it is installed (desktop), Esri File Geodatabases without GDAL (desktop), PostGIS, MySQL, MariaDB and SQL Server tables read live (desktop), and SQL queries and DuckDB databases through DuckDB Spatial when DuckDB is installed (desktop); PMTiles archives (by web address, or a file on the desktop) and MBTiles files; GeoJSON, CSV, GeoPackage (also as a table added to an existing file), GeoParquet, Shapefile, FlatGeobuf, KML/KMZ, GPX and WKT out (GeoPackage and FlatGeobuf not from the web app); standalone tables; reusable connections; Reload Data for linked files (desktop); geocoding (Find Place, address tables); a Data Sources pane (favourites, recent, saved services, a library) and an SQL pane (desktop); supported QGIS and GeoLibre projects and layer styles; layer and map files, styles, templates and packages | | **Open data** | STAC search (Planetary Computer assets), NASA Earthdata imagery and granule search (GeoTIFFs added on the desktop), Hugging Face, Overture Maps, Source Cooperative, OpenStreetMap by area, geoBoundaries, CKAN, Socrata and ArcGIS Hub portals; S3 buckets with signed connections and a bucket browser; a Data Cubes pane with a catalog of cubes for the time slider (added on the desktop) | | **Rasters** | GeoTIFF and cloud-optimised GeoTIFF (any pixel type, tiled or striped, compressed), ASCII grids, Zarr 2 and 3 stores (a variable at a time step, by web address, or folder on the desktop), and JPEG 2000, NetCDF, HDF, ERDAS Imagine and the other rasters GDAL reads when it is installed (desktop); reprojection by EPSG code; Stretch, RGB, Classify, Unique Values, Colormap and Shaded Relief; DRA, band combinations, brightness/contrast/gamma; raster functions, indices, change detection, classification, georeferencing; cloud-optimised GeoTIFF export (desktop); data cubes, point time-series charts (desktop), temporal summaries and trends (Sen's slope, Mann–Kendall); a spectral profile comparing a multiband raster's bands at points | -| **Maps** | Multiple maps and layouts per project, renamed and duplicated from the Browser pane; a GPU renderer (beta) with smooth zoom and pan; tilt, rotation, terrain and a 3D globe; maps of the Moon, Mars and other celestial bodies; Web Mercator or another projection (Equal Earth, Robinson, Winkel Tripel, polar and regional presets, or a [supported](docs/user-guide/maps.md#projections) projected EPSG or ESRI code); a search box for layers, places and coordinates; UTM and MGRS readouts; an on-map right-click menu (copy the coordinate, quick buffer, viewshed and line of sight); identify pop-ups with links and pictures; bookmarks, extent history, coordinate navigation; five offline basemaps, with borders in two worldviews | +| **Maps** | Multiple maps and layouts per project, renamed and duplicated from the Browser pane; a GPU renderer (beta) with smooth zoom and pan; tilt, rotation, terrain and a 3D globe; maps of the Moon, Mars and other celestial bodies; Web Mercator or another projection (Equal Earth, Robinson, Winkel Tripel, polar and regional presets, or a [supported](docs/user-guide/maps.md#projections) projected EPSG or ESRI code); a search box for layers, places and coordinates; UTM and MGRS readouts; an on-map right-click menu (copy the coordinate, quick buffer, viewshed and line of sight); identify pop-ups with links and pictures; bookmarks, extent history, coordinate navigation; five offline basemaps, with borders in 32 worldviews (31 downloaded when chosen) | | **Web services** | WMS, WMTS, WFS, WCS, OGC API Features and Tiles, and ArcGIS REST (FeatureServer, MapServer, ImageServer, VectorTileServer) from their capabilities; CSW catalogue search; sign-in to ArcGIS Online and Enterprise, basic-auth and API-key logins; WMS and WMTS time on the time slider, legends and GetFeatureInfo | | **Web tiles** | XYZ/TMS/WMS raster tiles, Mapbox Vector Tiles and MapLibre styles (sprites, patterns, expressions), cached and fetched in the background | | **Cartography** | Single symbol, unique values (also by expression), graduated colours with seven classification methods and manual breaks, proportional symbols, pie and bar diagrams; symbol size, colour, width and angle, and label text, size, colour and angle, by expression; label classes with SQL queries, straight and curved line placement, installed font families (desktop), scale ranges and annotation; stacked and dashed line strokes, hatch, marker, gradient and shapeburst fills, custom colour ramps and the matplotlib colour maps, symbol levels, reference scales and polygons without fill; masking, display filters, aggregation bins, 2.5D extrusion; graphics and dynamic text | diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index 21bc345fbe..1cda664674 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -47,7 +47,7 @@ use serde_json::{Map, Value, json}; fn usage() -> ExitCode { eprintln!( - "usage:\n rustgis-cli commands | tools\n rustgis-cli plugins [install | uninstall | enable | disable | browse | get | prepare ] [--registry URL]\n rustgis-cli skills [add | remove | enable | disable ]\n rustgis-cli info \n rustgis-cli logo [--size N] [--canvas WxH --at X,Y (.bmp only)]\n rustgis-cli render [--basemap NAME] [--tiles URL] [--width N] [--height N] [--dpi N] [--worldview auto|default|china]\n rustgis-cli run [--sample] [--project P] [--data F]… --cmd 'id={{json}}'… [--save P] [--worldview auto|default|china]\n rustgis-cli ask [--sample] [--project P] [--data F]… \"request\" [--provider P] [--model M] [--base-url URL] [--yes] [--save P]\n rustgis-cli ask --models [--provider P]\n rustgis-cli ask --login [--another-account] [--account CLIENT_ID] | --logout\n rustgis-cli ask --accounts | --account CLIENT_ID | --remove-account CLIENT_ID\n common options: --use-saved-secrets (use the connections, passwords, keys, ChatGPT sign-in and Earthdata Login token the RustGIS app saved; reads the system keychain), --threads N (the most threads one piece of work uses, 1-1024; default: the cores, up to 16)\n rustgis-cli mcp [--sample] [--project P] [--data F]… [--yes] [--attach [PORT] [--token-file FILE] [--timeout SECONDS (5-600)]]\n rustgis-cli mcp-register [--client claude] [--name NAME] [--port PORT]" + "usage:\n rustgis-cli commands | tools\n rustgis-cli plugins [install | uninstall | enable | disable | browse | get | prepare ] [--registry URL]\n rustgis-cli skills [add | remove | enable | disable ]\n rustgis-cli info \n rustgis-cli logo [--size N] [--canvas WxH --at X,Y (.bmp only)]\n rustgis-cli render [--basemap NAME] [--tiles URL] [--width N] [--height N] [--dpi N] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli run [--sample] [--project P] [--data F]… --cmd 'id={{json}}'… [--save P] [--worldview auto|default|CODE] [--worldview-detail simplified|original]\n rustgis-cli ask [--sample] [--project P] [--data F]… \"request\" [--provider P] [--model M] [--base-url URL] [--yes] [--save P]\n rustgis-cli ask --models [--provider P]\n rustgis-cli ask --login [--another-account] [--account CLIENT_ID] | --logout\n rustgis-cli ask --accounts | --account CLIENT_ID | --remove-account CLIENT_ID\n common options: --use-saved-secrets (use the connections, passwords, keys, ChatGPT sign-in and Earthdata Login token the RustGIS app saved; reads the system keychain), --threads N (the most threads one piece of work uses, 1-1024; default: the cores, up to 16)\n rustgis-cli mcp [--sample] [--project P] [--data F]… [--yes] [--attach [PORT] [--token-file FILE] [--timeout SECONDS (5-600)]]\n rustgis-cli mcp-register [--client claude] [--name NAME] [--port PORT]" ); ExitCode::from(2) } @@ -248,10 +248,8 @@ fn configuration(provider: &str, args: &[String], env: &Environment, saved: Opti const NEEDS_REQUEST: &str = "ask needs a request, e.g. rustgis-cli ask --sample \"Which countries have the largest GDP?\""; -/// `ask ""`: one conversation turn with the AI assistant, which acts on the project. -fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environment) -> Result<(), String> { - use rustgis_assistant::{Agent, Entry, agent, http}; - // The first value that isn't an option's. +/// The request `ask` is given: its first argument that is neither an option nor an option's value. +fn ask_request(args: &[String]) -> Option { let takes_value = [ "--provider", "--model", @@ -263,16 +261,23 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen "--plugin", "--registry", "--worldview", + "--worldview-detail", "--threads", "--account", "--remove-account", ]; - let prompt = args - .iter() + args.iter() .enumerate() .skip(1) .find(|(i, a)| !a.starts_with("--") && !args.get(i - 1).is_some_and(|p| takes_value.contains(&p.as_str()))) - .map(|(_, a)| a.clone()); + .map(|(_, a)| a.clone()) +} + +/// `ask ""`: one conversation turn with the AI assistant, which acts on the project. +fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environment) -> Result<(), String> { + use rustgis_assistant::{Agent, Entry, agent, http}; + // The first value that isn't an option's. + let prompt = ask_request(args); let provider = choose_provider(args, env, saved); if provider::preset(&provider).is_none() { let ids: Vec<&str> = provider::PRESETS.iter().map(|p| p.id).collect(); @@ -716,13 +721,47 @@ fn cli() -> ExitCode { } } } - // Whose borders the built-in countries and world outline show: the system's by default. + // Whose borders the built-in countries and world outline show: the system's by default, at + // the simplified detail unless `--worldview-detail original`. A view other than the built-in + // one is downloaded (once: it is kept in the cache folder) by the subcommands that draw or + // open maps. let worldview = opt(&args, "--worldview").unwrap_or("auto"); if worldview != "auto" && rustgis_engine::sample::Worldview::from_code(worldview).is_none() { - eprintln!("rustgis-cli: --worldview {worldview}: expected auto, default or china"); + eprintln!("rustgis-cli: --worldview {worldview}: expected auto, default or a worldview's code (such as chn, ind or usa)"); + return ExitCode::from(2); + } + let detail = opt(&args, "--worldview-detail").unwrap_or("simplified"); + if rustgis_engine::sample::Detail::from_code(detail).is_none() { + eprintln!("rustgis-cli: --worldview-detail {detail}: expected simplified or original"); return ExitCode::from(2); } - rustgis_engine::sample::apply_worldview(worldview); + let wanted = rustgis_engine::sample::wanted_view(worldview, detail); + // `mcp --attach` relays to the running app, which shows its own worldview; `ask`'s model, + // sign-in and account options draw nothing. + let attaching = cmd == "mcp" && args.iter().any(|a| a == "--attach"); + let ask_setup = cmd == "ask" + && (args.iter().any(|a| ["--models", "--login", "--logout", "--accounts", "--remove-account"].contains(&a.as_str())) + // Without a request, nothing is drawn by `--account`, nor unless a project is read or saved. + || (ask_request(&args).is_none() + && (args.iter().any(|a| a == "--account") + || !args.iter().any(|a| ["--sample", "--project", "--data", "--save"].contains(&a.as_str()))))); + if matches!(cmd, "render" | "run" | "ask" | "mcp") + && !attaching + && !ask_setup + && let Err(e) = rustgis_engine::sample::download_blocking(wanted) + { + // Asked for by name, it is needed; the system's choice falls back to the built-in borders. + if worldview != "auto" { + eprintln!("rustgis-cli: --worldview {worldview}: {e}"); + return ExitCode::FAILURE; + } + if opt(&args, "--worldview-detail").is_some() { + eprintln!("rustgis-cli: --worldview-detail {detail}: {e}"); + return ExitCode::FAILURE; + } + eprintln!("rustgis-cli: warning: {e}; the map shows the default borders"); + } + rustgis_engine::sample::apply_view(worldview, detail); // `--threads N` (or `--threads=N`): the most threads one piece of work uses (#1562), as // `gp.threads` sets it. let joined = args.iter().find_map(|a| a.strip_prefix("--threads=")); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 7ccb414d78..3ab32e521a 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -33,6 +33,7 @@ geolibre = ["dep:rustgis-geolibre"] testing = ["rustgis-plugins/testing"] [dev-dependencies] +miniz_oxide = { workspace = true } # Writing sample GeoPackages. rusqlite = { workspace = true } rustgis-plugins = { workspace = true, features = ["testing"] } diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 520a417f59..e51ce71e76 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -6,57 +6,224 @@ use rustgis_map::{Bookmark, Camera, ClassMethod, Marker, Ramp, Renderer, Rgba, S use crate::Project; -pub use rustgis_render::sample_data::{CITIES, COUNTRIES, COUNTRIES_CHN, LAKES, RIVERS, Worldview, countries, set_worldview, worldview}; +pub use rustgis_render::sample_data::{ + CITIES, COUNTRIES, Detail, LAKES, RIVERS, View, Worldview, countries, dataset, install, set_view, text, view, worldview, +}; -/// The worldview this system calls for: `RUSTGIS_WORLDVIEW` (`default` or `china`) when set, else -/// China when the system's time zone or first locale is mainland China's. Nothing is looked up -/// over the network. Test builds of the engine don't look at the system. +/// The worldview this system calls for: `RUSTGIS_WORLDVIEW` (a worldview's code, such as `ind`) +/// when set, else China when the system's time zone or first locale is mainland China's. Nothing +/// is looked up over the network. Test builds of the engine don't look at the system. pub fn system_worldview() -> Worldview { if let Some(w) = std::env::var("RUSTGIS_WORLDVIEW").ok().and_then(|v| Worldview::from_code(&v)) { return w; } if cfg!(test) { - return Worldview::Default; + return Worldview::DEFAULT; } let tz = iana_time_zone::get_timezone().ok(); let locales: Vec = sys_locale::get_locales().take(4).collect(); Worldview::detect(tz.as_deref(), locales.iter().map(String::as_str)) } -/// Applies a worldview preference: `auto` (or anything unknown) follows the system. -pub fn apply_worldview(pref: &str) -> Worldview { - let w = Worldview::from_code(pref).unwrap_or_else(system_worldview); - set_worldview(w); - w +/// The worldview a preference asks for: a worldview's code, or the system's for `auto` (or +/// anything unknown). +pub fn wanted_worldview(pref: &str) -> Worldview { + Worldview::from_code(pref).unwrap_or_else(system_worldview) +} + +/// The view the preferences ask for: the worldview's (see [`wanted_worldview`]) at the detail +/// `detail` names (`original` or `simplified`; anything else is the default, simplified). +pub fn wanted_view(pref: &str, detail: &str) -> View { + View::new(wanted_worldview(pref), Detail::from_code(detail).unwrap_or_default()) +} + +/// Applies the worldview preferences (see [`wanted_view`]) and returns the view asked for. It +/// shows only once its countries are in memory; until then the current one stays, and the caller +/// gets them ([`fetch`], [`download_blocking`]). Nothing is read from disk here. +pub fn apply_view(pref: &str, detail: &str) -> View { + let v = wanted_view(pref, detail); + if text(v).is_some() { + set_view(v); + } + v +} + +/// Whether downloaded worldviews are kept in the cache folder and read back from it (not in the +/// engine's own tests, which mustn't touch the computer's cache). +static KEEP: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(!cfg!(test)); + +/// Turns keeping downloaded worldviews in the cache folder on or off (off for tests). +pub fn keep_downloads(on: bool) { + KEEP.store(on, std::sync::atomic::Ordering::Relaxed); +} + +/// Where a downloaded view is kept: `worldviews/countries_.geojson` (simplified) or +/// `worldviews/original/countries_.geojson` in the cache folder (none in the browser). +fn kept_path(v: View) -> Option { + if v.built_in() || !KEEP.load(std::sync::atomic::Ordering::Relaxed) { + return None; + } + rustgis_data::dirs::cache_dir().map(|d| d.join("worldviews").join(v.file())) +} + +/// Reads a view kept from an earlier download into memory. A kept file that isn't usable (too +/// big, not text, not countries) is deleted, so it's downloaded again. +fn load_kept(v: View) -> bool { + let Some(path) = kept_path(v) else { return false }; + let Ok(meta) = std::fs::metadata(&path) else { return false }; + let usable = meta.len() <= v.max_bytes() as u64 + && std::fs::read(&path).ok().and_then(|b| String::from_utf8(b).ok()).is_some_and(|t| install(v, t).is_ok()); + if !usable { + log::warn!("{}: not a usable worldview, removed", path.display()); + let _ = std::fs::remove_file(&path); + } + usable +} + +/// Whether a view's countries are at hand: built in, in memory, or kept from an earlier download +/// (read now, so callers on the UI thread use [`fetch`] instead). +pub fn ready(v: View) -> bool { + text(v).is_some() || load_kept(v) +} + +/// Takes a view's downloaded countries: checks and keeps them for this run, and in the cache +/// folder for the next. Not keeping the file only costs a download next time, so it is logged. +pub fn accept(v: View, bytes: Vec) -> Result<(), String> { + let w = v.worldview; + // The original details are published gzipped; inflating stops at the size allowed. + let bytes = if bytes.starts_with(&[0x1f, 0x8b]) { + crate::render::rustgis_tiles::mvt::gunzip_within(&bytes, v.max_bytes()).map_err(|e| { + format!("the {} worldview's countries can't be unpacked ({e}): more than {} bytes, or damaged", w.name(), v.max_bytes()) + })? + } else { + bytes + }; + if bytes.len() > v.max_bytes() { + return Err(format!("the {} worldview's countries are {} bytes, more than the {} allowed", w.name(), bytes.len(), v.max_bytes())); + } + let text = String::from_utf8(bytes).map_err(|_| format!("the {} worldview's countries aren't UTF-8 text", w.name()))?; + install(v, text)?; + // Kept from the copy `install` keeps, not a second one. + if let (Some(path), Some(text)) = (kept_path(v), self::text(v)) { + let saved = + path.parent().map_or(Ok(()), std::fs::create_dir_all).and_then(|_| rustgis_data::io::write_atomic(&path, text.as_bytes())); + if let Err(e) = saved { + log::warn!("couldn't keep the {} worldview in {}: {e}", w.name(), path.display()); + } + } + Ok(()) +} + +/// How long a worldview's download may take (an original one is about 10 MB). +#[cfg(not(target_arch = "wasm32"))] +const DOWNLOAD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300); + +/// Gets a view's countries into memory and calls `done` with the outcome: natively on a thread of +/// its own, which reads the kept copy or downloads, checks the file and builds its world outline, +/// so an original (1:10m) view never holds the window; in the browser with its fetch, checking +/// the file when it lands. A download superseded by another choice isn't stopped: it is one +/// request of a fixed size, and what it brings is kept for the run, so choosing that worldview +/// again costs nothing. `done`'s error doesn't name the worldview; the caller's message does. +pub fn fetch(v: View, done: Box) + Send>) { + #[cfg(not(target_arch = "wasm32"))] + fetch_with(v, done, |url, max| crate::render::rustgis_tiles::cache::download_blocking_within(url, max, DOWNLOAD_TIMEOUT)); + #[cfg(target_arch = "wasm32")] + { + let Some(url) = v.url() else { + return done(Ok(())); + }; + crate::render::rustgis_tiles::cache::download_limited( + &url, + v.max_bytes(), + Box::new(move |r| done(r.and_then(|bytes| accept(v, bytes)))), + ); + } +} + +/// [`fetch`] natively, downloading with `download` (the address and the most bytes allowed). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn fetch_with( + v: View, + done: Box) + Send>, + download: impl FnOnce(&str, usize) -> Result, String> + Send + 'static, +) { + let Some(url) = v.url() else { + return done(Ok(())); + }; + { + let work = move || { + let r = if load_kept(v) { + Ok(()) + } else { + // The error alone: the app's notice names the worldview. + download(&url, v.max_bytes()).and_then(|bytes| accept(v, bytes)) + }; + if r.is_ok() { + rustgis_render::prepare_world(v); + } + r + }; + // A thread the system refuses costs the worldview, never the window's time. + let shared = std::sync::Arc::new(std::sync::Mutex::new(Some((work, done)))); + let mine = shared.clone(); + let spawned = std::thread::Builder::new().name("worldview".into()).spawn(move || { + if let Some((work, done)) = mine.lock().ok().and_then(|mut g| g.take()) { + // A panic (a parser on hostile bytes) is the download's error, not a silent stall. + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)) + .unwrap_or_else(|_| Err("the download stopped unexpectedly".to_string())); + done(r); + } + }); + if spawned.is_err() + && let Some((_, done)) = shared.lock().ok().and_then(|mut g| g.take()) + { + done(Err("couldn't start a thread".to_string())); + } + } +} + +/// Makes a view's countries ready, downloading them and waiting if they aren't at hand (the +/// command line's `--worldview`). +#[cfg(not(target_arch = "wasm32"))] +pub fn download_blocking(v: View) -> Result<(), String> { + if ready(v) { + return Ok(()); + } + let url = v.url().ok_or("the default worldview is built in")?; + let bytes = crate::render::rustgis_tiles::cache::download_blocking_within(&url, v.max_bytes(), DOWNLOAD_TIMEOUT) + .map_err(|e| format!("couldn't download the {} worldview: {e}", v.worldview.name()))?; + accept(v, bytes) } fn cam(lon: f64, lat: f64, res: f64) -> Camera { Camera { center: lonlat_to_merc(Coord::new(lon, lat)), res, bearing: 0.0, pitch: 0.0 } } -/// The built-in countries in a worldview. -fn countries_in(w: Worldview) -> &'static str { - match w { - Worldview::Default => COUNTRIES, - Worldview::China => COUNTRIES_CHN, - } +/// Whether the project has a layer named `Countries` holding exactly the built-in countries of +/// view `v` (the sample's, whether or not it may be swapped). +pub fn holds_countries(s: &crate::Session, v: View) -> bool { + dataset(v).is_some_and(|d| s.map().layers.iter().any(|l| l.name == "Countries" && l.dataset.features == d.features)) } -/// Swaps an untouched sample project's countries from worldview `from` to `to`: only in a project +/// Swaps an untouched sample project's countries from view `from` to `to`: only in a project /// that is unsaved, unchanged and has nothing to undo, and only a layer named `Countries` holding /// exactly the built-in countries of `from`. Returns whether a layer was swapped. -pub fn swap_countries(s: &mut crate::Session, from: Worldview, to: Worldview) -> bool { +/// +/// It runs on the UI thread, where the app applies a chosen worldview, and copies the view's +/// countries read ahead of time. The copy shares the features (`Features` is copy on write): +/// measured at 15 µs for an original (1:10m) view. +pub fn swap_countries(s: &mut crate::Session, from: View, to: View) -> bool { if from == to || s.dirty() || s.path.is_some() || s.can_undo() { return false; } - let read = |w| read_geojson(countries_in(w), "Countries").ok().map(|(ds, _)| ds); - let (Some(old), Some(new)) = (read(from), read(to)) else { + // Read once per view (ahead of time on the desktop, see `fetch`), so a swap only copies. + let (Some(old), Some(new)) = (dataset(from), dataset(to)) else { return false; }; let Some(l) = s.map_mut().layers.iter_mut().find(|l| l.name == "Countries" && l.dataset.features == old.features) else { return false; }; - l.dataset = new; + l.dataset = new.clone(); l.selection.clear(); l.touch_geometry(); true diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bc520d580e..5018f68792 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -69,30 +69,103 @@ pub(crate) fn isolate_process_test(name: &str) -> bool { #[test] fn worldview_swaps_only_untouched_sample_countries() { - use sample::{Worldview, swap_countries}; + use sample::{Detail, View, Worldview, swap_countries}; let countries = |s: &Session| s.map().layer_by_name("Countries").unwrap().dataset.features.len(); + // Japan's view, which no other test uses, given countries that differ from the built-in ones + // (every country but the first) as if downloaded. + let japan = View::new(Worldview::from_code("jpn").unwrap(), Detail::Original); + let mut fewer: Value = serde_json::from_str(sample::COUNTRIES).unwrap(); + fewer["features"].as_array_mut().unwrap().remove(0); let mut s = world(); s.mark_saved(); let n = countries(&s); - // The layer holds the default countries, not China's. - assert!(!swap_countries(&mut s, Worldview::China, Worldview::Default)); - assert!(swap_countries(&mut s, Worldview::Default, Worldview::China)); - assert_ne!(countries(&s), n); + // Not before the view's countries are at hand. + assert!(!sample::ready(japan)); + assert!(!swap_countries(&mut s, View::DEFAULT, japan)); + sample::accept(japan, fewer.to_string().into_bytes()).unwrap(); + assert!(sample::ready(japan)); + // The layer holds the default countries, not Japan's. + assert!(!swap_countries(&mut s, japan, View::DEFAULT)); + assert!(swap_countries(&mut s, View::DEFAULT, japan)); + assert_eq!(countries(&s), n - 1); assert!(!s.dirty()); - assert!(swap_countries(&mut s, Worldview::China, Worldview::Default)); + assert!(swap_countries(&mut s, japan, View::DEFAULT)); assert_eq!(countries(&s), n); - // Not in a project with changes, or a saved one. + // Not in a project with changes, or a saved one; it still holds the sample's countries (the + // app then says they're kept). s.mark_unsaved(); - assert!(!swap_countries(&mut s, Worldview::Default, Worldview::China)); + assert!(!swap_countries(&mut s, View::DEFAULT, japan)); + assert!(sample::holds_countries(&s, View::DEFAULT)); + assert!(!sample::holds_countries(&s, japan)); s.mark_saved(); s.path = Some("atlas.rgis".into()); - assert!(!swap_countries(&mut s, Worldview::Default, Worldview::China)); + assert!(!swap_countries(&mut s, View::DEFAULT, japan)); // Not someone else's layer named Countries. let mut t = world(); t.mark_saved(); t.run("edit.deleteField", &json!({"layer": "Countries", "field": "pop_est"})).unwrap(); t.mark_saved(); - assert!(!swap_countries(&mut t, Worldview::Default, Worldview::China)); + // With nothing to undo, so only the layer's own countries stop the swap. + t.clear_history(); + assert!(!t.can_undo()); + assert!(!swap_countries(&mut t, View::DEFAULT, japan)); + assert!(!sample::holds_countries(&t, View::DEFAULT)); +} + +#[test] +fn a_worldview_download_that_isnt_countries_is_refused() { + use sample::{Detail, View, Worldview}; + let korea = View::new(Worldview::from_code("kor").unwrap(), Detail::Simplified); + for bad in [b"\xff\xfe".to_vec(), b"404".to_vec(), sample::CITIES.as_bytes().to_vec()] { + assert!(sample::accept(korea, bad).is_err()); + } + assert!(!sample::ready(korea)); + // Nor is a download over the size allowed at its detail. + assert!(sample::accept(korea, vec![b' '; Detail::Simplified.max_bytes() + 1]).unwrap_err().contains("more than")); + // Applying it before then keeps the current view and says which one was asked for. + assert_eq!(sample::apply_view("kor", "simplified"), korea); + assert_ne!(sample::view(), korea); + assert_eq!(sample::wanted_view("kor", "nonsense"), korea); + // The default is built in. + assert!(sample::ready(View::DEFAULT)); + assert!(sample::download_blocking(View::DEFAULT).is_ok()); +} + +#[test] +fn an_original_worldview_downloads_gzipped() { + use sample::{Detail, View, Worldview}; + let gzip = |text: &[u8]| { + let mut out = vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0xff]; + out.extend(miniz_oxide::deflate::compress_to_vec(text, 6)); + out.extend([0; 8]); + out + }; + // Vietnam's view, original detail, which no other test uses. + let v = View::new(Worldview::from_code("vnm").unwrap(), Detail::Original); + // Something that unpacks to more than the original detail allows is refused, not cut. + let huge = gzip(&vec![b' '; Detail::Original.max_bytes() + 1]); + assert!(sample::accept(v, huge).unwrap_err().contains("can't be unpacked")); + assert!(sample::accept(v, vec![0x1f, 0x8b, 8]).is_err()); + assert!(sample::text(v).is_none()); + sample::accept(v, gzip(sample::COUNTRIES.as_bytes())).unwrap(); + assert_eq!(sample::text(v), Some(sample::COUNTRIES)); + // The default worldview's original detail is a download too. + assert!(!sample::ready(View::new(Worldview::DEFAULT, Detail::Original))); +} + +#[test] +fn a_failed_worldview_download_doesnt_name_the_worldview_twice() { + use sample::{Detail, View, Worldview}; + // Never the computer's own cache folder. + sample::keep_downloads(false); + // Greece's view, original detail, which no other test uses. + let v = View::new(Worldview::from_code("grc").unwrap(), Detail::Original); + let (tx, rx) = std::sync::mpsc::channel(); + sample::fetch_with(v, Box::new(move |r| drop(tx.send(r))), |_, _| Err("http status: 404".to_string())); + let e = rx.recv_timeout(std::time::Duration::from_secs(30)).unwrap().unwrap_err(); + // The app's notice names the worldview; the error is only why. + assert_eq!(e, "http status: 404"); + assert!(sample::text(v).is_none()); } #[test] diff --git a/crates/render/build.rs b/crates/render/build.rs index aeec4b99ca..dd8217801a 100644 --- a/crates/render/build.rs +++ b/crates/render/build.rs @@ -1,5 +1,6 @@ //! Fetches the Natural Earth sample data (public domain) that RustGIS embeds for its basemap //! outline and World Atlas sample. The files live in opengeos/rustgis-assets, not in this repo. +//! The countries in other worldviews aren't embedded: the app downloads them when one is chosen. //! //! Set `RUSTGIS_DATA_DIR` to a folder holding the files to build offline. @@ -7,7 +8,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; const BASE: &str = "https://assets.rustgis.app/data"; -const FILES: [&str; 5] = ["countries.geojson", "countries_chn.geojson", "cities.geojson", "rivers.geojson", "lakes.geojson"]; +const FILES: [&str; 4] = ["countries.geojson", "cities.geojson", "rivers.geojson", "lakes.geojson"]; fn valid(p: &Path) -> bool { std::fs::read(p).is_ok_and(|b| b.len() > 2 && b.first() == Some(&b'{')) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b875cd61c8..83eeede28c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -44,42 +44,199 @@ pub use rustgis_tiles; pub use tiles::{source_layers as tile_source_layers, spec as tile_spec, style_view}; /// Natural Earth 1:110m sample data (public domain), fetched by `build.rs` from rustgis-assets. +/// The countries in another worldview are downloaded when one is chosen, never built in. pub mod sample_data { + use std::sync::OnceLock; + use std::sync::atomic::{AtomicU8, Ordering}; + pub const COUNTRIES: &str = include_str!(concat!(env!("OUT_DIR"), "/countries.geojson")); - /// The countries as China sees its borders (Natural Earth's China point of view). - pub const COUNTRIES_CHN: &str = include_str!(concat!(env!("OUT_DIR"), "/countries_chn.geojson")); pub const CITIES: &str = include_str!(concat!(env!("OUT_DIR"), "/cities.geojson")); pub const RIVERS: &str = include_str!(concat!(env!("OUT_DIR"), "/rivers.geojson")); pub const LAKES: &str = include_str!(concat!(env!("OUT_DIR"), "/lakes.geojson")); - use std::sync::atomic::{AtomicU8, Ordering}; - - /// Whose view of disputed borders the built-in countries and world outline show. - #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] - pub enum Worldview { - /// Natural Earth's de facto borders. + /// Where the worldviews' countries are downloaded from (source.coop): `original/countries_.geojson` + /// and `countries_.geojson`, made from Natural Earth's points of view by rustgis-assets' + /// `scripts/worldviews.py`. + pub const WORLDVIEWS_URL: &str = "https://data.source.coop/opengeos/data/rustgis/worldviews"; + + /// How detailed a downloaded worldview's borders are. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] + pub enum Detail { + /// Natural Earth's 1:10m shapes, every island kept (about 10 MB, a 3 MB gzip download). + Original, + /// Simplified to the built-in countries' 1:110m size (about 250 KB), the default. #[default] - Default, - /// China's view (required for maps shown in China). - China, + Simplified, } - impl Worldview { + impl Detail { + /// The code settings and `--worldview-detail` use. pub fn code(self) -> &'static str { match self { - Worldview::Default => "default", - Worldview::China => "china", + Detail::Original => "original", + Detail::Simplified => "simplified", } } - pub fn from_code(code: &str) -> Option { + pub fn from_code(code: &str) -> Option { match code.trim().to_ascii_lowercase().as_str() { - "default" => Some(Worldview::Default), - "china" | "chn" | "cn" => Some(Worldview::China), + "original" => Some(Detail::Original), + "simplified" => Some(Detail::Simplified), _ => None, } } + /// The most bytes a worldview's file may be at this detail. + pub fn max_bytes(self) -> usize { + match self { + Detail::Original => 64 << 20, + Detail::Simplified => 8 << 20, + } + } + } + + /// A worldview at a detail. The default worldview at the simplified detail is built in; every + /// other view is downloaded, the default's original one included. + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub struct View { + pub worldview: Worldview, + pub detail: Detail, + } + + impl Default for View { + fn default() -> Self { + View::DEFAULT + } + } + + impl View { + /// The built-in countries. + pub const DEFAULT: View = View { worldview: Worldview::DEFAULT, detail: Detail::Simplified }; + + pub fn new(worldview: Worldview, detail: Detail) -> View { + View { worldview, detail } + } + + /// Whether it is built in (the default worldview, simplified). + pub fn built_in(self) -> bool { + self == View::DEFAULT + } + + /// Its place among the views' slots. + pub const fn index(self) -> usize { + self.worldview.0 as usize * 2 + matches!(self.detail, Detail::Simplified) as usize + } + + /// Its file's path in the cache folder (the GeoJSON itself). + pub fn file(self) -> String { + match self.detail { + Detail::Original => format!("original/countries_{}.geojson", self.worldview.code()), + Detail::Simplified => format!("countries_{}.geojson", self.worldview.code()), + } + } + + /// The address its countries are downloaded from (none for the built-in one): below + /// [`WORLDVIEWS_URL`], gzipped for the original detail. + pub fn url(self) -> Option { + let gz = if self.detail == Detail::Original { ".gz" } else { "" }; + (!self.built_in()).then(|| format!("{WORLDVIEWS_URL}/{}{gz}", self.file())) + } + + /// The most bytes its GeoJSON may be (once inflated). + pub fn max_bytes(self) -> usize { + self.detail.max_bytes() + } + } + + /// How many worldviews there are. + pub const WORLDVIEW_COUNT: usize = VIEWS.len(); + + /// Each worldview's code (Natural Earth's) and English name; the first is the built-in one. + const VIEWS: [(&str, &str); 32] = [ + ("default", "Default"), + ("arg", "Argentina"), + ("bdg", "Bangladesh"), + ("bra", "Brazil"), + ("chn", "China"), + ("egy", "Egypt"), + ("fra", "France"), + ("deu", "Germany"), + ("grc", "Greece"), + ("ind", "India"), + ("idn", "Indonesia"), + ("isr", "Israel"), + ("ita", "Italy"), + ("jpn", "Japan"), + ("mar", "Morocco"), + ("nep", "Nepal"), + ("nld", "Netherlands"), + ("pak", "Pakistan"), + ("pse", "Palestine"), + ("pol", "Poland"), + ("prt", "Portugal"), + ("rus", "Russia"), + ("sau", "Saudi Arabia"), + ("kor", "South Korea"), + ("esp", "Spain"), + ("swe", "Sweden"), + ("twn", "Taiwan"), + ("tur", "Turkey"), + ("ukr", "Ukraine"), + ("gbr", "United Kingdom"), + ("usa", "United States"), + ("vnm", "Vietnam"), + ]; + + /// Whose view of disputed borders the built-in countries and world outline show: Natural + /// Earth's de facto borders (built in), or one of its points of view (downloaded). + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] + pub struct Worldview(u8); + + impl Worldview { + /// Natural Earth's de facto borders, built in. + pub const DEFAULT: Worldview = Worldview(0); + /// China's view (required for maps shown in China), the one chosen automatically. + pub const CHINA: Worldview = Worldview(4); + + /// Every worldview, the default first, then by English name. + pub fn all() -> impl Iterator { + (0..VIEWS.len() as u8).map(Worldview) + } + + /// Its position in [`Worldview::all`]. + pub fn index(self) -> usize { + usize::from(self.0) + } + + /// The code settings, `RUSTGIS_WORLDVIEW` and `--worldview` use (Natural Earth's, such as `ind`). + pub fn code(self) -> &'static str { + VIEWS.get(self.index()).map_or("default", |v| v.0) + } + + /// Its English name: the country whose view it is. + pub fn name(self) -> &'static str { + VIEWS.get(self.index()).map_or("Default", |v| v.1) + } + + /// The worldview a code names: Natural Earth's code, the ISO 3166-1 alpha-3 one where it + /// differs, or the country's English name, in any case; `china` and `cn` are China. + pub fn from_code(code: &str) -> Option { + let code = code.trim().to_ascii_lowercase(); + let code = match code.as_str() { + "cn" => "chn", + "bgd" => "bdg", + "npl" => "nep", + c => c, + }; + Worldview::all().find(|w| w.code() == code || w.name().eq_ignore_ascii_case(code)) + } + + /// Whether it is the default worldview (Natural Earth's de facto borders), the one built + /// in at the simplified detail. + pub fn built_in(self) -> bool { + self == Worldview::DEFAULT + } + /// The worldview for a system in time zone `tz` (IANA, such as `Asia/Shanghai`) whose /// preferred locales are `locales` (such as `zh-CN`, `zh_CN.UTF-8`): China when the time /// zone is one of mainland China's or the first locale is mainland Chinese. @@ -95,27 +252,120 @@ pub mod sample_data { let mut parts = base.split('-'); parts.next() == Some("zh") && parts.any(|p| p == "cn") }); - if china_tz || china_locale { Worldview::China } else { Worldview::Default } + if china_tz || china_locale { Worldview::CHINA } else { Worldview::DEFAULT } } } - static WORLDVIEW: AtomicU8 = AtomicU8::new(0); + /// How many views there are (each worldview at each detail). + pub const VIEW_COUNT: usize = VIEWS.len() * 2; + + /// The downloaded countries of each view (the built-in one's slot stays empty), and each view's + /// countries read. Both are kept for the rest of the run, deliberately: a view is downloaded + /// only when chosen, so they hold the views a session has shown (an original one is about + /// 10 MB of text and as much read), and switching back to one costs nothing. + static TEXTS: [OnceLock; VIEW_COUNT] = [const { OnceLock::new() }; VIEW_COUNT]; + static SETS: [OnceLock>; VIEW_COUNT] = [const { OnceLock::new() }; VIEW_COUNT]; - /// Sets the worldview of the countries sample and the basemap's world outline. - pub fn set_worldview(w: Worldview) { - WORLDVIEW.store(w as u8, Ordering::Relaxed); + /// The view shown, as its index. + static VIEW: AtomicU8 = AtomicU8::new(View::DEFAULT.index() as u8); + + /// Keeps a view's downloaded countries for the rest of the run, once they are checked: at + /// most [`View::max_bytes`], GeoJSON polygons of at least 100 countries with the built-in + /// countries' fields. A view that already has its countries keeps them. + pub fn install(v: View, text: String) -> Result<(), String> { + let w = v.worldview; + if v.built_in() { + return Ok(()); + } + let max = v.max_bytes(); + if text.len() > max { + return Err(format!("the {} worldview's countries are {} bytes, more than the {max} allowed", w.name(), text.len())); + } + let ds = check(&text).map_err(|e| format!("the {} worldview's countries aren't usable: {e}", w.name()))?; + let (Some(texts), Some(sets)) = (TEXTS.get(v.index()), SETS.get(v.index())) else { + return Err("unknown worldview".into()); + }; + // Read once: the check's dataset is the one shown. It goes in first, so a view whose text + // is at hand (what `view` and `set_view` go by) always has its countries read. + if texts.get().is_none() { + let _ = sets.set(Some(ds)); + let _ = texts.set(text); + } + Ok(()) + } + + /// Checks that `text` can stand in for the built-in countries and returns it read. It reads the + /// whole file, once per view and run: a few milliseconds for a simplified one, about 85 ms for + /// an original one, which the desktop app checks on the download's thread. A file the reader + /// skips features of is refused: a worldview missing countries isn't usable. + fn check(text: &str) -> Result { + use rustgis_data::Geometry; + let names = |d: &rustgis_data::Dataset| d.fields.iter().map(|f| f.name.clone()).collect::>(); + // The built-in countries' fields, read once. + static BUILT_IN: OnceLock> = OnceLock::new(); + let built_in = + BUILT_IN.get_or_init(|| rustgis_data::io::read_geojson(COUNTRIES, "Countries").map(|(d, _)| names(&d)).unwrap_or_default()); + let (ds, report) = rustgis_data::io::read_geojson(text, "Countries").map_err(|e| e.to_string())?; + if report.skipped > 0 { + return Err(format!("{} of its features can't be read", report.skipped)); + } + if ds.features.len() < 100 { + return Err(format!("{} countries, fewer than 100", ds.features.len())); + } + if built_in.is_empty() || names(&ds) != *built_in { + return Err("its fields aren't the built-in countries'".into()); + } + if !ds.features.iter().all(|f| matches!(f.geometry, Some(Geometry::Polygon(_)))) { + return Err("not every country is a polygon".into()); + } + Ok(ds) + } + + /// A view's countries read as a layer's dataset, once per view and run (a few milliseconds + /// simplified, about 85 ms for an original view, which the desktop app reads on the + /// download's thread): `None` until its countries are at hand. + pub fn dataset(v: View) -> Option<&'static rustgis_data::Dataset> { + let slot = SETS.get(v.index())?; + if v.built_in() { + return slot.get_or_init(|| rustgis_data::io::read_geojson(COUNTRIES, "Countries").ok().map(|(d, _)| d)).as_ref(); + } + // A downloaded view's dataset is kept by `install`, which read it. + slot.get()?.as_ref() + } + + /// A view's countries GeoJSON, if it is built in or has been downloaded. + pub fn text(v: View) -> Option<&'static str> { + if v.built_in() { Some(COUNTRIES) } else { TEXTS.get(v.index()).and_then(|t| t.get()).map(String::as_str) } } + /// Shows a view in the countries sample and the basemap's world outline, if its countries are + /// at hand ([`text`]); otherwise nothing changes and it says so with `false`. + pub fn set_view(v: View) -> bool { + let v = View::new(v.worldview, v.detail); + if text(v).is_none() { + return false; + } + VIEW.store(u8::try_from(v.index()).unwrap_or(0), Ordering::Relaxed); + true + } + + /// The view shown. + pub fn view() -> View { + let i = usize::from(VIEW.load(Ordering::Relaxed)); + let worldview = Worldview::all().nth(i / 2).unwrap_or_default(); + let detail = if i % 2 == 1 { Detail::Simplified } else { Detail::Original }; + let v = View::new(worldview, detail); + if text(v).is_some() { v } else { View::DEFAULT } + } + + /// The worldview shown. pub fn worldview() -> Worldview { - if WORLDVIEW.load(Ordering::Relaxed) == Worldview::China as u8 { Worldview::China } else { Worldview::Default } + view().worldview } /// The countries GeoJSON in the current worldview. pub fn countries() -> &'static str { - match worldview() { - Worldview::Default => COUNTRIES, - Worldview::China => COUNTRIES_CHN, - } + text(view()).unwrap_or(COUNTRIES) } } @@ -345,23 +595,48 @@ pub fn viewing_distance(ground_res: f64, view_height: f64) -> f64 { /// The built-in world outline used by every basemap (Natural Earth 1:110m, public domain), in the /// current worldview. fn world() -> &'static Vec { - static W: [OnceLock>; 2] = [OnceLock::new(), OnceLock::new()]; - let wv = sample_data::worldview(); - let cell = &W[wv as usize]; - cell.get_or_init(|| match rustgis_data::io::read_geojson(sample_data::countries(), "world") { - Ok((ds, _)) => ds.features.into_iter().filter_map(|f| f.geometry).map(|g| g.map_coords(&lonlat_to_merc)).collect(), - Err(e) => { - log::warn!("built-in world outline unreadable: {e}"); - Vec::new() - } - }) + world_of(sample_data::view()) +} + +/// The world outline in view `wv`, in Web Mercator. +fn world_of(wv: sample_data::View) -> &'static Vec { + static W: [OnceLock>; sample_data::VIEW_COUNT] = [const { OnceLock::new() }; sample_data::VIEW_COUNT]; + static NONE: Vec = Vec::new(); + let Some(cell) = W.get(wv.index()) else { return &NONE }; + // A view whose countries aren't at hand draws no outline and caches none, so its slot fills + // once they arrive. + let Some(ds) = sample_data::dataset(wv) else { + log::warn!("the world outline of a worldview not at hand was asked for"); + return &NONE; + }; + cell.get_or_init(|| ds.features.iter().filter_map(|f| f.geometry.as_ref()).map(|g| g.map_coords(&lonlat_to_merc)).collect()) +} + +/// Reads a view's countries and builds its world outline for the flat map and the globe ahead of +/// time (the desktop app does it on the download's thread), so none of it is done on the UI +/// thread when the view is shown. A map in another projection still projects the outline once, +/// on the first frame drawn in it. +pub fn prepare_world(v: sample_data::View) { + let _ = sample_data::dataset(v); + let _ = world_of(v); + let _ = world_lonlat_of(v); } /// The built-in world outline in longitude/latitude, for the globe. fn world_lonlat() -> &'static Vec { - static W: [OnceLock>; 2] = [OnceLock::new(), OnceLock::new()]; - let cell = &W[sample_data::worldview() as usize]; - cell.get_or_init(|| world().iter().map(|g| g.map_coords(&rustgis_geom::merc_to_lonlat)).collect()) + world_lonlat_of(sample_data::view()) +} + +/// The world outline in view `wv`, in longitude/latitude. +fn world_lonlat_of(wv: sample_data::View) -> &'static Vec { + static W: [OnceLock>; sample_data::VIEW_COUNT] = [const { OnceLock::new() }; sample_data::VIEW_COUNT]; + static NONE: Vec = Vec::new(); + let Some(cell) = W.get(wv.index()) else { return &NONE }; + // As `world_of`: nothing is cached until the view's countries are at hand. + if sample_data::dataset(wv).is_none() { + return &NONE; + } + cell.get_or_init(|| world_of(wv).iter().map(|g| g.map_coords(&rustgis_geom::merc_to_lonlat)).collect()) } thread_local! { @@ -373,9 +648,14 @@ thread_local! { /// The built-in world outline in a custom projection's coordinates (kept per projection). fn world_in(flat: &rustgis_map::projection::Flat, key: &str) -> std::rc::Rc> { WORLD_IN.with(|cell| { + let lonlat = world_lonlat(); + // An outline not at hand yet is drawn empty, not kept. + if lonlat.is_empty() { + return std::rc::Rc::new(Vec::new()); + } cell.borrow_mut() - .entry(format!("{}:{key}", sample_data::worldview().code())) - .or_insert_with(|| std::rc::Rc::new(world_lonlat().iter().map(|g| flat.project(g)).collect())) + .entry(format!("{}:{key}", sample_data::view().index())) + .or_insert_with(|| std::rc::Rc::new(lonlat.iter().map(|g| flat.project(g)).collect())) .clone() }) } @@ -6597,36 +6877,115 @@ mod tests { use rustgis_data::{Field, FieldType, Value}; #[test] - fn worldview_detection_and_data() { - use sample_data::Worldview::{China, Default}; - let detect = |tz: Option<&str>, locales: &[&str]| sample_data::Worldview::detect(tz, locales.iter().copied()); - assert_eq!(detect(Some("Asia/Shanghai"), &["en-US"]), China); - assert_eq!(detect(Some("Asia/Urumqi"), &[]), China); - assert_eq!(detect(Some("Europe/Berlin"), &["zh-CN", "en"]), China); - assert_eq!(detect(None, &["zh_CN.UTF-8"]), China); - assert_eq!(detect(None, &["zh-Hans-CN"]), China); - assert_eq!(detect(Some("Asia/Taipei"), &["zh-TW"]), Default); - assert_eq!(detect(Some("Asia/Hong_Kong"), &["zh-HK"]), Default); - assert_eq!(detect(Some("America/New_York"), &["en-US", "zh-CN"]), Default); - assert_eq!(detect(None, &[]), Default); - assert_eq!(sample_data::Worldview::from_code(" China "), Some(China)); - assert_eq!(sample_data::Worldview::from_code("default"), Some(Default)); - assert_eq!(sample_data::Worldview::from_code("auto"), None); - // Both files have the same fields; in China's view Taiwan is part of China. - let read = |text| rustgis_data::io::read_geojson(text, "Countries").unwrap().0; - let (def, chn) = (read(sample_data::COUNTRIES), read(sample_data::COUNTRIES_CHN)); - let fields = |d: &Dataset| d.fields.iter().map(|f| f.name.clone()).collect::>(); - assert_eq!(fields(&def), fields(&chn)); - let names = |d: &Dataset| { - let i = d.fields.iter().position(|f| f.name == "name").unwrap(); - d.features - .iter() - .filter_map(|f| if let Some(Value::Text(t)) = f.attrs.get(i) { Some(t.clone()) } else { None }) - .collect::>() - }; - assert!(names(&def).iter().any(|n| n == "Taiwan")); - assert!(!names(&chn).iter().any(|n| n == "Taiwan")); - assert!(names(&chn).iter().any(|n| n == "China")); + fn worldview_detection_and_codes() { + use sample_data::Worldview; + let (china, default) = (Worldview::CHINA, Worldview::DEFAULT); + let detect = |tz: Option<&str>, locales: &[&str]| Worldview::detect(tz, locales.iter().copied()); + assert_eq!(detect(Some("Asia/Shanghai"), &["en-US"]), china); + assert_eq!(detect(Some("Asia/Urumqi"), &[]), china); + assert_eq!(detect(Some("Europe/Berlin"), &["zh-CN", "en"]), china); + assert_eq!(detect(None, &["zh_CN.UTF-8"]), china); + assert_eq!(detect(None, &["zh-Hans-CN"]), china); + assert_eq!(detect(Some("Asia/Taipei"), &["zh-TW"]), default); + assert_eq!(detect(Some("Asia/Hong_Kong"), &["zh-HK"]), default); + assert_eq!(detect(Some("America/New_York"), &["en-US", "zh-CN"]), default); + assert_eq!(detect(None, &[]), default); + // Settings saved by earlier versions said `china`. + assert_eq!(Worldview::from_code(" China "), Some(china)); + assert_eq!(Worldview::from_code("cn"), Some(china)); + assert_eq!(Worldview::from_code("chn"), Some(china)); + assert_eq!(Worldview::from_code("default"), Some(default)); + assert_eq!(Worldview::from_code("IND").map(Worldview::name), Some("India")); + assert_eq!(Worldview::from_code("united states").map(Worldview::code), Some("usa")); + assert_eq!(Worldview::from_code("bgd").map(Worldview::code), Some("bdg")); + for bad in ["auto", "", "xyz", "../chn"] { + assert_eq!(Worldview::from_code(bad), None, "{bad}"); + } + // Natural Earth's 31 points of view, each downloaded; only the default is built in. + let all: Vec<_> = Worldview::all().collect(); + assert_eq!(all.len(), 32); + assert_eq!(china.code(), "chn"); + assert_eq!( + sample_data::View::new(china, sample_data::Detail::Simplified).url().as_deref(), + Some("https://data.source.coop/opengeos/data/rustgis/worldviews/countries_chn.geojson") + ); + let codes: std::collections::HashSet<_> = all.iter().map(|w| w.code()).collect(); + assert_eq!(codes.len(), all.len()); + assert!(all.iter().all(|w| Worldview::from_code(w.code()) == Some(*w))); + assert!(all.iter().skip(1).all(|w| !w.built_in() && w.code().len() == 3)); + } + + #[test] + fn a_worldview_needs_its_countries_before_it_is_shown() { + use sample_data::{Detail, View, Worldview, install, set_view, text}; + // Sweden's view, which no other test uses. + let w = Worldview::from_code("swe").unwrap(); + let (original, simplified) = (View::new(w, Detail::Original), View::new(w, Detail::Simplified)); + assert_eq!(text(original), None); + assert!(!set_view(original)); + assert_eq!(sample_data::view(), View::DEFAULT); + // What isn't a countries file is refused. + for bad in ["", "not json", r#"{"type":"FeatureCollection","features":[]}"#, sample_data::CITIES] { + assert!(install(original, bad.to_string()).is_err()); + } + let few = r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"A"},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]}}]}"#; + assert!(install(original, few.to_string()).unwrap_err().contains("fewer than 100")); + // Nor one the reader skips features of (a country left out), however many it keeps. + let mut broken: serde_json::Value = serde_json::from_str(sample_data::COUNTRIES).unwrap(); + broken["features"][0]["geometry"] = serde_json::json!({"type": "Polygon", "coordinates": "not coordinates"}); + assert!(install(original, broken.to_string()).unwrap_err().contains("can't be read")); + assert_eq!(text(original), None); + // Nor is anything over the size allowed at its detail, whatever it holds (the web app's + // fetch has no cap). + let huge = format!("{}{}", sample_data::COUNTRIES, " ".repeat(Detail::Simplified.max_bytes())); + assert!(install(simplified, huge).unwrap_err().contains("more than")); + // The built-in countries' shape is accepted; the view then shows (the same borders). Each + // detail is its own download. + install(original, sample_data::COUNTRIES.to_string()).unwrap(); + assert!(text(original).is_some()); + assert_eq!(text(simplified), None); + assert!(!set_view(simplified)); + assert!(set_view(original)); + assert_eq!(sample_data::view(), original); + assert_eq!(sample_data::worldview(), w); + assert!(set_view(View::DEFAULT)); + // The view shown at start is the built-in one, even once the default worldview's + // original detail is at hand. + let default_original = View::new(Worldview::DEFAULT, Detail::Original); + install(default_original, sample_data::COUNTRIES.to_string()).unwrap(); + assert_eq!(sample_data::view(), View::DEFAULT); + } + + #[test] + fn views_and_their_files() { + use sample_data::{Detail, View, Worldview}; + let ind = Worldview::from_code("ind").unwrap(); + assert_eq!(Detail::default(), Detail::Simplified); + assert_eq!( + View::new(ind, Detail::Original).url().as_deref(), + Some("https://data.source.coop/opengeos/data/rustgis/worldviews/original/countries_ind.geojson.gz") + ); + assert_eq!(View::new(ind, Detail::Original).file(), "original/countries_ind.geojson"); + assert_eq!( + View::new(ind, Detail::Simplified).url().as_deref(), + Some("https://data.source.coop/opengeos/data/rustgis/worldviews/countries_ind.geojson") + ); + // The built-in countries are the default worldview simplified; its original detail is a + // download like any other. + assert!(View::new(Worldview::DEFAULT, Detail::Simplified).built_in()); + assert_eq!(View::DEFAULT.url(), None); + assert_eq!( + View::new(Worldview::DEFAULT, Detail::Original).url().as_deref(), + Some("https://data.source.coop/opengeos/data/rustgis/worldviews/original/countries_default.geojson.gz") + ); + let slots: std::collections::HashSet<_> = + Worldview::all().flat_map(|w| [View::new(w, Detail::Original), View::new(w, Detail::Simplified)]).map(View::index).collect(); + assert_eq!(slots.len(), 2 * 32); + assert!(slots.iter().all(|&i| i < sample_data::VIEW_COUNT)); + for (code, d) in [("original", Detail::Original), (" Simplified ", Detail::Simplified)] { + assert_eq!(Detail::from_code(code), Some(d)); + } + assert_eq!(Detail::from_code("detailed"), None); } #[test] diff --git a/crates/tiles/src/mvt.rs b/crates/tiles/src/mvt.rs index 994d8c73a6..77aec1ba30 100644 --- a/crates/tiles/src/mvt.rs +++ b/crates/tiles/src/mvt.rs @@ -279,7 +279,15 @@ fn is_zlib(b: &[u8]) -> bool { /// Strips the gzip header (RFC 1952, all flags) and inflates the deflate body; the trailer is ignored. fn gunzip(b: &[u8]) -> Result, String> { + gunzip_within(b, MAX_INFLATE) +} + +/// Inflates gzip bytes to at most `max` bytes (more is an error, not a truncation). +pub fn gunzip_within(b: &[u8], max: usize) -> Result, String> { const TRUNC: &str = "truncated gzip header"; + if !b.starts_with(&[0x1f, 0x8b]) { + return Err("not gzip".into()); + } if b.get(2) != Some(&8) { return Err("unsupported gzip compression method".into()); } @@ -300,7 +308,7 @@ fn gunzip(b: &[u8]) -> Result, String> { pos += 2; } let body = b.get(pos..).ok_or(TRUNC)?; - inflate::decompress_to_vec_with_limit(body, MAX_INFLATE).map_err(|e| format!("gzip: {:?}", e.status)) + inflate::decompress_to_vec_with_limit(body, max).map_err(|e| format!("gzip: {:?}", e.status)) } /// Minimal protobuf wire reader. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 966cc90d13..fbdd523585 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -115,6 +115,7 @@ mod vertexedit; mod webdataui; mod widgets; mod workspacepanes; +mod worldviewui; mod zarrui; use rustgis_engine::cmd::service_added::Removal; @@ -694,9 +695,14 @@ pub struct UiState { pub dark_follows_system: bool, /// Interface language preference: a language code or `auto`. pub language: String, - /// Worldview preference for the built-in countries and world outline: `auto`, `default` or - /// `china`. + /// Worldview preference for the built-in countries and world outline: a worldview's code + /// (such as `default`, `chn` or `ind`), or `auto` until one is chosen (China's on a system in + /// mainland China, else the default). pub worldview: String, + /// How detailed a downloaded worldview is: `simplified` (the default) or `original`. + pub worldview_detail: String, + /// The worldview being downloaded. + pub worldview_fetch: Option, /// Start-up preference: what RustGIS opens with. pub start_with: StartWith, /// Whether a file holding several layers asks which to add (#934), or adds them all. @@ -941,6 +947,8 @@ impl Default for UiState { dark_follows_system: true, language: i18n::AUTO.into(), worldview: i18n::AUTO.into(), + worldview_detail: rustgis_engine::sample::Detail::default().code().into(), + worldview_fetch: None, start_with: StartWith::Sample, ask_layers: true, reserved_shortcuts: Vec::new(), @@ -1380,11 +1388,34 @@ impl RustGisApp { i18n::set_current(self.chosen_lang()); // After the language, so a notice about the saved value is in it. threadsui::load(&mut self); - // A stored value that is neither `auto` nor a known worldview means `auto`. - if let Some(w) = self.services.load_pref.as_ref().and_then(|load| load("worldview")) - && rustgis_engine::sample::Worldview::from_code(&w).is_some() - { - self.ui.worldview = w.trim().to_ascii_lowercase(); + // A stored value that is neither `auto` nor a known worldview means `auto`; `china`, as + // earlier versions saved it, is China's view. One this version doesn't know (from a newer + // RustGIS) is said, and stays saved until another is chosen. + let load = |key: &str| self.services.load_pref.as_ref().and_then(|load| load(key)).map(|v| v.trim().to_ascii_lowercase()); + let (stored, stored_detail) = (load("worldview"), load("worldview_detail")); + if let Some(code) = stored.filter(|c| c != i18n::AUTO) { + match rustgis_engine::sample::Worldview::from_code(&code) { + Some(w) => self.ui.worldview = w.code().to_string(), + None => self.session.notify( + i18n::fmt( + "The saved worldview '{code}' isn't one this version knows, so it is ignored until you choose one", + &[("code", &code)], + ), + false, + ), + } + } + if let Some(code) = stored_detail { + match rustgis_engine::sample::Detail::from_code(&code) { + Some(d) => self.ui.worldview_detail = d.code().to_string(), + None => self.session.notify( + i18n::fmt( + "The saved worldview detail '{code}' isn't one this version knows; simplified borders are used", + &[("code", &code)], + ), + false, + ), + } } self.apply_worldview(); self.ui.start_with = @@ -1893,24 +1924,17 @@ impl RustGisApp { /// The sample "World Atlas" project. pub fn with_sample() -> Self { // Tests don't depend on the machine's time zone and locale. - rustgis_engine::sample::apply_worldview(if cfg!(test) { "default" } else { i18n::AUTO }); + rustgis_engine::sample::apply_view(if cfg!(test) { "default" } else { i18n::AUTO }, ""); let mut s = Session::new(Project::default()); let _ = s.run("project.sample", &Value::Null); s.mark_saved(); RustGisApp::new(s) } - /// Applies the worldview preference; an untouched sample project's countries follow it. + /// Applies the worldview preference, downloading its countries if they aren't at hand; an + /// untouched sample project's countries follow it. fn apply_worldview(&mut self) { - use rustgis_engine::sample; - let before = sample::worldview(); - // Tests don't depend on the machine's time zone and locale. - let pref = if cfg!(test) && self.ui.worldview == i18n::AUTO { "default" } else { self.ui.worldview.as_str() }; - let after = sample::apply_worldview(pref); - if after != before { - sample::swap_countries(&mut self.session, before, after); - self.map.invalidate(); - } + worldviewui::apply(self); } /// Reloads available theme files from the user folder, retaining built-ins when it is absent. @@ -2868,13 +2892,40 @@ impl RustGisApp { self.map.invalidate(); } "ui.worldview" => { - let code = p.get("worldview").and_then(Value::as_str).unwrap_or(i18n::AUTO).to_ascii_lowercase(); - if code != i18n::AUTO && rustgis_engine::sample::Worldview::from_code(&code).is_none() { - return Err(format!("unknown worldview '{code}'")); + // `detail` alone (a missing or null worldview) keeps the worldview; no parameters at + // all mean `auto`. + let detail_only = p.get("worldview").is_none_or(Value::is_null) && p.get("detail").is_some_and(|d| !d.is_null()); + let code = match p.get("worldview") { + _ if detail_only => None, + None | Some(Value::Null) => Some(i18n::AUTO.to_string()), + Some(Value::String(c)) => Some(c.trim().to_ascii_lowercase()), + Some(other) => return Err(format!("worldview must be a worldview's code, not {other}")), + }; + let detail = match p.get("detail") { + None | Some(Value::Null) => None, + Some(Value::String(d)) => Some( + rustgis_engine::sample::Detail::from_code(d) + .ok_or_else(|| format!("unknown worldview detail '{d}': original or simplified"))?, + ), + Some(other) => return Err(format!("detail must be original or simplified, not {other}")), + }; + if let Some(code) = code { + // Kept as the worldview's own code, so `China` and `chn` are saved alike. + self.ui.worldview = if code == i18n::AUTO { + code + } else { + let w = rustgis_engine::sample::Worldview::from_code(&code).ok_or_else(|| format!("unknown worldview '{code}'"))?; + w.code().to_string() + }; + if let Some(save) = &self.services.save_pref { + save("worldview", &self.ui.worldview); + } } - self.ui.worldview = code; - if let Some(save) = &self.services.save_pref { - save("worldview", &self.ui.worldview); + if let Some(d) = detail { + self.ui.worldview_detail = d.code().to_string(); + if let Some(save) = &self.services.save_pref { + save("worldview_detail", &self.ui.worldview_detail); + } } self.apply_worldview(); } @@ -5298,6 +5349,7 @@ impl RustGisApp { connectionui::poll(self, ctx); connectiontree::poll(self, ctx); portalsui::poll(self, ctx); + worldviewui::poll(self, ctx); catalogsui::poll(self, ctx); opendataui::poll(self, ctx); embeddingsui::poll(self, ctx); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index fea13cccad..6f1dc42025 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -4998,29 +4998,51 @@ fn other_name(ui: &Ui, l: crate::i18n::Lang) -> &'static str { if shown == l.english() && drawable(ui, l.name()) { l.name() } else { l.english() } } -/// Whose view of disputed borders the built-in countries and world outline show (Settings › Language). +/// Whose view of disputed borders the built-in countries and world outline show (Settings › +/// Language): the built-in default or one of Natural Earth's points of view, downloaded when +/// chosen. Until one is chosen, a system in mainland China shows China's. fn worldview_menu(app: &mut RustGisApp, ui: &mut Ui) { - use rustgis_engine::sample::Worldview; - let name = |w: Worldview| match w { - Worldview::Default => tl!("Default"), - Worldview::China => tl!("China"), + use crate::worldviewui::name; + use rustgis_engine::sample::{self, Detail, View, Worldview}; + let label = match crate::worldviewui::downloading(app) { + Some(w) => crate::i18n::fmt("{name} (downloading…)", &[("name", name(w))]), + None => name(sample::worldview()).to_string(), }; - let auto = app.ui.worldview == crate::i18n::AUTO; - let current = rustgis_engine::sample::worldview(); - let label = if auto { format!("{} ({})", tl!("Automatic"), name(current)) } else { name(current).to_string() }; let label = format!("{}\n{label}", tl!("Worldview")); big_menu(ui, app, "globe_view", &label, "Whose borders the sample countries and the basemap outline show.", move |ui, app| { - if ui.selectable_label(auto, tl!("Automatic (system time zone and region)")).clicked() { - let _ = app.run("ui.worldview", json!({"worldview": crate::i18n::AUTO})); - ui.close(); + // Looked up only while the menu is open: `auto` reads the system's time zone and locale. + let wanted = crate::worldviewui::wanted(app); + ui.label(egui::RichText::new(tl!("Detail")).small().weak()); + for (d, text, tip) in [ + (Detail::Simplified, tl!("Simplified"), tl!("Borders at 1:110m, a small download (about 250 KB)")), + ( + Detail::Original, + tl!("Original"), + tl!("Natural Earth's 1:10m borders with every island, a larger download (about 3 MB, 10 MB unpacked)"), + ), + ] { + if ui.selectable_label(wanted.detail == d, text).on_hover_text(tip).clicked() { + let _ = app.run("ui.worldview", json!({"detail": d.code()})); + } } ui.separator(); - for w in [Worldview::Default, Worldview::China] { - if ui.selectable_label(!auto && w == current, name(w)).clicked() { - let _ = app.run("ui.worldview", json!({"worldview": w.code()})); - ui.close(); + let detail = Detail::from_code(&app.ui.worldview_detail).unwrap_or_default(); + egui::ScrollArea::vertical().max_height(ui.ctx().content_rect().height() * 0.6).show(ui, |ui| { + for w in Worldview::all() { + let text = if sample::text(View::new(w, detail)).is_some() { + name(w).to_string() + } else { + crate::i18n::fmt("{name} (download)", &[("name", name(w))]) + }; + if ui.selectable_label(w == wanted.worldview, text).clicked() { + let _ = app.run("ui.worldview", json!({"worldview": w.code()})); + ui.close(); + } + if w.built_in() { + ui.separator(); + } } - } + }); }); } diff --git a/crates/ui-egui/src/worldviewui.rs b/crates/ui-egui/src/worldviewui.rs new file mode 100644 index 0000000000..ad257233ff --- /dev/null +++ b/crates/ui-egui/src/worldviewui.rs @@ -0,0 +1,236 @@ +//! The worldview: whose borders the built-in countries and the basemap's world outline show +//! (Settings › Language › Worldview). The default is built in; every other one is downloaded when +//! it is chosen (or, for China, when the system calls for it), off the frame through the tile +//! cache's downloads (a thread natively, fetch on the web), and kept in the cache folder. + +use rustgis_engine::sample::{self, View, Worldview}; + +use crate::{RustGisApp, Slot, i18n}; + +/// A worldview's name in the interface language. +pub fn name(w: Worldview) -> &'static str { + match w.name() { + "Default" => tl!("Default"), + "Argentina" => tl!("Argentina"), + "Bangladesh" => tl!("Bangladesh"), + "Brazil" => tl!("Brazil"), + "China" => tl!("China"), + "Egypt" => tl!("Egypt"), + "France" => tl!("France"), + "Germany" => tl!("Germany"), + "Greece" => tl!("Greece"), + "India" => tl!("India"), + "Indonesia" => tl!("Indonesia"), + "Israel" => tl!("Israel"), + "Italy" => tl!("Italy"), + "Japan" => tl!("Japan"), + "Morocco" => tl!("Morocco"), + "Nepal" => tl!("Nepal"), + "Netherlands" => tl!("Netherlands"), + "Pakistan" => tl!("Pakistan"), + "Palestine" => tl!("Palestine"), + "Poland" => tl!("Poland"), + "Portugal" => tl!("Portugal"), + "Russia" => tl!("Russia"), + "Saudi Arabia" => tl!("Saudi Arabia"), + "South Korea" => tl!("South Korea"), + "Spain" => tl!("Spain"), + "Sweden" => tl!("Sweden"), + "Taiwan" => tl!("Taiwan"), + "Turkey" => tl!("Turkey"), + "Ukraine" => tl!("Ukraine"), + "United Kingdom" => tl!("United Kingdom"), + "United States" => tl!("United States"), + "Vietnam" => tl!("Vietnam"), + other => other, + } +} + +/// The download under way: the view and where its outcome lands. +pub struct Fetch { + pub wanted: View, + landing: Landing, +} + +/// Where a download lands: the bytes, from the services' fetch (checked here), or the outcome of +/// [`sample::fetch`], which checked them on its own thread. +enum Landing { + Bytes(Slot, String>>), + Done(Slot>), +} + +/// The worldview preference, with `auto` as the default one in tests (they don't depend on the +/// machine's time zone and locale). +fn pref(app: &RustGisApp) -> &str { + if cfg!(test) && app.ui.worldview == i18n::AUTO { "default" } else { app.ui.worldview.as_str() } +} + +/// The view the preferences ask for. +pub fn wanted(app: &RustGisApp) -> View { + sample::wanted_view(pref(app), &app.ui.worldview_detail) +} + +/// Applies the worldview preferences: shows the view if its countries are in memory, else gets +/// them (the kept copy or a download) and keeps the current borders until they arrive. An +/// untouched sample project's countries follow. +pub fn apply(app: &mut RustGisApp) { + let before = sample::view(); + let wanted = sample::apply_view(pref(app), &app.ui.worldview_detail); + let after = sample::view(); + if after != before { + if !sample::swap_countries(&mut app.session, before, after) && sample::holds_countries(&app.session, before) { + // The project has changes or is saved: its sample countries stay as they are. + app.session.notify( + i18n::fmt( + "The basemap now shows the {view} worldview; the project's Countries layer keeps its borders", + &[("view", name(after.worldview))], + ), + false, + ); + } + app.map.invalidate(); + } + if after == wanted { + app.ui.worldview_fetch = None; + } else if app.ui.worldview_fetch.as_ref().is_none_or(|f| f.wanted != wanted) { + start(app, wanted); + } +} + +/// Starts getting a view's countries. +fn start(app: &mut RustGisApp, wanted: View) { + let landing = match (&app.services.fetch, wanted.url()) { + (Some(fetch), Some(url)) => { + let slot = Slot::default(); + fetch(&url, slot.clone()); + Landing::Bytes(slot) + } + _ => { + let slot: Slot> = Slot::default(); + let land = slot.clone(); + sample::fetch(wanted, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); + Landing::Done(slot) + } + }; + app.ui.worldview_fetch = Some(Fetch { wanted, landing }); +} + +/// The worldview being downloaded, if any (the ribbon says so). +pub fn downloading(app: &RustGisApp) -> Option { + app.ui.worldview_fetch.as_ref().map(|f| f.wanted.worldview) +} + +/// Lands a download: shows the view if it is still the one asked for, or says why it can't. +pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { + let Some(fetch) = &app.ui.worldview_fetch else { return }; + let wanted = fetch.wanted; + let landed = match &fetch.landing { + Landing::Bytes(slot) => slot.lock().unwrap_or_else(|e| e.into_inner()).take().map(|r| r.and_then(|b| sample::accept(wanted, b))), + Landing::Done(slot) => slot.lock().unwrap_or_else(|e| e.into_inner()).take(), + }; + let Some(r) = landed else { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + }; + app.ui.worldview_fetch = None; + match r { + Ok(()) => apply(app), + Err(e) => { + let text = i18n::fmt( + "Couldn't download the {view} worldview ({error}); the map keeps the {current} borders", + &[("view", name(wanted.worldview)), ("error", &e), ("current", name(sample::worldview()))], + ); + app.session.notify(text, true); + } + } + ctx.request_repaint(); +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// An app whose downloads all end the way `answer` says, at once. + fn app_fetching(answer: impl Fn(&str) -> Result, String> + 'static) -> RustGisApp { + // Never the computer's own cache folder. + sample::keep_downloads(false); + let mut app = RustGisApp::with_sample(); + app.services.fetch = Some(Box::new(move |url: &str, slot: Slot, String>>| { + if let Ok(mut s) = slot.lock() { + *s = Some(answer(url)); + } + })); + app + } + + /// A worldview is downloaded only when it is chosen, from its own address, and kept as its code. + /// (The worldview shown is shared by every test in the process, so it isn't looked at here.) + #[test] + fn a_chosen_worldview_is_downloaded_then_kept() { + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::::new())); + let log = asked.clone(); + let mut app = app_fetching(move |url| { + log.borrow_mut().push(url.to_string()); + Ok(sample::COUNTRIES.as_bytes().to_vec()) + }); + let netherlands = Worldview::from_code("nld").unwrap(); + let nld = View::new(netherlands, sample::Detail::Simplified); + assert!(asked.borrow().is_empty(), "nothing is downloaded before a worldview is chosen"); + assert!(sample::text(nld).is_none()); + app.run("ui.worldview", json!({"worldview": "Netherlands"})).unwrap(); + assert_eq!(app.ui.worldview, "nld"); + assert_eq!(downloading(&app), Some(netherlands)); + assert_eq!(*asked.borrow(), ["https://data.source.coop/opengeos/data/rustgis/worldviews/countries_nld.geojson"]); + let mark = app.session.notice_mark(); + poll(&mut app, &egui::Context::default()); + assert!(app.session.notices_since(mark).is_empty()); + assert_eq!(downloading(&app), None); + assert!(sample::text(nld).is_some()); + // Choosing it again downloads nothing. + app.run("ui.worldview", json!({"worldview": "nld"})).unwrap(); + assert_eq!(asked.borrow().len(), 1); + assert_eq!(downloading(&app), None); + // Nor does the built-in default. + app.run("ui.worldview", json!({"worldview": "default"})).unwrap(); + assert_eq!(asked.borrow().len(), 1); + // The original detail is a download of its own, kept as a setting. + app.run("ui.worldview", json!({"worldview": "nld", "detail": "original"})).unwrap(); + assert_eq!(app.ui.worldview_detail, "original"); + assert_eq!( + asked.borrow().last().map(String::as_str), + Some("https://data.source.coop/opengeos/data/rustgis/worldviews/original/countries_nld.geojson.gz") + ); + poll(&mut app, &egui::Context::default()); + assert!(sample::text(View::new(netherlands, sample::Detail::Original)).is_some()); + // Back to simplified: already in memory, nothing downloaded. + app.run("ui.worldview", json!({"worldview": null, "detail": "simplified"})).unwrap(); + assert_eq!(asked.borrow().len(), 2); + assert_eq!(app.ui.worldview, "nld"); + assert!(app.run("ui.worldview", json!({"detail": "detailed"})).is_err()); + assert!(app.run("ui.worldview", json!({"worldview": "atlantis"})).is_err()); + assert!(app.run("ui.worldview", json!({"worldview": 7})).is_err()); + assert_eq!((app.ui.worldview.as_str(), app.ui.worldview_detail.as_str()), ("nld", "simplified")); + // The view shown is the process's: leave it as other tests expect. + sample::set_view(View::DEFAULT); + } + + /// A download that fails, or isn't countries, says so and keeps the borders shown. + #[test] + fn a_failed_worldview_download_is_told() { + for (code, answer) in [("pol", Err("HTTP 404".to_string())), ("prt", Ok(b"not found".to_vec()))] { + let mut app = app_fetching(move |_| answer.clone()); + let w = View::new(Worldview::from_code(code).unwrap(), sample::Detail::Simplified); + app.run("ui.worldview", json!({"worldview": code})).unwrap(); + let mark = app.session.notice_mark(); + poll(&mut app, &egui::Context::default()); + let told: Vec<_> = app.session.notices_since(mark).iter().map(|n| (n.text.clone(), n.error)).collect(); + assert_eq!(told.len(), 1, "{code}: {told:?}"); + assert!(told[0].1 && told[0].0.contains(w.worldview.name()) && told[0].0.contains("worldview"), "{told:?}"); + // Named once, by the notice: the download's error doesn't repeat it. + assert_eq!(told[0].0.matches("download").count(), 1, "{told:?}"); + assert!(sample::text(w).is_none()); + assert_eq!(downloading(&app), None); + } + } +} diff --git a/docs/cli.md b/docs/cli.md index 7d778e007f..9e12e2352e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -25,9 +25,18 @@ It defaults to 1600 × 900 pixels at 96 DPI; `--width`, `--height` and `--dpi` c A data file is zoomed to its full extent; a project keeps its saved view. `--tiles` accepts an XYZ template, vector tiles or a MapLibre-style address. -`--worldview auto|default|china` chooses the disputed borders in the built-in countries and -world outline, for `render`, `run` and the other subcommands. `auto` follows -`RUSTGIS_WORLDVIEW`, else the system time zone and locale. +`--worldview auto|default|CODE` chooses the disputed borders in the built-in countries and +world outline, for `render`, `run`, `ask` and `mcp`: the default borders, or a +[worldview](user-guide/maps.md#worldview)'s code, such as `chn`, `ind` or `usa`. A worldview +other than the default is downloaded once and kept in the cache folder; if the download fails, +a named one is an error. `auto` follows `RUSTGIS_WORLDVIEW`, else the system time zone and +locale (China's view in mainland China, falling back to the default borders with a warning when +it can't be downloaded). `--worldview-detail simplified|original` chooses how detailed: the +simplified borders (the default, about 250 KB) or Natural Earth's 1:10m ones (a 3 MB download), +which `--worldview default` also downloads. Given explicitly, it makes a failed download an +error even with `auto`. Nothing is downloaded by `ask`'s model and sign-in options, by `ask` +with no request unless it reads or saves a project (with `--account` and no request, not even +then), nor by `mcp --attach`. `--threads N` sets the most threads one piece of work uses (1 to 1024, never more than the cores), as [`gp.threads`](user-guide/analysis.md#analysis-workflows) sets it. With `mcp --attach` the diff --git a/docs/installation.md b/docs/installation.md index 49ca95b333..ebcc3d7985 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -105,8 +105,7 @@ cargo build --release -p rustgis-cli # the command-line tool The build downloads the Natural Earth sample data from [rustgis-assets](https://github.com/opengeos/rustgis-assets). To build offline, download -`countries.geojson`, `countries_chn.geojson`, `cities.geojson`, `rivers.geojson` and -`lakes.geojson` from `https://assets.rustgis.app/data/` once and point the build at them: +`countries.geojson`, `cities.geojson`, `rivers.geojson` and `lakes.geojson` from `https://assets.rustgis.app/data/` once and point the build at them: ```sh RUSTGIS_DATA_DIR=/path/to/data cargo build --release diff --git a/docs/privacy.md b/docs/privacy.md index ad52308259..e169950574 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -67,6 +67,11 @@ still identify private data, so review copied diagnostics before sharing them. `data:image/…` value) needs no request. A fetched picture is kept in memory for the session, or until a sign-out or a login that ends clears the cached web tiles; the web app also uses the browser's own cache. Links in the pop-up open only when you click them. +- Choosing a worldview other than the default, or the original detail, in **Settings › + Language › Worldview** downloads its borders from source.coop (`data.source.coop`, the `opengeos/data` repository), + once on the desktop (they are kept in the cache folder) and once a session in the web app. + Until you choose one, a system whose time zone or language is mainland China's downloads + China's view the same way. - Web data, remote rasters, cloud storage, database connections and online catalogs contact their configured servers. Searches may send keywords, coordinates, an area of interest, dates or filters; authenticated connections also send the credentials or tokens required by diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 6762b615a0..b47239c431 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -471,13 +471,28 @@ taking other bodies' basemaps off) and `map.bodies`. ### Worldview -The world outline and the World Atlas sample's countries come in two worldviews: Natural -Earth's default borders, and China's (Natural Earth's China point of view: Taiwan, Aksai Chin -and South Tibet are part of China). RustGIS picks China's when the system's time zone is -mainland China's (such as `Asia/Shanghai`) or its first locale is `zh-CN`; nothing is looked up -over the network. Choose one in **Settings › Language › Worldview**, set `RUSTGIS_WORLDVIEW` -(`default` or `china`), or pass `--worldview` to `rustgis-cli`. An untouched sample project -switches its countries at once; others keep the layer they have. +The world outline and the World Atlas sample's countries show Natural Earth's default (de facto) +borders, which are built in, or the borders as one of 31 countries sees them: Natural Earth's +[points of view](https://www.naturalearthdata.com/blog/admin-0-countries-point-of-views/), from +Argentina to Vietnam. Choose one in **Settings › Language › Worldview**, set `RUSTGIS_WORLDVIEW` +to its code (such as `chn`, `ind` or `usa`), or pass `--worldview` to `rustgis-cli`. + +A point of view isn't part of the app: it is downloaded from +[source.coop](https://source.coop/opengeos/data/rustgis/worldviews) when you choose it, and the +desktop app and the command line keep it in the cache folder, so it is downloaded once; the web +app downloads it again in each session. **Detail**, at the top of the same menu, sets how much: + +- **Simplified** (the default): borders at 1:110m, like the built-in ones; about 250 KB. +- **Original**: Natural Earth's 1:10m borders with every island and territory; a 3 MB download, + 10 MB once unpacked, so maps with it draw more slowly. With the default worldview, this + downloads the detailed version of the built-in borders. + +`rustgis-cli` takes `--worldview-detail original`. The map keeps the borders it shows until the +download arrives, and says so if it fails. Until +you choose one, RustGIS shows China's view when the system's time zone is mainland China's +(such as `Asia/Shanghai`) or its first locale is `zh-CN`, downloading it the same way, and the +default borders everywhere else. Your choice is kept for the next start. An untouched sample +project switches its countries when the new borders arrive; others keep the layer they have. ## Projections