diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 474c845b60..cd311afe5d 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -294,16 +294,25 @@ fn uninstall_geolibre_language(_s: &mut Session, p: &Value) -> CmdResult { } /// Downloads and installs the pinned GeoLibre runner release for this platform; returns the -/// program's path. `progress` gets the bytes received and the expected total. Blocks: the app -/// calls it from a background thread, then picks the runner with `gp.setGeolibre`. Native only. +/// program's path. `progress` gets the bytes received and the expected total. This blocking path +/// serves `gp.installGeolibre` and scripts; the desktop card uses [`install_geolibre_cancellable`] +/// on a background thread. Native only. pub fn install_geolibre(progress: &dyn Fn(u64, Option)) -> Result { + install_geolibre_cancellable(progress, &std::sync::atomic::AtomicBool::new(false)) +} + +/// The desktop card's background install path: checks Cancel between download chunks, before +/// extraction and before publication. A blocked HTTP read finishes or times out first. Checksum +/// verification, extraction, runner lookup and version probing have no internal Cancel checks; +/// cancellation waits for those steps to finish. +pub fn install_geolibre_cancellable(progress: &dyn Fn(u64, Option), cancel: &std::sync::atomic::AtomicBool) -> Result { #[cfg(all(feature = "geolibre", not(target_arch = "wasm32")))] { - rustgis_geolibre::install::install(progress).map(|p| p.display().to_string()) + rustgis_geolibre::install::install_cancellable(progress, cancel).map(|p| p.display().to_string()) } #[cfg(not(all(feature = "geolibre", not(target_arch = "wasm32"))))] { - let _ = progress; + let _ = (progress, cancel); Err("this build can't install the GeoLibre runner".into()) } } diff --git a/crates/engine/src/grids.rs b/crates/engine/src/grids.rs index f9b5108e2e..50b44e1f68 100644 --- a/crates/engine/src/grids.rs +++ b/crates/engine/src/grids.rs @@ -48,12 +48,21 @@ pub enum News { Got { name: String, bytes: usize }, /// A grid couldn't be had, and why. Failed { name: String, error: String }, + /// A contiguous batch ended; failures have their own notices. + Finished { grids: usize, bytes: u64 }, /// News a session asked for too late to hear, counted ([`news_since`]). Missed(u64), } #[derive(Default)] struct State { + /// Byte counter shared with the download transport, retained until this batch ends. + progress: std::sync::Arc, + batch_active: bool, + batch_total: usize, + batch_done: usize, + batch_got: usize, + batch_bytes: u64, /// Grids being downloaded now. busy: HashSet, /// Grids whose download failed this run: not tried again until the setting is turned on again. @@ -104,6 +113,37 @@ impl State { out } + /// Records a settled download before waking readers, including its final batch summary. + fn finish(&mut self, name: &str, outcome: Result) { + self.busy.remove(name); + self.batch_done += 1; + match outcome { + Ok(bytes) => { + self.bytes += bytes; + self.batch_got += 1; + self.batch_bytes += bytes as u64; + self.got.insert(name.to_string()); + self.tell(News::Got { name: name.to_string(), bytes }); + } + Err(error) => { + self.failed.insert(name.to_string()); + self.tell(News::Failed { name: name.to_string(), error }); + } + } + self.running = self.running.saturating_sub(1); + self.finish_batch(); + } + + /// Ends a batch only after every queued or running grid has settled. + fn finish_batch(&mut self) { + if self.batch_active && self.busy.is_empty() { + self.batch_active = false; + if self.batch_got > 0 { + self.tell(News::Finished { grids: self.batch_got, bytes: self.batch_bytes }); + } + } + } + /// The setting turned on: this run's failures are tried again, and the limits start over. fn turned_on(&mut self) { self.turns += 1; @@ -159,6 +199,13 @@ pub fn enabled() -> bool { ENABLED.load(Ordering::SeqCst) } +/// Current batch progress: settled grids, total grids, bytes received, and whether it is active. +/// Native downloads count bytes as they arrive; browser downloads count them on completion. +pub fn progress() -> (usize, usize, u64, bool) { + let s = lock(); + (s.batch_done, s.batch_total, s.progress.received().max(s.batch_bytes), s.batch_active) +} + /// How many times downloads were turned on this run: a download said before is said again after. pub fn turns() -> u64 { lock().turns @@ -260,6 +307,7 @@ fn next() { let Some(grid) = grid else { break }; start(grid); } + lock().finish_batch(); // Those dropped or refused on the way: their waiters see it. state().1.notify_all(); } @@ -312,6 +360,15 @@ impl State { self.tell(News::Failed { name: name.to_string(), error }); return Claim::Settled; } + if !self.batch_active { + self.batch_active = true; + self.batch_total = 0; + self.batch_done = 0; + self.batch_got = 0; + self.batch_bytes = 0; + self.progress = Default::default(); + } + self.batch_total += 1; self.started += 1; self.busy.insert(name.to_string()); Claim::Mine @@ -326,8 +383,10 @@ impl State { if !on { self.busy.remove(&grid.name); self.started = self.started.saturating_sub(1); + self.batch_total = self.batch_total.saturating_sub(1); } else if self.bytes >= MAX_BYTES { self.busy.remove(&grid.name); + self.batch_done += 1; self.failed.insert(grid.name.clone()); self.tell(News::Failed { name: grid.name, error: limit_text() }); } else { @@ -365,19 +424,7 @@ fn limit_text() -> String { /// Records how `name`'s download went, and wakes those waiting for it. fn finish(name: &str, outcome: Result) { let mut s = lock(); - s.busy.remove(name); - match outcome { - Ok(bytes) => { - s.bytes += bytes; - s.got.insert(name.to_string()); - s.tell(News::Got { name: name.to_string(), bytes }); - } - Err(error) => { - s.failed.insert(name.to_string()); - s.tell(News::Failed { name: name.to_string(), error }); - } - } - s.running = s.running.saturating_sub(1); + s.finish(name, outcome); drop(s); state().1.notify_all(); rustgis_map::source::wake(); @@ -545,7 +592,8 @@ fn start(grid: MissingGrid) { fn fetch_now(grid: &MissingGrid) { let got = std::panic::catch_unwind(|| { let download = *download().read().unwrap_or_else(|e| e.into_inner()); - let bytes = download(&grid.url, MAX_GRID, DOWNLOAD_TIMEOUT)?; + let progress = lock().progress.clone(); + let bytes = crate::render::rustgis_tiles::cache::with_progress(Some(progress), || download(&grid.url, MAX_GRID, DOWNLOAD_TIMEOUT))?; keep(&grid.name, &bytes).map(|()| bytes.len()) }) .unwrap_or_else(|payload| Err(crate::bug("the download", payload.as_ref()))); @@ -634,8 +682,8 @@ pub fn news_texts(news: &[News]) -> Vec<(String, bool)> { let mut count = 0; for n in news { match n { - News::Missed(_) => {} - News::Got { name, bytes } => got.push(format!("{name} ({})", size_text(*bytes))), + News::Missed(_) | News::Finished { .. } => {} + News::Got { name, bytes } => got.push(format!("{name} ({})", size_text(*bytes as u64))), News::Failed { name, error } => { count += 1; match why.iter_mut().find(|(e, _)| e == error) { @@ -683,15 +731,44 @@ pub fn news_texts(news: &[News]) -> Vec<(String, bool)> { out } -fn size_text(bytes: usize) -> String { - let mb = bytes as f64 / 1_000_000.0; - if mb >= 1.0 { format!("{mb:.1} MB") } else { format!("{} KB", bytes.div_ceil(1000)) } +/// Download sizes in decimal units; rounding small amounts up keeps received bytes visible. +/// Accepts the batch counters directly without narrowing them through `usize`. +pub fn size_text(bytes: u64) -> String { + let kb = bytes.div_ceil(1000); + if kb < 1000 { format!("{kb} KB") } else { format!("{:.1} MB", bytes as f64 / 1_000_000.0) } } #[cfg(test)] mod tests { use super::*; + /// A completion is emitted once per batch, after its last grid settles, with only + /// successfully retained bytes counted; a later batch starts with fresh counters. + #[test] + fn batch_summary_waits_for_all_grids_and_counts_successes() { + let mut s = State::default(); + assert!(matches!(s.claim("a.tif", true), Claim::Mine)); + assert!(matches!(s.claim("b.tif", true), Claim::Mine)); + s.finish("a.tif", Ok(123_456)); + assert_eq!(s.news_since(&mut 0), [News::Got { name: "a.tif".into(), bytes: 123_456 }]); + s.finish("b.tif", Err("HTTP 404".into())); + s.finish_batch(); + assert_eq!( + s.news_since(&mut 0), + [ + News::Got { name: "a.tif".into(), bytes: 123_456 }, + News::Failed { name: "b.tif".into(), error: "HTTP 404".into() }, + News::Finished { grids: 1, bytes: 123_456 } + ] + ); + assert!(!s.batch_active); + assert!(matches!(s.claim("c.tif", true), Claim::Mine)); + assert_eq!((s.batch_total, s.batch_done, s.batch_got, s.batch_bytes), (1, 0, 0, 0)); + let mut seen = s.told; + s.finish("c.tif", Err("HTTP 404".into())); + assert_eq!(s.news_since(&mut seen), [News::Failed { name: "c.tif".into(), error: "HTTP 404".into() }]); + } + #[test] fn only_plain_names_are_kept() { assert!(plain("us_noaa_conus.tif")); @@ -828,5 +905,11 @@ mod tests { ); assert_eq!(said[0].0.matches("at most 16").count(), 1, "{said:?}"); assert_eq!(size_text(12_345_678), "12.3 MB"); + assert_eq!(size_text(13_442), "14 KB"); + assert_eq!(size_text(999_000), "999 KB"); + assert_eq!(size_text(999_999), "1.0 MB"); + assert_eq!(size_text(1), "1 KB"); + assert_eq!(size_text(0), "0 KB"); + assert_eq!(size_text(5_000_000_000), "5000.0 MB"); } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 18464859e9..a5d55f5d4c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3002,6 +3002,15 @@ impl Session { self.notify(text, error); } for n in &news { + if let crate::grids::News::Finished { grids, bytes } = n { + self.notify_text( + crate::notice_text::NoticeText::format( + if *grids == 1 { "Downloaded {count} datum grid, {size}" } else { "Downloaded {count} datum grids, {size}" }, + [("count", grids.to_string().into()), ("size", crate::grids::size_text(*bytes).into())], + ), + false, + ); + } // Its download is over: one tried again (the setting turned on again) is said again. if let crate::grids::News::Got { name, .. } | crate::grids::News::Failed { name, .. } = n { self.grid_downloads_said.remove(name); diff --git a/crates/engine/tests/datum_grid_downloads.rs b/crates/engine/tests/datum_grid_downloads.rs index bd952ba3c4..aa7d71fddf 100644 --- a/crates/engine/tests/datum_grid_downloads.rs +++ b/crates/engine/tests/datum_grid_downloads.rs @@ -67,6 +67,7 @@ fn a_read_waits_for_the_grids_its_system_needs() { assert_eq!(ASKED.load(Ordering::SeqCst), 0); // On: the read gets both grids first, keeps them, and its features land where they put them. + let mut download_notices = Session::new(Project::default()); grids::set_enabled(true); let t = crs::waiting_for_grids(|| texas.transformer()).unwrap(); assert!(close(t.to_lonlat(at).unwrap(), (-99.00031395482138, 29.208749002954207)), "{:?}", t.to_lonlat(at)); @@ -80,9 +81,23 @@ fn a_read_waits_for_the_grids_its_system_needs() { news.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); assert_eq!( news, - [News::Got { name: "us_noaa_conus.tif".into(), bytes: 173_029 }, News::Got { name: "us_noaa_ethpgn.tif".into(), bytes: 13_442 }] + [ + News::Finished { grids: 2, bytes: 186_471 }, + News::Got { name: "us_noaa_conus.tif".into(), bytes: 173_029 }, + News::Got { name: "us_noaa_ethpgn.tif".into(), bytes: 13_442 } + ] ); assert!(crs::missing_grids(texas).is_empty()); + download_notices.notice_landed_rasters(); + assert_eq!( + download_notices + .notices + .iter() + .filter(|n| n.text.starts_with("Downloaded 2 datum grids")) + .map(|n| (n.text.as_str(), n.error)) + .collect::>(), + [("Downloaded 2 datum grids, 187 KB", false)] + ); // Read again, nothing more is asked for. let _ = crs::waiting_for_grids(|| texas.transformer()).unwrap(); assert_eq!(ASKED.load(Ordering::SeqCst), 2); @@ -238,4 +253,19 @@ fn a_read_waits_for_the_grids_its_system_needs() { } grids::set_enabled(false); MODE.store(GRIDS, Ordering::SeqCst); + // This binary owns the process-wide grid news: exercise a small singular completion through + // the real session landing, once despite repeated frames, without another network request. + let mut summary = Session::new(Project::default()); + grids::tell(News::Finished { grids: 1, bytes: 13_442 }); + summary.notice_landed_rasters(); + summary.notice_landed_rasters(); + assert_eq!( + summary + .notices + .iter() + .filter(|n| n.text.starts_with("Downloaded 1 datum grid")) + .map(|n| (n.text.as_str(), n.error)) + .collect::>(), + [("Downloaded 1 datum grid, 14 KB", false)] + ); } diff --git a/crates/geolibre/src/install.rs b/crates/geolibre/src/install.rs index e3c9c6fb66..3e02c113c1 100644 --- a/crates/geolibre/src/install.rs +++ b/crates/geolibre/src/install.rs @@ -10,6 +10,7 @@ use std::io::Read; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use serde_json::Value; use sha2::{Digest, Sha256}; @@ -78,17 +79,28 @@ fn find_asset(agent: &ureq::Agent, target: &str) -> Result<(String, String, Stri /// Downloads the runner, checks it and installs it; returns the installed program. `progress` /// gets the bytes received and the expected total. pub fn install(progress: &dyn Fn(u64, Option)) -> Result { + install_cancellable(progress, &AtomicBool::new(false)) +} + +/// Installs as [`install`], checking Cancel between download chunks and before publication. +/// A blocked HTTP read finishes or times out before Cancel can be observed. Checksum verification, +/// archive extraction, runner lookup and the version probe each run as a single step without +/// internal Cancel checks; cancellation is observed after those steps finish. +pub fn install_cancellable(progress: &dyn Fn(u64, Option), cancel: &AtomicBool) -> Result { + check_cancel(cancel)?; let target = target().ok_or("there is no GeoLibre runner for this platform")?; let dir = install_dir().ok_or("can't find a folder to install the GeoLibre runner in")?; let agent = agent(); let (tag, name, archive_url, sums_url) = find_asset(&agent, target)?; + check_cancel(cancel)?; let sums = get(&agent, &sums_url)?.body_mut().read_to_string().map_err(|e| e.to_string())?; let expected = sums.split_whitespace().next().unwrap_or("").to_ascii_lowercase(); if expected.len() != 64 || !expected.bytes().all(|b| b.is_ascii_hexdigit()) { return Err(format!("{name}: unreadable checksum")); } + check_cancel(cancel)?; let mut resp = get(&agent, &archive_url)?; let total = resp.body().content_length(); if total.is_some_and(|t| t > MAX_BYTES) { @@ -98,6 +110,7 @@ pub fn install(progress: &dyn Fn(u64, Option)) -> Result { let mut bytes = Vec::with_capacity(total.unwrap_or(0).min(MAX_BYTES) as usize); let mut buf = vec![0u8; 256 * 1024]; loop { + check_cancel(cancel)?; let n = reader.read(&mut buf).map_err(|e| format!("{name}: {e}"))?; if n == 0 { break; @@ -108,6 +121,7 @@ pub fn install(progress: &dyn Fn(u64, Option)) -> Result { } progress(bytes.len() as u64, total); } + check_cancel(cancel)?; let actual: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); if actual != expected { return Err(format!("{name}: the download doesn't match its published checksum")); @@ -118,21 +132,29 @@ pub fn install(progress: &dyn Fn(u64, Option)) -> Result { let staging = dir.join(format!(".download-{}", std::process::id())); let _ = std::fs::remove_dir_all(&staging); std::fs::create_dir_all(&staging).map_err(|e| format!("{}: {e}", staging.display()))?; - let unpacked = unpack(&bytes, target, &staging); + let unpacked = check_cancel(cancel).and_then(|()| unpack(&bytes, target, &staging)); let exe_name = if target.contains("windows") { "geolibre.exe" } else { "geolibre" }; let found = unpacked.and_then(|_| find_file(&staging, exe_name, 3).ok_or_else(|| format!("{name} has no {exe_name}"))); - let result = found.and_then(|exe| put_in_place(&exe, &dir.join(exe_name), &tag)); + let result = found.and_then(|exe| put_in_place(&exe, &dir.join(exe_name), &tag, cancel)); let _ = std::fs::remove_dir_all(&staging); result } +/// Cancellation never promotes a partial or staged runner to the installed path. +/// The stable error text identifies cancellation to callers of this string-error API. +fn check_cancel(cancel: &AtomicBool) -> Result<(), String> { + if cancel.load(Ordering::Relaxed) { Err("GeoLibre installation cancelled".into()) } else { Ok(()) } +} + /// Moves the unpacked runner `exe` to `dest`, replacing an installed one, but only once `exe` /// starts and reports a supported version ([`crate::runner::check_supported`]): a download that /// doesn't is refused and an installed runner is left as it was. -fn put_in_place(exe: &Path, dest: &Path, tag: &str) -> Result { +fn put_in_place(exe: &Path, dest: &Path, tag: &str, cancel: &AtomicBool) -> Result { + check_cancel(cancel)?; make_executable(exe)?; let version = crate::runner::version_of(exe).ok_or_else(|| format!("the downloaded {tag} runner doesn't start"))?; crate::runner::check_supported(&format!("the downloaded {tag} runner"), &version)?; + check_cancel(cancel)?; // Replace an older install without ever losing it: set it aside, move the new one in, and // put the old one back if that fails. let old = dest.with_file_name(format!("{}.old", crate::runner::exe_name())); @@ -245,12 +267,15 @@ mod tests { let staged = tmp.0.join("staged"); for (line, says) in [(Some("geolibre-cli 2.0.0"), "2.0.0"), (None, "doesn't start"), (Some("geolibre-cli soon"), "can't read")] { fake(&staged, line).unwrap(); - let e = put_in_place(&staged, &dest, "v1.8.0").unwrap_err(); + let e = put_in_place(&staged, &dest, "v1.8.0", &AtomicBool::new(false)).unwrap_err(); assert!(e.contains("the downloaded v1.8.0 runner") && e.contains(says), "{e}"); assert_eq!(crate::runner::version_of(&dest).as_deref(), Some("geolibre-cli 1.8.0"), "the installed runner is kept"); } fake(&staged, Some("geolibre-cli 1.8.1")).unwrap(); - assert_eq!(put_in_place(&staged, &dest, "v1.8.1").unwrap(), dest); + assert_eq!(put_in_place(&staged, &dest, "v1.8.1", &AtomicBool::new(true)).unwrap_err(), "GeoLibre installation cancelled"); + assert_eq!(crate::runner::version_of(&dest).as_deref(), Some("geolibre-cli 1.8.0")); + assert!(staged.exists()); + assert_eq!(put_in_place(&staged, &dest, "v1.8.1", &AtomicBool::new(false)).unwrap(), dest); assert_eq!(crate::runner::version_of(&dest).as_deref(), Some("geolibre-cli 1.8.1")); assert!(!staged.exists() && !tmp.0.join(format!("{}.old", crate::runner::exe_name())).exists()); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6415f43dfd..034179d13d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7471,6 +7471,7 @@ impl RustGisApp { self.fonts_pending = false; i18n::set_current(self.lang()); rustgis_engine::plugins::set_language(self.lang().code()); + panes::poll_geolibre_install(self, ctx); panes::poll_geolibre(self, ctx); panes::poll_plugin_run(self, ctx); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index cd80a89420..9f1e7546b6 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -3082,6 +3082,8 @@ pub struct GpForm { pub coordinate_fields: Option<((u64, String, Option), Vec)>, /// A GeoLibre runner install in progress (it runs on a background thread). pub install: Option>>, + /// Why installing or loading the GeoLibre runner failed, independent of tool-run feedback. + pub install_error: Option, /// The browser's GeoLibre tools loading. pub web_load: Option>>, /// A tool running in the browser's GeoLibre runner: its run id, and where the result lands. @@ -3267,6 +3269,7 @@ pub fn start_geolibre_load(app: &mut RustGisApp) { return; } let Some(load) = &app.services.geolibre_manifests else { return }; + app.gp.install_error = None; let slot = crate::Slot::default(); load(slot.clone()); app.gp.web_load = Some(slot); @@ -3283,11 +3286,16 @@ pub fn poll_geolibre(app: &mut RustGisApp, ctx: &egui::Context) { app.gp.web_load = None; match r.and_then(|json| rustgis_engine::cmd::gp::external_load_manifests(&json)) { Ok(_) => { + app.gp.install_error = None; if let Some(save) = &app.services.save_pref { save("geolibre_web", "on"); } } - Err(e) => app.gp.last = Some((false, vec![e])), + Err(e) => { + let error = Session::redacted(&e); + app.gp.install_error = Some(error.as_str().to_string()); + app.session.notify_redacted(error, true); + } } } if let Some((id, tool, out)) = app.gp.web_run.as_ref().and_then(|(id, tool, slot)| take(slot).map(|o| (*id, *tool, o))) { @@ -3303,6 +3311,7 @@ pub fn poll_geolibre(app: &mut RustGisApp, ctx: &egui::Context) { /// Progress of a one-click GeoLibre runner install. #[derive(Default)] pub struct Install { + pub cancel: std::sync::Arc, pub done: u64, pub total: Option, /// The installed program, or why it failed; set when the install ends. @@ -3502,6 +3511,64 @@ fn no_geolibre_here(ui: &mut Ui, t: &Tokens) { ); } +/// Collects an install even when the Tools pane is closed. Preferences belong to the +/// application, so completion is independent of which project is currently open. +/// Installer feedback never replaces the result of a tool run. +pub(crate) fn poll_geolibre_install(app: &mut RustGisApp, ctx: &egui::Context) { + // An install that just finished: use the runner, and remember it. + let finished = app.gp.install.as_ref().and_then(|st| { + let mut st = st.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + st.result.take() + }); + if let Some(result) = finished { + app.gp.install = None; + // The worker's cancellation result is distinct from a failure followed by a late click. + if result.as_ref().is_err_and(|error| error == "GeoLibre installation cancelled") { + app.session.notify(tl!("GeoLibre installation cancelled"), false); + app.gp.install_error = None; + return; + } + let mark = app.session.notice_mark(); + match result.and_then(|path| app.run("gp.setGeolibre", json!({"path": path})).map(|_| path)) { + Ok(path) => { + if let Some(save) = &app.services.save_pref { + save("geolibre_runner", &path); + } + app.gp.install_error = None; + let count = rustgis_engine::cmd::gp::geolibre_status()["tools"].as_u64().unwrap_or(0); + let key = if count == 1 { "GeoLibre tool installed: {count} tool" } else { "GeoLibre tools installed: {count} tools" }; + app.session.notify(crate::i18n::fmt(key, &[("count", &count.to_string())]), false); + } + Err(e) => { + app.command_failed("gp.installGeolibre", &e, mark); + app.gp.install_error = Some(Session::redacted(&e).as_str().to_string()); + } + } + } + if app.gp.install.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } +} + +/// Draws the running install's received bytes and acknowledges Cancel while a read unwinds. +fn geolibre_install_progress(ui: &mut Ui, install: &std::sync::Mutex) { + let (done, total, cancel) = { + let st = install.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + (st.done, st.total, st.cancel.clone()) + }; + let cancelled = cancel.load(std::sync::atomic::Ordering::Relaxed); + let text = crate::i18n::fmt( + if cancelled { "Cancelling… {size}" } else { "Downloading… {size}" }, + &[("size", &rustgis_engine::grids::size_text(done))], + ); + let bar = egui::ProgressBar::new(total.map(|t| done as f32 / t.max(1) as f32).unwrap_or(0.0)).text(text); + ui.add(if total.is_some() { bar } else { bar.animate(true) }); + if ui.add_enabled(!cancelled, egui::Button::new(tl!("Cancel"))).clicked() { + cancel.store(true, std::sync::atomic::Ordering::Relaxed); + } + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); +} + /// Where to get the GeoLibre tools when the runner isn't installed (desktop and CLI builds only). fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { // Read directly, not through Session::run: a command each frame would bump the session's @@ -3515,21 +3582,6 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } return; } - // An install that just finished: use the runner, and remember it. - let finished = app.gp.install.as_ref().and_then(|st| st.lock().unwrap_or_else(std::sync::PoisonError::into_inner).result.take()); - if let Some(result) = finished { - app.gp.install = None; - match result.and_then(|path| app.run("gp.setGeolibre", json!({"path": path})).map(|_| path)) { - Ok(path) => { - if let Some(save) = &app.services.save_pref { - save("geolibre_runner", &path); - } - app.gp.last = None; - } - Err(e) => app.gp.last = Some((false, vec![e])), - } - return; - } if status["web"] == true { geolibre_web_card(app, ui, t); return; @@ -3563,30 +3615,26 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { ); geolibre_passed_over(app, ui, t, true); ui.add_space(6.0); - let progress = app.gp.install.as_ref().and_then(|st| st.lock().ok().map(|s| (s.done, s.total))); - match progress { - Some((done, total)) => { - let mb = |b: u64| format!("{:.1}", b as f64 / 1_048_576.0); - let text = crate::i18n::fmt("Downloading… {mb} MB", &[("mb", &mb(done))]); - let bar = egui::ProgressBar::new(total.map(|t| done as f32 / t.max(1) as f32).unwrap_or(0.0)).text(text); - ui.add(if total.is_some() { bar } else { bar.animate(true) }); - // Keep drawing while the download runs on its thread. - ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); - } + match &app.gp.install { + Some(install) => geolibre_install_progress(ui, install), None => { #[cfg(not(target_arch = "wasm32"))] if crate::widgets::primary_button(ui, tl!("Install Whitebox and GeoLibre tools"), true, vec2(0.0, 28.0)).clicked() { let st = std::sync::Arc::new(std::sync::Mutex::new(Install::default())); app.gp.install = Some(st.clone()); - app.gp.last = None; + app.gp.install_error = None; let ctx = ui.ctx().clone(); + let cancel = st.lock().unwrap_or_else(std::sync::PoisonError::into_inner).cancel.clone(); let spawned = std::thread::Builder::new().name("geolibre-install".into()).spawn(move || { - let result = rustgis_engine::cmd::gp::install_geolibre(&|done, total| { - if let Ok(mut s) = st.lock() { - s.done = done; - s.total = total; - } - }); + let result = rustgis_engine::cmd::gp::install_geolibre_cancellable( + &|done, total| { + if let Ok(mut s) = st.lock() { + s.done = done; + s.total = total; + } + }, + &cancel, + ); if let Ok(mut s) = st.lock() { s.result = Some(result); } @@ -3594,7 +3642,9 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }); if let Err(e) = spawned { app.gp.install = None; - app.gp.last = Some((false, vec![e.to_string()])); + let error = Session::redacted(&e.to_string()); + app.gp.install_error = Some(error.as_str().to_string()); + app.session.notify_redacted(error, true); } } ui.add_space(2.0); @@ -3620,18 +3670,16 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { if let Some(save) = &app.services.save_pref { save("geolibre_runner", &path); } - app.gp.last = None; + app.gp.install_error = None; } - Err(e) => app.gp.last = Some((false, vec![e])), + Err(e) => app.gp.install_error = Some(Session::redacted(&e).as_str().to_string()), } } }); } } - if let Some((false, msgs)) = &app.gp.last { - for m in msgs { - ui.label(egui::RichText::new(m).size(11.0).color(t.red)); - } + if let Some(error) = &app.gp.install_error { + ui.label(egui::RichText::new(error).size(11.0).color(t.red)); } }, ); @@ -3643,7 +3691,7 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { /// (`shown_below`), not when the Locate… error drawn below it already says it. fn geolibre_passed_over(app: &RustGisApp, ui: &mut Ui, t: &Tokens, shown_below: bool) { let Some(note) = rustgis_engine::cmd::gp::geolibre_passed_over() else { return }; - if shown_below && matches!(&app.gp.last, Some((false, msgs)) if msgs.contains(¬e)) { + if shown_below && app.gp.install_error.as_deref() == Some(note.as_str()) { return; } ui.add_space(4.0); @@ -3694,6 +3742,7 @@ fn geolibre_uninstall(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } } app.gp.uninstall_error = None; + app.gp.install_error = None; } Err(e) => app.gp.uninstall_error = Some(e), } @@ -3791,13 +3840,11 @@ fn geolibre_web_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { ui.label(egui::RichText::new(tl!("Loading the GeoLibre tools…")).size(11.5)); }); } else if crate::widgets::primary_button(ui, tl!("Load Whitebox and GeoLibre tools"), true, vec2(0.0, 28.0)).clicked() { - app.gp.last = None; + app.gp.install_error = None; start_geolibre_load(app); } - if let Some((false, msgs)) = &app.gp.last { - for m in msgs { - ui.label(egui::RichText::new(m).size(11.0).color(t.red)); - } + if let Some(error) = &app.gp.install_error { + ui.label(egui::RichText::new(error).size(11.0).color(t.red)); } }); } @@ -10621,3 +10668,97 @@ pub(crate) mod tests { assert!(h.query_by_role_and_label(Role::SpinButton, "Flat-area size").is_none(), "off again, no size"); } } + +#[cfg(test)] +mod install_completion_tests { + use super::*; + + /// The card's real progress control acknowledges a click before the worker finishes a read. + #[test] + fn install_cancel_shows_pending_state() { + use egui_kittest::kittest::{NodeT, Queryable}; + let install = std::sync::Arc::new(std::sync::Mutex::new(Install { done: 13_442, total: Some(20_000_000), ..Default::default() })); + let mut h = egui_kittest::Harness::builder() + .build_ui_state(|ui, st: &mut std::sync::Arc>| geolibre_install_progress(ui, st), install); + h.run(); + assert!(h.query_by_label("Downloading… 14 KB").is_some()); + h.get_by_label("Cancel").click(); + h.run(); + assert!(h.state().lock().unwrap().cancel.load(std::sync::atomic::Ordering::Relaxed)); + assert!(h.query_by_label("Cancelling… 14 KB").is_some()); + assert!(h.get_by_label("Cancel").accesskit_node().is_disabled()); + } + + /// An install completing in the frame loop cannot replace an open tool form's feedback. + #[test] + fn install_completion_preserves_open_tool_failure() { + use egui_kittest::kittest::Queryable; + for (text, error, web) in [ + ("fixture: install failed", true, false), + ("GeoLibre installation cancelled", false, false), + ("fixture: manifest failed", true, true), + ] { + let mut app = RustGisApp::new(Session::new(rustgis_engine::Project::default())); + app.gp.open(Some("buffer"), &app.session); + app.ui.right = Some(RightPane::Geoprocessing); + let tool_error = "fixture: buffer tool failed"; + app.gp.last = Some((false, vec![tool_error.into()])); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 860.0)).build_ui_state( + |ui, app: &mut RustGisApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run(); + assert!(h.query_by_label(tool_error).is_some(), "the open form shows its tool error"); + let mark = h.state().session.notice_mark(); + if web { + let slot = crate::Slot::default(); + *slot.lock().unwrap() = Some(Err(text.into())); + h.state_mut().gp.web_load = Some(slot); + } else { + h.state_mut().gp.install = + Some(std::sync::Arc::new(std::sync::Mutex::new(Install { result: Some(Err(text.into())), ..Default::default() }))); + } + h.step(); + assert!(h.state().gp.install.is_none() && h.state().gp.web_load.is_none(), "the normal frame collects install completion"); + assert_eq!(h.state().gp.last, Some((false, vec![tool_error.into()])), "install completion preserves the tool result"); + assert!(h.query_by_label(tool_error).is_some(), "the tool error remains visible"); + let notices = h.state().session.notices_since(mark); + assert_eq!(notices.iter().map(|n| (n.text.as_str(), n.error)).collect::>(), [(text, error)]); + } + } + + /// The normal frame, with Tools closed, preserves a worker failure after a late Cancel + /// request and reports genuine cancellation as information, each exactly once. + #[test] + fn closed_tools_pane_still_reports_install_failure() { + for (text, error) in [("fixture: truncated runner", true), ("GeoLibre installation cancelled", false)] { + let mut app = RustGisApp::new(Session::new(rustgis_engine::Project::default())); + app.ui.right = None; + app.gp.install = Some(std::sync::Arc::new(std::sync::Mutex::new(Install { + result: Some(Err(text.into())), + cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)), + ..Default::default() + }))); + let mark = app.session.notice_mark(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut RustGisApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.step(); + assert!(h.state().gp.install.is_none()); + assert_eq!(h.state().ui.right, None); + assert!(h.state().gp.last.is_none(), "install feedback belongs to the install card"); + assert_eq!(h.state().gp.install_error.is_some(), error, "the worker result determines whether a failure is retained"); + let notices = h.state().session.notices_since(mark); + assert_eq!(notices.iter().map(|n| (n.text.as_str(), n.error)).collect::>(), [(text, error)]); + h.step(); + assert_eq!(h.state().session.notices_since(mark).len(), 1); + } + } +} diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 2651d0a041..c0f4861cae 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -4106,21 +4106,31 @@ fn settings_tab(app: &mut RustGisApp, ui: &mut Ui) { }); group(ui, "Start-up", |ui| start_project_menu(app, ui)); group(ui, "Datum Grids", |ui| { - let mut on = app.ui.download_grids; - // The browser keeps what it downloads for the session; a computer, in a folder. - let tip = if cfg!(target_arch = "wasm32") { - tl!( - "When a coordinate system's most accurate datum transformation needs a grid RustGIS doesn't have, download it from PROJ's grid server (cdn.proj.org). Grids already downloaded stay in use for this session when this is off." - ) - } else { - tl!( - "When a coordinate system's most accurate datum transformation needs a grid RustGIS doesn't have, download it from PROJ's grid server (cdn.proj.org). Grids already downloaded stay in use when this is off: to stop using them, delete the datum-grids folder in RustGIS's app data and start RustGIS again (grids installed for PROJ are still used)." - ) - }; - let resp = ui.checkbox(&mut on, tl!("Download Datum Grids")).on_hover_text(tip); - if resp.clicked() { - let _ = app.run("ui.datumGrids", json!({"on": on})); - } + col(ui, |ui| { + let mut on = app.ui.download_grids; + // The browser keeps what it downloads for the session; a computer, in a folder. + let tip = if cfg!(target_arch = "wasm32") { + tl!( + "When a coordinate system's most accurate datum transformation needs a grid RustGIS doesn't have, download it from PROJ's grid server (cdn.proj.org). Grids already downloaded stay in use for this session when this is off." + ) + } else { + tl!( + "When a coordinate system's most accurate datum transformation needs a grid RustGIS doesn't have, download it from PROJ's grid server (cdn.proj.org). Grids already downloaded stay in use when this is off: to stop using them, delete the datum-grids folder in RustGIS's app data and start RustGIS again (grids installed for PROJ are still used)." + ) + }; + let resp = ui.checkbox(&mut on, tl!("Download Datum Grids")).on_hover_text(tip); + if resp.clicked() { + let _ = app.run("ui.datumGrids", json!({"on": on})); + } + let (done, total, bytes, active) = rustgis_engine::grids::progress(); + if active { + ui.small(crate::i18n::fmt( + "{done} of {total} · {size}", + &[("done", &done.to_string()), ("total", &total.to_string()), ("size", &rustgis_engine::grids::size_text(bytes))], + )); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + } + }); }); group(ui, "Map Tiles", |ui| { let mut on = app.ui.sharp_tiles; diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 6f3296216a..83c185e3e4 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1535,7 +1535,11 @@ version RustGIS works with, and only then installs it in its data folder (by default `~/.local/share/rustgis/geolibre` on Linux, `~/Library/Application Support/RustGIS/geolibre` on macOS, `%LOCALAPPDATA%\RustGIS\geolibre` on Windows). `RUSTGIS_APP_DATA_DIR` overrides the data folder; Linux also honours `XDG_DATA_HOME`. From the command line, `gp.installGeolibre` -does the same. +installs the same runner synchronously. The desktop install card shows download progress and +**Cancel**, then **Cancelling…** while a cancelled read unwinds. Cancellation is checked +between network reads and before the runner replaces an installed copy; a blocked read must end +or time out first. A notice reports success with the tool count, or failure, even if the Tools +pane was closed while the installation ran. To remove it, click **Uninstall** beside *GeoLibre* at the top of the Tools pane, then **Confirm uninstall** (`gp.uninstallGeolibre` from the command line): RustGIS deletes the runner diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 6a4805a1c2..97f5922807 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -847,6 +847,9 @@ grids, not the server's other files such as deformation models): keeps its places until it is opened again. - Each download is said, with its size, and so is each that fails (not tried again until the setting is turned off and on). An answer that isn't a grid file is refused. +- While downloads run, the setting shows settled grids out of the total and received bytes. + The desktop counts bytes as they arrive; the browser updates the size when each grid finishes. + A final notice counts successfully downloaded grids and their total retained size. - Turned off, grids already downloaded stay in use, and downloads already under way finish. On a computer, delete the `datum-grids` folder and start RustGIS again to stop using them (grids installed for PROJ are still used). The web app keeps a grid for the session only.