From 908835a05e3e95704fc60d483bcb45cc36d4b3e4 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 08:49:06 -0600 Subject: [PATCH 1/4] feat(ui): report download completion and cancel runner installs --- crates/engine/src/cmd/gp.rs | 10 +- crates/engine/src/grids.rs | 102 +++++++++++++++--- crates/engine/src/lib.rs | 9 ++ crates/engine/tests/datum_grid_downloads.rs | 6 +- crates/geolibre/src/install.rs | 32 +++++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/panes.rs | 110 ++++++++++++++++---- crates/ui-egui/src/ribbon.rs | 40 ++++--- docs/user-guide/analysis.md | 5 +- docs/user-guide/maps.md | 3 + 10 files changed, 258 insertions(+), 60 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 41dd0250dd..70f5975c6c 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -297,13 +297,19 @@ fn uninstall_geolibre_language(_s: &mut Session, p: &Value) -> CmdResult { /// 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. pub fn install_geolibre(progress: &dyn Fn(u64, Option)) -> Result { + install_geolibre_cancellable(progress, &std::sync::atomic::AtomicBool::new(false)) +} + +/// The UI install path, with Cancel observed before the runner is put in place. +/// Blocking HTTP reads finish or time out before cancellation is observed. +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..714d5f1ee7 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,7 +682,7 @@ pub fn news_texts(news: &[News]) -> Vec<(String, bool)> { let mut count = 0; for n in news { match n { - News::Missed(_) => {} + News::Missed(_) | News::Finished { .. } => {} News::Got { name, bytes } => got.push(format!("{name} ({})", size_text(*bytes))), News::Failed { name, error } => { count += 1; @@ -692,6 +740,30 @@ fn size_text(bytes: usize) -> String { 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)); + } + #[test] fn only_plain_names_are_kept() { assert!(plain("us_noaa_conus.tif")); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2626b5821f..d4a93a1f25 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2978,6 +2978,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, {mb} MB" } else { "Downloaded {count} datum grids, {mb} MB" }, + [("count", grids.to_string().into()), ("mb", format!("{:.1}", *bytes as f64 / 1_000_000.0).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..fb4b404a5f 100644 --- a/crates/engine/tests/datum_grid_downloads.rs +++ b/crates/engine/tests/datum_grid_downloads.rs @@ -80,7 +80,11 @@ 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()); // Read again, nothing more is asked for. diff --git a/crates/geolibre/src/install.rs b/crates/geolibre/src/install.rs index e3c9c6fb66..68ed8c45f4 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,26 @@ 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. +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 +108,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 +119,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 +130,28 @@ 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. +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 +264,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!(put_in_place(&staged, &dest, "v1.8.1", &AtomicBool::new(true)).unwrap_err().contains("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 b69ad33643..91f917af59 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7440,6 +7440,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 3421738961..0838703d57 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -3284,6 +3284,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. @@ -3483,6 +3484,74 @@ 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. +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); + let cancelled = st.cancel.load(std::sync::atomic::Ordering::Relaxed); + st.result.take().map(|result| (result, cancelled)) + }); + if let Some((result, cancelled)) = finished { + app.gp.install = None; + if cancelled && result.is_err() { + app.session.notify(tl!("GeoLibre installation cancelled"), false); + app.gp.last = 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.last = None; + let count = rustgis_engine::cmd::gp::geolibre_status()["tools"].as_u64().unwrap_or(0); + app.session.notify(crate::i18n::fmt("GeoLibre tools installed: {count} tools", &[("count", &count.to_string())]), false); + } + Err(e) => { + app.command_failed("gp.installGeolibre", &e, mark); + app.gp.last = Some((false, vec![e])); + } + } + } + if app.gp.install.is_some() { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } +} + +#[cfg(test)] +mod install_completion_tests { + use super::*; + + /// The normal frame, with Tools closed, collects and notices an install failure once. + #[test] + fn closed_tools_pane_still_reports_install_failure() { + 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("fixture: truncated runner".into())), + ..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); + let notices = h.state().session.notices_since(mark); + assert_eq!(notices.iter().filter(|n| n.error && n.text == "fixture: truncated runner").count(), 1); + h.step(); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.text == "fixture: truncated runner").count(), 1); + } +} + /// 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 @@ -3496,21 +3565,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; @@ -3551,6 +3605,15 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { 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) }); + if ui.button(tl!("Cancel")).clicked() + && let Some(install) = &app.gp.install + { + install + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .cancel + .store(true, std::sync::atomic::Ordering::Relaxed); + } // Keep drawing while the download runs on its thread. ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); } @@ -3561,13 +3624,17 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { app.gp.install = Some(st.clone()); app.gp.last = 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); } @@ -3575,6 +3642,7 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }); if let Err(e) = spawned { app.gp.install = None; + app.session.notify(e.to_string(), true); app.gp.last = Some((false, vec![e.to_string()])); } } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 22c0ee6529..a8a58bc3bd 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -4081,21 +4081,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} · {mb} MB", + &[("done", &done.to_string()), ("total", &total.to_string()), ("mb", &format!("{:.1}", bytes as f64 / 1_000_000.0))], + )); + 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 260edd831d..e3252c429a 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1523,7 +1523,10 @@ 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. +does the same. The install card shows download progress and **Cancel**. 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 b384e3e51e..fe3df2962e 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -826,6 +826,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. From 5eb352f197db18236debe86a78ba8175603feb2e Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 13:07:10 -0600 Subject: [PATCH 2/4] fix(ui): report small downloads and pending cancellation --- crates/engine/src/grids.rs | 13 ++- crates/engine/src/lib.rs | 4 +- crates/engine/tests/datum_grid_downloads.rs | 26 +++++ crates/geolibre/src/install.rs | 3 +- crates/ui-egui/src/panes.rs | 118 ++++++++++++-------- crates/ui-egui/src/ribbon.rs | 4 +- docs/user-guide/analysis.md | 3 +- 7 files changed, 116 insertions(+), 55 deletions(-) diff --git a/crates/engine/src/grids.rs b/crates/engine/src/grids.rs index 714d5f1ee7..59f78845ab 100644 --- a/crates/engine/src/grids.rs +++ b/crates/engine/src/grids.rs @@ -683,7 +683,7 @@ pub fn news_texts(news: &[News]) -> Vec<(String, bool)> { for n in news { match n { News::Missed(_) | News::Finished { .. } => {} - News::Got { name, bytes } => got.push(format!("{name} ({})", size_text(*bytes))), + 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) { @@ -731,7 +731,9 @@ pub fn news_texts(news: &[News]) -> Vec<(String, bool)> { out } -fn size_text(bytes: usize) -> String { +/// Download sizes in decimal units; rounding small amounts up keeps received bytes visible. +/// Batch totals stay wide on 32-bit front ends as well as native builds. +pub fn size_text(bytes: u64) -> 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)) } } @@ -762,6 +764,9 @@ mod tests { 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] @@ -900,5 +905,9 @@ 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(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 d4a93a1f25..d0cb3732ed 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2981,8 +2981,8 @@ impl Session { if let crate::grids::News::Finished { grids, bytes } = n { self.notify_text( crate::notice_text::NoticeText::format( - if *grids == 1 { "Downloaded {count} datum grid, {mb} MB" } else { "Downloaded {count} datum grids, {mb} MB" }, - [("count", grids.to_string().into()), ("mb", format!("{:.1}", *bytes as f64 / 1_000_000.0).into())], + 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, ); diff --git a/crates/engine/tests/datum_grid_downloads.rs b/crates/engine/tests/datum_grid_downloads.rs index fb4b404a5f..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)); @@ -87,6 +88,16 @@ fn a_read_waits_for_the_grids_its_system_needs() { ] ); 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); @@ -242,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 68ed8c45f4..0bce83f382 100644 --- a/crates/geolibre/src/install.rs +++ b/crates/geolibre/src/install.rs @@ -139,6 +139,7 @@ pub fn install_cancellable(progress: &dyn Fn(u64, Option), cancel: &AtomicB } /// 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(()) } } @@ -269,7 +270,7 @@ mod tests { 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!(put_in_place(&staged, &dest, "v1.8.1", &AtomicBool::new(true)).unwrap_err().contains("cancelled")); + 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); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 0838703d57..e3da239c17 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -3490,12 +3490,12 @@ 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); - let cancelled = st.cancel.load(std::sync::atomic::Ordering::Relaxed); - st.result.take().map(|result| (result, cancelled)) + st.result.take() }); - if let Some((result, cancelled)) = finished { + if let Some(result) = finished { app.gp.install = None; - if cancelled && result.is_err() { + // 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.last = None; return; @@ -3525,33 +3525,73 @@ pub(crate) fn poll_geolibre_install(app: &mut RustGisApp, ctx: &egui::Context) { mod install_completion_tests { use super::*; - /// The normal frame, with Tools closed, collects and notices an install failure once. + /// 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()); + } + + /// 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() { - 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("fixture: truncated runner".into())), - ..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); - let notices = h.state().session.notices_since(mark); - assert_eq!(notices.iter().filter(|n| n.error && n.text == "fixture: truncated runner").count(), 1); - h.step(); - assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.text == "fixture: truncated runner").count(), 1); + 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_eq!(h.state().gp.last.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); + } } } +/// 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 @@ -3598,25 +3638,8 @@ 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) }); - if ui.button(tl!("Cancel")).clicked() - && let Some(install) = &app.gp.install - { - install - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .cancel - .store(true, std::sync::atomic::Ordering::Relaxed); - } - // 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() { @@ -3642,8 +3665,9 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }); if let Err(e) = spawned { app.gp.install = None; - app.session.notify(e.to_string(), true); - app.gp.last = Some((false, vec![e.to_string()])); + let error = Session::redacted(&e.to_string()); + app.gp.last = Some((false, vec![error.as_str().to_string()])); + app.session.notify_redacted(error, true); } } ui.add_space(2.0); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index a8a58bc3bd..30096eda15 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -4100,8 +4100,8 @@ fn settings_tab(app: &mut RustGisApp, ui: &mut Ui) { let (done, total, bytes, active) = rustgis_engine::grids::progress(); if active { ui.small(crate::i18n::fmt( - "{done} of {total} · {mb} MB", - &[("done", &done.to_string()), ("total", &total.to_string()), ("mb", &format!("{:.1}", bytes as f64 / 1_000_000.0))], + "{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)); } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index e3252c429a..c00c8cacf6 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1523,7 +1523,8 @@ 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. The install card shows download progress and **Cancel**. Cancellation is checked +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. From 0728e2b72b741e391ca54287e9c565c34e1da408 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 14:42:56 -0600 Subject: [PATCH 3/4] fix(ui): preserve tool feedback when runner setup finishes --- crates/engine/src/grids.rs | 2 +- crates/ui-egui/src/panes.rs | 191 ++++++++++++++++++++++-------------- 2 files changed, 121 insertions(+), 72 deletions(-) diff --git a/crates/engine/src/grids.rs b/crates/engine/src/grids.rs index 59f78845ab..09c504800f 100644 --- a/crates/engine/src/grids.rs +++ b/crates/engine/src/grids.rs @@ -732,7 +732,7 @@ pub fn news_texts(news: &[News]) -> Vec<(String, bool)> { } /// Download sizes in decimal units; rounding small amounts up keeps received bytes visible. -/// Batch totals stay wide on 32-bit front ends as well as native builds. +/// Accepts the batch counters directly without narrowing them through `usize`. pub fn size_text(bytes: u64) -> 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)) } diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index e3da239c17..eb03e893e1 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -3063,6 +3063,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. @@ -3248,6 +3250,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); @@ -3264,11 +3267,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))) { @@ -3486,6 +3494,7 @@ 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| { @@ -3497,7 +3506,7 @@ pub(crate) fn poll_geolibre_install(app: &mut RustGisApp, ctx: &egui::Context) { // 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.last = None; + app.gp.install_error = None; return; } let mark = app.session.notice_mark(); @@ -3506,13 +3515,14 @@ pub(crate) fn poll_geolibre_install(app: &mut RustGisApp, ctx: &egui::Context) { if let Some(save) = &app.services.save_pref { save("geolibre_runner", &path); } - app.gp.last = None; + app.gp.install_error = None; let count = rustgis_engine::cmd::gp::geolibre_status()["tools"].as_u64().unwrap_or(0); - app.session.notify(crate::i18n::fmt("GeoLibre tools installed: {count} tools", &[("count", &count.to_string())]), false); + 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.last = Some((false, vec![e])); + app.gp.install_error = Some(Session::redacted(&e).as_str().to_string()); } } } @@ -3521,58 +3531,6 @@ pub(crate) fn poll_geolibre_install(app: &mut RustGisApp, ctx: &egui::Context) { } } -#[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()); - } - - /// 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_eq!(h.state().gp.last.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); - } - } -} - /// 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) = { @@ -3645,7 +3603,7 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { 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 || { @@ -3666,7 +3624,7 @@ fn geolibre_card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { if let Err(e) = spawned { app.gp.install = None; let error = Session::redacted(&e.to_string()); - app.gp.last = Some((false, vec![error.as_str().to_string()])); + app.gp.install_error = Some(error.as_str().to_string()); app.session.notify_redacted(error, true); } } @@ -3693,18 +3651,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)); } }, ); @@ -3716,7 +3672,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); @@ -3767,6 +3723,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), } @@ -3864,13 +3821,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)); } }); } @@ -10271,3 +10226,97 @@ pub(crate) mod tests { assert_eq!(h.state().dialogs.text, "Rivers"); } } + +#[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); + } + } +} From 1966156546bb5b83e34cdbce08181f63b40b14d1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 16:06:04 -0600 Subject: [PATCH 4/4] fix(downloads): explain cancellation delays and format size units --- crates/engine/src/cmd/gp.rs | 11 +++++++---- crates/engine/src/grids.rs | 6 ++++-- crates/geolibre/src/install.rs | 4 +++- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 70f5975c6c..08d93b5ef3 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -294,14 +294,17 @@ 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 UI install path, with Cancel observed before the runner is put in place. -/// Blocking HTTP reads finish or time out before cancellation is observed. +/// 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")))] { diff --git a/crates/engine/src/grids.rs b/crates/engine/src/grids.rs index 09c504800f..50b44e1f68 100644 --- a/crates/engine/src/grids.rs +++ b/crates/engine/src/grids.rs @@ -734,8 +734,8 @@ pub fn news_texts(news: &[News]) -> Vec<(String, bool)> { /// 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 mb = bytes as f64 / 1_000_000.0; - if mb >= 1.0 { format!("{mb:.1} MB") } else { format!("{} KB", bytes.div_ceil(1000)) } + 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)] @@ -906,6 +906,8 @@ 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/geolibre/src/install.rs b/crates/geolibre/src/install.rs index 0bce83f382..3e02c113c1 100644 --- a/crates/geolibre/src/install.rs +++ b/crates/geolibre/src/install.rs @@ -83,7 +83,9 @@ pub fn install(progress: &dyn Fn(u64, Option)) -> Result { } /// Installs as [`install`], checking Cancel between download chunks and before publication. -/// A blocked HTTP read finishes or times out before Cancel can be observed. +/// 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")?;