From a5463c3ea6896c58cc6b1b25ae6c52a6882543d1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 20:31:08 -0600 Subject: [PATCH 1/4] fix(ui): hold the web app's save, share and export buttons to the download limit --- crates/engine/src/cmd/exports.rs | 30 ++- crates/engine/src/cmd/field.rs | 25 +- crates/engine/src/cmd/gp.rs | 22 +- crates/engine/src/cmd/items.rs | 11 +- crates/engine/src/cmd/share.rs | 5 +- crates/engine/src/cmd/workflows.rs | 6 +- crates/engine/src/construction.rs | 6 - crates/engine/src/lib.rs | 25 +- crates/engine/src/project.rs | 1 - crates/engine/src/project_capabilities.rs | 5 - crates/engine/src/tests/browser_exports.rs | 43 ++- crates/ui-egui/src/analysispane.rs | 32 +-- crates/ui-egui/src/lib.rs | 296 ++++++++++----------- docs/user-guide/sharing.md | 3 +- 14 files changed, 287 insertions(+), 223 deletions(-) diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 04357ea7f7..3cc713e5f2 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -144,8 +144,7 @@ impl Room { } /// What to do about a file too large to download. -pub(crate) const SMALLER: &str = - "make a smaller file (fewer features or layers, a smaller size or fewer pages), use the ribbon's buttons, or use the desktop app"; +pub(crate) const SMALLER: &str = "make a smaller file (fewer features or layers, a smaller size or fewer pages), or use the desktop app"; /// The file a command makes at once ([`file_command`]): the path it is for, and, where it is /// downloaded, the room it has. A file that is written has no limit here but memory. @@ -159,6 +158,12 @@ impl<'a> Output<'a> { /// A file that is written, or kept in the session: nothing limits it here. pub(crate) const UNLIMITED: Output<'static> = Output { path: "", room: None }; + /// A file the front end gets from the session itself, called `path` when it is refused: held to + /// the room a download has where files are downloaded. + pub(crate) fn here(s: &Session, path: &'a str) -> Result, String> { + Ok(Output { path, room: s.download_room()? }) + } + /// Whether it is made to be downloaded. pub(crate) fn downloads(self) -> bool { self.room.is_some() @@ -282,13 +287,14 @@ pub(crate) fn mib(bytes: usize) -> usize { /// most the files waiting for download may hold. The features and the file are held at once, in /// the browser's memory. A fixed figure: the browser can't say what memory it has free, so /// `rustgis_data::memory::planned` would give its floor there. -pub(crate) const MAX_DOWNLOAD_BYTES: usize = 256 << 20; +pub const MAX_DOWNLOAD_BYTES: usize = 256 << 20; /// Every feature of layer `l`, read in place, for a file made in memory to be downloaded: refused /// past [`MAX_DOWNLOAD_BYTES`] of features, before any is read when the source's count alone says -/// so. A definition query is applied after the read, so it doesn't make the read smaller. -pub(super) fn read_for_download(l: &rustgis_map::Layer) -> Result<(Dataset, rustgis_map::Unreadable), String> { - read_for_download_after(l, 0) +/// so. A definition query is applied after the read, so it doesn't make the read smaller. Where +/// the file has no limit, neither has the read. +pub(super) fn read_for_download(l: &rustgis_map::Layer, room: Room) -> Result<(Dataset, rustgis_map::Unreadable), String> { + if room.bytes == usize::MAX { l.load_all_counted() } else { read_for_download_after(l, 0) } } /// [`read_for_download`] for a file made of several layers, `held` bytes of whose features were @@ -514,12 +520,15 @@ pub(crate) fn download_command( // Said if the queue refuses the file, as when it isn't made. let unsent = held.clone(); let Made { bytes, answer, done, taken, .. } = made; - let done = done.unwrap_or_else(|| format!("Download offered: {name}")); + // A front end that offers the file says so itself. + let done = (!s.offers_files()).then(|| done.unwrap_or_else(|| format!("Download offered: {name}"))); let then: Then = Box::new(move |s: &mut Session, _: &mut Value| { if let Some(taken) = taken { taken(s); } - s.notify_written(done); + if let Some(done) = done { + s.notify_written(done); + } let mark = s.notice_mark(); for notice in held { s.relay_notice(notice); @@ -732,7 +741,10 @@ pub(crate) fn drawn( // already reported above retain their screen markers, so this cannot duplicate them. s.notice_landed_pixels(); written?; - s.notify_written(format!("Exported {path}")); + // A front end that offers the file says so itself. + if !s.offers_files() { + s.notify_written(format!("Exported {path}")); + } Ok(()) }); Ok(Wrote { diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index cd633d0d9e..212c97836b 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -81,8 +81,18 @@ pub(crate) fn package(s: &mut Session, p: &Value) -> Result<(String, Vec), S /// Construction notes describe the delivered package, so callers emit them after delivery. pub(crate) fn package_output(s: &mut Session, p: &Value) -> Result<(String, Vec, rustgis_data::loss::Notes), String> { + package_output_within(s, p, super::exports::Output::UNLIMITED) +} + +/// [`package_output`] for the file `out` describes: a downloaded one is stopped as it passes its +/// room. +pub(crate) fn package_output_within( + s: &mut Session, + p: &Value, + out: super::exports::Output<'_>, +) -> Result<(String, Vec, rustgis_data::loss::Notes), String> { let mut notes = rustgis_data::loss::Notes::new(); - let (name, bytes) = build_package(s, p, &mut notes)?; + let (name, bytes) = build_package(s, p, &mut notes, out)?; Ok((name, bytes, notes)) } @@ -106,7 +116,12 @@ fn legacy_user(s: &Session) -> Result<(), String> { /// `notes`, said once the package has been delivered. Cancel is checked between streamed /// chunks, tile archives and the encoding steps. A single archive read or ZIP compression /// runs through before the next check. -fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Notes) -> Result<(String, Vec), String> { +fn build_package( + s: &mut Session, + p: &Value, + notes: &mut rustgis_data::loss::Notes, + out: super::exports::Output<'_>, +) -> Result<(String, Vec), String> { use rustgis_data::progress; progress::check().map_err(|e| e.to_string())?; let mut losses = rustgis_data::loss::Notes::new(); @@ -582,7 +597,11 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not if let Some(package) = project.field_origin.as_ref().map(|o| o.package.as_str()).filter(|p| !coming_back && !p.is_empty()) { entries.push((super::field_changes::GIVEN.into(), super::field_changes::given_entry(package)?)); } - let bytes = rustgis_data::zip::write(&entries)?; + let mut parts = out.parts(); + for (name, bytes) in entries { + parts.push(name, bytes)?; + } + let bytes = parts.zip()?; progress::check().map_err(|e| e.to_string())?; notes.extend(losses); Ok((area, bytes)) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 96d2f73680..12b9612ffb 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -3859,15 +3859,17 @@ pub(super) fn queue_export(s: &mut Session, mut wrote: super::exports::Wrote) -> // Not exported until the download is taken: the claim goes from the pending answer, and what // follows it (what the file leaves out) stays, under the file's name. let exported = format!("Exported {file_name}"); - let messages: Vec = wrote - .completion_notes() - .into_iter() - .filter_map(|message| match message.strip_prefix(&exported) { - Some("") => None, - Some(note) if note.starts_with([' ', ';']) => Some(format!("{file_name}{note}")), - _ => Some(message), - }) - .collect(); + let unclaimed = |message: &str| match message.strip_prefix(&exported) { + Some("") => None, + Some(note) if note.starts_with([' ', ';']) => Some(format!("{file_name}{note}")), + _ => Some(message.to_string()), + }; + let messages: Vec = wrote.completion_notes().iter().filter_map(|message| unclaimed(message)).collect(); + // A front end that offers the file says so itself, and its browser or phone may not save it: + // what follows the claim is all that is said once it is taken. + if s.offers_files() { + wrote.notes = wrote.notes.into_vec().into_iter().filter_map(|n| unclaimed(n.as_str()).map(|text| n.map_text(|_| text))).collect(); + } let mut out = queue(s, file_name, bytes, Delivery::Export(Box::new(wrote)))?; out["messages"] = json!(messages); Ok(out) @@ -3896,7 +3898,7 @@ fn queue(s: &mut Session, file_name: String, bytes: Arc>, from: Delivery Err(shared) => shared, }; let cap = s.download_cap(); - let held = s.waiting_download_bytes(); + let held = if cap == usize::MAX { 0 } else { s.waiting_download_bytes() }; // An export whose writer takes a limit was stopped at it; this is what holds the others (a // picture, an SVG, a PDF past its pages, the file a raster layer holds) to it. // Measured as the queue counts what waits: by what the file holds, its spare room included. diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 93092c533d..0f1bec2ff4 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -1894,9 +1894,12 @@ pub fn item_bytes(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec Ok((name, bytes)) } -/// Builds an item and returns construction-loss notes for publication only after delivery. +/// Builds an item and returns construction-loss notes for publication only after delivery. In the +/// browser, where it is downloaded, it is stopped as it passes the room a download has. pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec, rustgis_data::loss::Notes), String> { - item_output_within(s, kind, p, Output::UNLIMITED) + let what = ITEMS.iter().find(|i| i.0 == kind).map_or("the file", |i| i.2); + let out = Output::here(s, what)?; + item_output_within(s, kind, p, out) } /// [`item_output`] for the file `out` describes: a downloaded one is stopped as it passes its room. @@ -1979,7 +1982,7 @@ fn item_output_within( } "projectPackage" => (s.project.name.clone(), package_project(s, &mut construction_notes, out)?), "fieldPackage" => { - let (name, bytes, notes) = super::field::package_output(s, p)?; + let (name, bytes, notes) = super::field::package_output_within(s, p, out)?; construction_notes.extend(notes); (name, bytes) } @@ -2045,6 +2048,8 @@ fn item_output_within( } k => return Err(format!("unknown item '{k}'")), }; + // A small file's writer, such as the bookmarks', takes no limit. + out.check(bytes.len())?; let ext = ITEMS.iter().find(|i| i.0 == kind).map_or("json", |i| i.1); Ok((format!("{}.{ext}", safe(&name)), bytes, construction_notes)) } diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index d0c0bedf2f..b88ef1962a 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -732,7 +732,10 @@ fn write_layer( let mut held = None; use std::borrow::Cow; let (mut whole, unreadable) = if l.is_streamed() && chunks.is_none() { - let (dataset, unreadable) = if download.is_some() { super::exports::read_for_download(l)? } else { l.load_all_counted()? }; + let (dataset, unreadable) = match download { + Some(room) => super::exports::read_for_download(l, room)?, + None => l.load_all_counted()?, + }; (Cow::Owned(dataset), unreadable) } else { (Cow::Borrowed(&l.dataset), rustgis_map::Unreadable::default()) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 95a62b5a95..a2dda14603 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2755,8 +2755,10 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result super::exports::read_for_download(&layer, room)?, + None => layer.load_all_counted()?, + }; (Cow::Owned(ds), unreadable) } else { (Cow::Borrowed(&layer.dataset), rustgis_map::Unreadable::default()) diff --git a/crates/engine/src/construction.rs b/crates/engine/src/construction.rs index 40ca5762eb..2383445c5b 100644 --- a/crates/engine/src/construction.rs +++ b/crates/engine/src/construction.rs @@ -214,12 +214,6 @@ pub(crate) fn forget_feature(s: &mut Session, layer: u32, feature: u64) { } impl Session { - /// Counted losses for a layer output, including browser downloads. Call before encoding - /// and present the notes only after the output has been accepted or written. - pub fn layer_construction_output_notes(&self, layer: u32) -> Result, String> { - let l = self.map().layer(layer).ok_or("no such layer")?; - self.constructions.export_notes(self.map().instance_id(), l) - } /// Counted runtime-construction losses for a whole-project output. Embedders saving the /// public `Project` directly should present these notes too: `Project` owns no session cache. /// Explicit save/download paths call this inside their existing durable output transaction; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0d2a08a02f..fa25713442 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -943,6 +943,9 @@ pub struct Session { notices_given: u64, /// While a download's file is made, the notices that wait with it ([`Session::holding_notices`]). held_notices: Option>, + /// While the front end runs a command whose file it downloads, the most bytes it takes + /// ([`Session::offer_files`]). + offering: Option, /// Loss notices given in this session by code, including ones no longer kept, less those a /// failed command withdrew (see [`Session::losses_given`]). losses_given: Vec<(rustgis_data::loss::LossCode, u64)>, @@ -1538,6 +1541,7 @@ impl Session { diagnostics: rustgis_data::diagnostics::History::default(), notices_given: 0, held_notices: None, + offering: None, losses_given: Vec::new(), beyond_said: None, crs_notes_said: Vec::new(), @@ -1854,7 +1858,20 @@ impl Session { if self.queue_gp_files { return true; } - cfg!(target_arch = "wasm32") + self.offering.is_some() || cfg!(target_arch = "wasm32") + } + + /// For a front end whose button saves by downloading: until it is set back, a command that + /// takes a path queues its file ([`Session::take_gp_files`]) as a browser's script does, held + /// to `most` bytes (`usize::MAX` for no limit but memory). It leaves saying that the file was + /// offered to the front end. Gives what was set before. + pub fn offer_files(&mut self, most: Option) -> Option { + std::mem::replace(&mut self.offering, most) + } + + /// Whether the front end says itself that a file was offered ([`Session::offer_files`]). + pub(crate) fn offers_files(&self) -> bool { + self.offering.is_some() } /// The most bytes the files waiting for download may hold in all. @@ -1863,7 +1880,7 @@ impl Session { if let Some(cap) = self.download_cap { return cap; } - cmd::exports::MAX_DOWNLOAD_BYTES + self.offering.unwrap_or(cmd::exports::MAX_DOWNLOAD_BYTES) } /// Where files are downloaded, the room for one more; `None` where they are written. Refused @@ -1873,7 +1890,9 @@ impl Session { return Ok(None); } let waiting = self.waiting_download_bytes(); - let bytes = self.download_cap().saturating_sub(waiting); + // No limit stays none whatever waits. + let cap = self.download_cap(); + let bytes = if cap == usize::MAX { cap } else { cap.saturating_sub(waiting) }; if self.waiting_download_count() >= cmd::exports::MAX_DOWNLOADS || bytes == 0 { return Err(cmd::gp::queue_full(self.download_cap())); } diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 0777e25ea3..142c0b890a 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -14,7 +14,6 @@ use crate::render::rustgis_tiles::address::Reach; mod capabilities; #[path = "project_label_losses.rs"] pub(crate) mod label_losses; -pub use capabilities::layout_file_bytes; #[cfg(test)] pub(crate) use capabilities::{layer_file_bytes, map_file_bytes}; pub(crate) use capabilities::{layer_file_within, layout_file_within, map_file_within, model_capabilities, task_capabilities}; diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index b5a4a0702d..294b4913a2 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1341,11 +1341,6 @@ pub(crate) fn map_file_within(map: &Map, out: Output<'_>) -> Result, Str /// A layout file has its own header, as a map file has: what its elements use, as the project /// holding it requires for them (#2277). Indented, as layout files have always been written. No /// `crs-wkt`: a layout holds no coordinate system, only a measured grid's as text. -pub fn layout_file_bytes(layout: &rustgis_map::layout::Layout) -> Result, String> { - layout_file_within(layout, Output::UNLIMITED) -} - -/// [`layout_file_bytes`] for the file `out` describes. pub(crate) fn layout_file_within(layout: &rustgis_map::layout::Layout, out: Output<'_>) -> Result, String> { let requires = layout_capabilities(std::slice::from_ref(layout)); out.json_pretty(&Item { format: FORMAT, requires, value: layout }) diff --git a/crates/engine/src/tests/browser_exports.rs b/crates/engine/src/tests/browser_exports.rs index 7972d8ce58..a5654317b0 100644 --- a/crates/engine/src/tests/browser_exports.rs +++ b/crates/engine/src/tests/browser_exports.rs @@ -749,12 +749,10 @@ fn a_browser_file_command_downloads_the_desktops_file_and_says_the_same() { /// Every command that saves, packages or shares a file, over the limit (a stand-in of ten /// bytes), is stopped as the file is made: nothing waits to be downloaded, and the refusal says -/// what to do. A bookmarks file, of a bounded size, is refused once made. -/// Under the limit, each downloads. +/// what to do. Under the limit, each downloads. #[test] fn a_browser_file_command_over_the_limit_is_stopped_as_it_is_made() { const STOPPED: &str = "stopped once the file passed"; - const MADE: &str = "more than the 1 MiB a command can download"; let files = Files::new(); let mut s = items(&files, true); let mut cases = file_cases(); @@ -764,10 +762,9 @@ fn a_browser_file_command_over_the_limit_is_stopped_as_it_is_made() { ("project.exportLog", json!({}), "log.csv", false), ]); for (command, params, file, _) in cases { - let refusal = if command == "bookmark.save" { MADE } else { STOPPED }; s.download_cap = Some(10); let e = s.run(command, &to(¶ms, file)).unwrap_err(); - assert!(e.contains(file) && e.contains(refusal) && e.contains("make a smaller file"), "{command} {file}: {e}"); + assert!(e.contains(file) && e.contains(STOPPED) && e.contains("make a smaller file"), "{command} {file}: {e}"); assert!(s.take_gp_files().is_empty(), "{command} {file}"); s.download_cap = Some(8 << 20); let pending = s.run(command, &to(¶ms, file)).unwrap_or_else(|e| panic!("{command} {file}: {e}")); @@ -777,6 +774,42 @@ fn a_browser_file_command_over_the_limit_is_stopped_as_it_is_made() { } } +/// An item the interface downloads itself (the ribbon's save buttons) is held to the same room as +/// the command that saves it, and takes none of the queue's places. +#[test] +fn a_browser_item_over_the_limit_is_stopped_as_it_is_made() { + let files = Files::new(); + let mut s = items(&files, true); + for (kind, params) in [ + ("map", json!({})), + ("layer", json!({"layer": "Places"})), + ("styles", json!({})), + ("ramps", json!({})), + ("template", json!({})), + ("projectPackage", json!({})), + ("mapPackage", json!({})), + ("mobilePackage", json!({})), + ("gpPackage", json!({})), + ("bookmarks", json!({})), + ("task", json!({"task": "Steps"})), + ("report", json!({"report": "List"})), + ("presentation", json!({})), + ("notebook", json!({})), + ("obj", json!({"layer": "Places"})), + ("stl", json!({"layer": "training"})), + ("webMap", json!({})), + ("webLayer", json!({"layer": "Places"})), + ("fieldPackage", json!({})), + ] { + s.download_cap = Some(10); + let e = crate::cmd::items::item_output(&mut s, kind, ¶ms).unwrap_err(); + assert!(e.contains("stopped once the file passed") && e.contains("make a smaller file"), "{kind}: {e}"); + s.download_cap = None; + let (_, bytes, _) = crate::cmd::items::item_output(&mut s, kind, ¶ms).unwrap_or_else(|e| panic!("{kind}: {e}")); + assert!(!bytes.is_empty() && s.take_gp_files().is_empty(), "{kind}"); + } +} + /// An STL's room is for the triangles it keeps: zero-area ones, which it leaves out, take none of /// it. A point's cube of next to no height keeps its top and bottom, 284 bytes; a whole cube is /// 684. diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index f09f5245ef..48d66ce9f4 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -313,16 +313,15 @@ fn combo(ui: &mut Ui, id: &str, name: &str, value: &mut String, options: &[Strin .on_hover_text(tl!(name)); } -/// Asks where a desktop conversion goes before starting its export worker. Browser downloads -/// retain the text-returning command; that command refuses a streamed layer's partial view. +/// Asks where a desktop conversion goes before starting its export worker; where the app +/// downloads, the command's file is offered instead. fn convert_layer(app: &mut RustGisApp) -> Result<(), String> { let format = app.workflow.format.clone(); let ext = if format == "wkt" { "csv" } else { &format }; let name = format!("{}.{ext}", app.workflow.layer); let mut params = json!({"layer": app.workflow.layer, "format": format}); if app.services.download.is_some() { - let answer = app.session.run("data.convert", ¶ms)?; - app.download_bytes(&name, answer["text"].as_str().unwrap_or("").as_bytes().to_vec()); + app.run_offering("data.convert", &name, params, None)?; } else if let Some(path) = crate::dialogs::pick_save(&name, &[ext], tl!("Converted data")) { params["path"] = json!(path); #[cfg(not(target_arch = "wasm32"))] @@ -1569,19 +1568,22 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { if kind == "reality" { combo(ui, "wf_mesh", "Layer", &mut app.workflow.layer, &rasters); if ui.button(tl!("Export Mesh (OBJ)…")).clicked() { - match app.session.run("imagery.mesh", &json!({"layer": app.workflow.layer})) { - Ok(v) => { - let name = format!("{}.obj", app.workflow.layer); - let bytes = v["text"].as_str().unwrap_or("").as_bytes().to_vec(); - if app.services.download.is_some() { - app.download_bytes(&name, bytes); - } else if let Some(path) = crate::dialogs::pick_save(&name, &["obj"], tl!("3D mesh")) { - app.workflow.error = rustgis_engine::data::io::write_atomic(std::path::Path::new(&path), &bytes) - .err() - .map(|e| e.to_string()); + let name = format!("{}.obj", app.workflow.layer); + let params = json!({"layer": app.workflow.layer}); + if app.services.download.is_some() { + app.workflow.error = app.run_offering("imagery.mesh", &name, params, None).err(); + } else { + match app.session.run("imagery.mesh", ¶ms) { + Ok(v) => { + let bytes = v["text"].as_str().unwrap_or("").as_bytes().to_vec(); + if let Some(path) = crate::dialogs::pick_save(&name, &["obj"], tl!("3D mesh")) { + app.workflow.error = rustgis_engine::data::io::write_atomic(std::path::Path::new(&path), &bytes) + .err() + .map(|e| e.to_string()); + } } + Err(e) => app.workflow.error = Some(e), } - Err(e) => app.workflow.error = Some(e), } } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index be3b7eff98..214866031c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1553,6 +1553,12 @@ pub struct RustGisApp { pub map: mapview::MapView, pub dialogs: dialogs::Dialogs, pub gp: panes::GpForm, + /// While a command runs whose file is offered as a download ([`Self::run_offering`]): what is + /// said once the host takes it. + offering: Option, + /// The most bytes [`Self::run_offering`] takes, for a test to reach. + #[cfg(test)] + pub(crate) offer_most: Option, pub table: table::TableState, pub layout: layoutview::LayoutView, /// The text graphic the Format pane edits (#516). @@ -1949,6 +1955,9 @@ impl RustGisApp { map: mapview::MapView::default(), dialogs: dialogs::Dialogs::default(), gp: panes::GpForm::default(), + offering: None, + #[cfg(test)] + offer_most: None, table: table::TableState::default(), layout: layoutview::LayoutView::default(), graphic_format: graphicformat::GraphicFormat::default(), @@ -3017,39 +3026,52 @@ impl RustGisApp { if self.services.download.is_none() { return Err(tl!("this build saves projects with Save As").into()); } - let stem: String = stem.chars().take(200).collect(); - // Not an undoable edit: saving names the project, as `project.saveAs` does. The name - // stays set while the download is offered, and goes back if the download fails. - let construction_notes = self.session.construction_output_notes()?; - let old = std::mem::replace(&mut self.session.project.name, stem.clone()); - let (text, report) = match self.session.project.saved_text(None) { - Ok(saved) => saved, - Err(e) => { - self.session.project.name = old; - return Err(e.to_string()); - } - }; - let file = format!("{stem}.rgis"); - if let Err(e) = self.services.download.as_ref().ok_or(tl!("no download service"))?(&file, Arc::new(text.into_bytes())) { - self.session.project.name = old; - return Err(e); - } + // As long as a project's name may be, which the command takes from the file's. + let file = format!("{}.rgis", stem.chars().take(200).collect::()); + let old = self.session.project.name.clone(); + let offered = crate::i18n::fmt("Download offered: {name}. The browser doesn't say whether it saved the file.", &[("name", &file)]); + self.run_offering("project.saveAs", &file, json!({}), Some(offered))?; if self.session.project.name != old { - // Save As changed the document even when it began clean. Offering a download - // cannot confirm that this renamed document reached a file. - self.session.mark_unsaved(); + // Save As changed the document even when it began clean. self.ui.history_jump = None; } - let offered = crate::i18n::fmt("Download offered: {name}. The browser doesn't say whether it saved the file.", &[("name", &file)]); - self.session.notify(offered, false); - report.notify(&mut self.session); - for note in construction_notes { - self.session.say(note); - } self.ui.web_file = Some(file); Ok(()) } + /// Runs `command` (a save, export or share that takes a path) and offers its file as the + /// download `name`, where the app downloads (the browser, a phone): the command a script runs, + /// so its file is the same and, in the browser, held to what a download may be. `offered` is + /// what is said once the host has taken it, else that it was offered. + pub(crate) fn run_offering(&mut self, command: &str, name: &str, mut params: Value, offered: Option) -> Result { + // A name is one file's: a `/` in a layer's isn't a folder. + let name = name.replace(['/', '\\'], "_"); + // Of something without a name: an extension alone isn't read as one. + let name = if name.rfind('.') == Some(0) { format!("untitled{name}") } else { name }; + params["path"] = json!(name); + let offered = offered.unwrap_or_else(|| Self::offered(&name)); + // A phone's file goes to the system to save: nothing limits it but memory, as before. + let most = + if cfg!(any(target_os = "android", target_os = "ios")) { usize::MAX } else { rustgis_engine::cmd::exports::MAX_DOWNLOAD_BYTES }; + #[cfg(test)] + let most = self.offer_most.unwrap_or(most); + let outer = (self.session.offer_files(Some(most)), self.offering.replace(offered)); + // Run here, not on another thread: its file is offered as it ends. + let ran = self.run_with_prepared(command, params, AppDispatch::Direct); + self.session.offer_files(outer.0); + self.offering = outer.1; + ran + } + + /// Says that the host took the download `name`. + fn offered(name: &str) -> String { + if cfg!(any(target_os = "android", target_os = "ios")) { + crate::i18n::fmt("Choose where to save {name}.", &[("name", name)]) + } else { + crate::i18n::fmt("Download offered: {name}", &[("name", name)]) + } + } + /// Offers bytes as a download (web), and says whether the browser accepted the offer. /// A failure is notified; acceptance does not confirm that a file was saved. pub(crate) fn download_bytes(&mut self, name: &str, bytes: Vec) -> bool { @@ -3064,11 +3086,7 @@ impl RustGisApp { self.session.notify(e, true); return false; } - let offered = if cfg!(any(target_os = "android", target_os = "ios")) { - crate::i18n::fmt("Choose where to save {name}.", &[("name", name)]) - } else { - crate::i18n::fmt("Download offered: {name}", &[("name", name)]) - }; + let offered = Self::offered(name); self.session.notify(offered, false); true } @@ -3094,6 +3112,11 @@ impl RustGisApp { Some(download) => download(&name, bytes), None => Err(tl!("this build has no download service").into()), }; + if delivered.is_ok() + && let Some(offered) = self.offering.take() + { + self.session.notify(offered, false); + } // gp.fileDelivered reports delivery failures itself. The app also reports // acknowledgment failures before dispatch, without repeating engine notices. // Asked before the acknowledgment forgets the file. @@ -5273,11 +5296,7 @@ impl RustGisApp { "ui.save" | "ui.saveAs" if self.services.download.is_some() => { let name = format!("{}.rgis", self.session.project.name); if id == "ui.save" && self.ui.web_file.as_deref() == Some(name.as_str()) { - // The keyboard caller discards the result, so the failure is shown here too. - if let Err(error) = self.save_download(&name) { - self.session.notify(error.clone(), true); - return Err(error); - } + self.save_download(&name)?; } else { self.dialogs.open("saveProject", &self.session)?; } @@ -5301,8 +5320,9 @@ impl RustGisApp { let print = id == "ui.printLayout"; let pdf_only = print || p.get("format").and_then(Value::as_str) == Some("pdf"); if self.services.download.is_some() { - let bytes = self.layout_bytes(li, true, if print { 300.0 } else { 150.0 })?; - self.download(&format!("{name}.pdf"), bytes); + let dpi = if print { 300 } else { 150 }; + let params = json!({"layout": li, "dpi": dpi, "georeference": self.ui.pdf_georeference}); + return self.run_offering("layout.export", &format!("{name}.pdf"), params, None); } else if print { // Printing goes through the system's PDF viewer, which owns the printers. let bytes = self.layout_bytes(li, true, 300.0)?; @@ -5348,14 +5368,7 @@ impl RustGisApp { let i = rustgis_engine::cmd::report::index(&self.session, p)?; let name = self.session.project.reports.get(i).map(|r| r.name.clone()).unwrap_or_default(); if self.services.download.is_some() { - let session = &mut self.session; - let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::report::report_bytes(session, i, 150.0, true) - })) - .unwrap_or_else(|payload| Err(crate::bug("the report export", payload.as_ref()))) - .inspect_err(|e| self.session.notify(e.clone(), true))? - .0; - self.download(&format!("{name}.pdf"), bytes); + return self.run_offering("report.export", &format!("{name}.pdf"), json!({"report": i, "dpi": 150}), None); } else if let Some(path) = dialogs::pick_save(&format!("{name}.pdf"), &["pdf", "png"], tl!("PDF or PNG")) { // Drawn on a thread of its own, with progress and Cancel in the status bar: a // layer read in place is read whole for it. @@ -5370,8 +5383,7 @@ impl RustGisApp { let li = self.session.active_layout.ok_or("open a layout first")?; let l = self.session.project.layouts.get(li).cloned().ok_or("open a layout first")?; if self.services.download.is_some() { - let bytes = rustgis_engine::project::layout_file_bytes(&l)?; - self.download(&format!("{}.rgislayout", l.name), bytes); + return self.run_offering("layout.save", &format!("{}.rgislayout", l.name), json!({"layout": li}), None); } else if let Some(path) = dialogs::pick_save(&format!("{}.rgislayout", l.name), &["rgislayout"], tl!("RustGIS layout")) { return self.run("layout.save", json!({"layout": li, "path": path})); } @@ -5719,14 +5731,7 @@ impl RustGisApp { let i = rustgis_engine::cmd::presentation::index(&self.session, p)?; let name = self.session.project.presentations.get(i).map(|r| r.name.clone()).unwrap_or_default(); if self.services.download.is_some() { - let session = &mut self.session; - let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::presentation::export_bytes(session, i, "html", 110.0) - })) - .unwrap_or_else(|payload| Err(crate::bug("the presentation export", payload.as_ref()))) - .inspect_err(|e| self.session.notify(e.clone(), true))? - .0; - self.download(&format!("{name}.html"), bytes); + return self.run_offering("presentation.export", &format!("{name}.html"), json!({"presentation": i, "dpi": 110}), None); } else if let Some(path) = dialogs::pick_save(&format!("{name}.html"), &["html", "pdf", "png"], tl!("Slideshow, PDF or PNG")) { @@ -5873,20 +5878,8 @@ impl RustGisApp { }; } "ui.exportMap" if self.services.download.is_some() => { - // The same last-resort panic guard `Session::run` gives commands. - let session = &mut self.session; - let png = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rustgis_engine::cmd::share::map_png_fitted(session, 192.0))) - .unwrap_or_else(|payload| Err(crate::bug("Export Map", payload.as_ref()))); - let png = match png { - Ok(p) => p, - Err(e) => { - self.session.notify(e.clone(), true); - return Err(e); - } - }; let name = format!("{}.png", self.session.map().name); - self.download(&name, png); + return self.run_offering("share.exportMap", &name, json!({"dpi": 192, "fit": true}), None); } // Without a format, the Export Features dialog asks for one. "ui.exportLayer" if p.get("format").and_then(Value::as_str).is_none() => { @@ -5908,90 +5901,14 @@ impl RustGisApp { let annotation_export = id == "ui.annotationExport"; let table = id == "ui.exportTable"; let id = if table { self.export_table_target(p)? } else { self.export_target(p)? }; - let construction_notes = if table { Default::default() } else { self.session.layer_construction_output_notes(id)? }; // Any format the dialog offers here (`dialogs::export_formats`): not GeoPackage or - // FlatGeobuf, which the data crate refuses in the browser. + // FlatGeobuf, which the command refuses in the browser. A Shapefile, several files, + // goes in a zip. let ext = p.get("format").and_then(Value::as_str).unwrap_or("geojson").to_ascii_lowercase(); - let download_ext = if ext == "shp" { "zip".to_string() } else { ext.clone() }; - let name = self.export_file_name(id, &download_ext, table, annotation_export)?; rustgis_engine::cmd::share::gpkg_table(p, &ext)?; - use std::borrow::Cow; - let (mut ds, lost, query, source_name) = if table { - let t = - self.session.project.table(id).ok_or_else(|| tl!("the table Export Table was opened on is gone").to_string())?; - (Cow::Borrowed(&t.dataset), Default::default(), None, t.dataset.name.clone()) - } else { - let l = self.session.map().layer(id).ok_or_else(|| tl!("select a layer in the Layers pane first").to_string())?; - // A streamed layer exports its whole source, not the features read for the view. - let (ds, lost) = if l.is_streamed() { - let (dataset, lost) = l.load_all_counted()?; - (Cow::Owned(dataset), lost) - } else { - (Cow::Borrowed(&l.dataset), Default::default()) - }; - (ds, lost, l.definition_query.as_deref(), l.name.clone()) - }; - let query_report = rustgis_engine::data::export::filter_dataset(&mut ds, query).map_err(|e| e.to_string())?; - // A layer in its own coordinate system, as share.exportLayer writes a file; a table - // in longitude/latitude, as share.exportTable does. - use rustgis_engine::data::io; - let (crs, default_note) = if table { - (rustgis_engine::data::raster::Crs::LonLat, None) - } else { - io::default_export_in(&ds, &name, self.session.project.coordinate_system) - }; - let written = io::write_bytes_noted(&ds, &ext, crs, &name).map_err(|e| e.to_string()); - let (bytes, left_out, unplaced, extent) = match written { - Ok(w) => w, - Err(e) => { - self.session.notify(e.clone(), true); - return Err(e); - } - }; - let ext = download_ext; - // The features written, read whole, give their own extent, in longitude/latitude - // (not a raster's, or the one a streamed layer's source declares), taken from the - // places converted for the download when it is written there. - let mut notes: rustgis_engine::data::loss::Notes = rustgis_engine::data::export_notes([(ds.as_ref(), extent)], &name, crs); - rustgis_engine::cmd::share::coalesce_read_zm(&mut notes, &name, &ds, &lost); - notes.extend(unplaced); - // Which system it is written in, where that isn't the layer's own, as share.exportLayer says. - notes.extend(default_note); - let mut dbf_notes = rustgis_engine::data::loss::Notes::new(); - if ext == "zip" { - dbf_notes.extend(io::shapefile_names_note(&ds.fields, &name)); - dbf_notes.extend(io::shapefile_values_notes(&ds, &name)); - dbf_notes.extend(io::shapefile_geometry_notes(&ds, &name, crs)); - } - if matches!(ext.as_str(), "parquet" | "geoparquet") { - dbf_notes.extend(rustgis_engine::data::source::parquet::values_note(&ds, &name)); - } - dbf_notes.extend(io::dates_as_text_note(&ds.fields, &name)); - dbf_notes.extend(rustgis_engine::cmd::share::gpkg_dates_note(&ds, &ext, &name)); - if lost.rows > 0 { - dbf_notes.push(rustgis_engine::cmd::whole::unread_note(&name, lost.rows)); - } - dbf_notes.extend(rustgis_engine::cmd::share::read_notes(&name, &source_name, &lost)); - // CSV holds a point a row, GPX a name for each feature and no areas; reading text back, CSV reads blanks as null and KML and GPX trim it. - dbf_notes.extend(io::export_losses_notes(&ds, &ext, io::name_field(&ds), &name).map_err(|e| e.to_string())?); - // NaN and infinities, which GeoJSON can't hold, written as null. - let null_numbers = rustgis_engine::data::export::numbers_written_as_null(&ds.features, &ds.fields, &ext); - drop(ds); - // Said only once the download is taken, as the other notes are. - dbf_notes.extend(io::left_out_note(&name, &ext, left_out)); - if ext == "zip" && rustgis_engine::data::raster::wkt::to_wkt(crs).is_none() { - dbf_notes.push(rustgis_engine::data::loss::Note::loss( - rustgis_engine::data::loss::LossCode::DroppedCrsName, - format!("{name}: no .prj written, as {} has no WKT form", crs.label()), - )); - } - if self.download(&name, bytes) { - rustgis_engine::cmd::share::notify_export_query(&mut self.session, &name, &source_name, &query_report); - rustgis_engine::cmd::share::notify_null_numbers(&mut self.session, &name, null_numbers); - for note in notes.into_iter().chain(dbf_notes).chain(construction_notes) { - self.session.say(note); - } - } + let name = self.export_file_name(id, if ext == "shp" { "zip" } else { &ext }, table, annotation_export)?; + let (command, target) = if table { ("share.exportTable", "table") } else { ("share.exportLayer", "layer") }; + return self.run_offering(command, &name, json!({target: id}), None); } "ui.exportRaster" if self.services.download.is_some() => { // The web app: encode once and download. A tile layer is fetched on a thread of @@ -6000,15 +5917,9 @@ impl RustGisApp { let tiles = p.get("tiles").cloned().unwrap_or(Value::Null); return self.run("share.exportRaster", json!({"path": "tiles.tif", "tiles": tiles})); } - match rustgis_engine::cmd::raster::geotiff_bytes(&mut self.session, &Value::Null) { - Ok((name, bytes)) => { - self.download(&format!("{name}.tif"), bytes); - } - Err(e) => { - self.session.notify(e.clone(), true); - return Err(e); - } - } + let layer = self.session.active_layer.and_then(|id| self.session.map().layer(id)); + let name = layer.map(|l| format!("{}.tif", l.name)).unwrap_or_else(|| ".tif".into()); + return self.run_offering("share.exportRaster", &name, json!({}), None); } "ui.exportRaster" => { // A tile layer (the one its menu names, else the one picked) is written over the @@ -10368,6 +10279,73 @@ mod download_service_tests { assert!(!app.session.notices.iter().any(|n| n.text.contains("Download offered"))); } + /// Every button that downloads a file holds it to what a download may be, as the same command + /// in a script does: past it nothing is offered, and the refusal says what to do. Within it, or + /// with no limit (a phone), one file is offered under the button's name. + #[test] + fn a_button_over_the_download_limit_offers_nothing() { + let taken: std::sync::Arc>> = Default::default(); + let names = taken.clone(); + let mut app = RustGisApp::with_sample().with_services(Services { + download: Some(Box::new(move |name, bytes| { + assert!(!bytes.is_empty(), "{name}"); + names.lock().unwrap().push(name.to_string()); + Ok(()) + })), + ..Default::default() + }); + let dir = tempfile::tempdir().unwrap(); + let grid = dir.path().join("dem.asc"); + std::fs::write(&grid, "ncols 2\nnrows 2\nxllcorner 0\nyllcorner 0\ncellsize 1\n1 2\n3 4\n").unwrap(); + app.run("layer.addData", json!({"path": grid, "name": "Dem"})).unwrap(); + let dem = app.session.active_layer; + use rustgis_engine::data::{Dataset, Field, FieldType, GeometryType, Value}; + let mut totals = Dataset::new("Totals", GeometryType::None, vec![Field::new("population", FieldType::Integer)]); + totals.push(None, vec![Value::Int(1_000_000)]); + let totals = app.session.project.add_table(totals); + app.run("layer.rename", json!({"layer": "Cities", "name": "Cities/Towns"})).unwrap(); + app.run("layout.new", json!({"name": "Page", "template": "blank"})).unwrap(); + app.run("report.new", json!({"layer": "Cities/Towns", "name": "List"})).unwrap(); + app.run("presentation.new", json!({"name": "Slides"})).unwrap(); + app.run("presentation.mapPage", json!({})).unwrap(); + let map = app.session.map().name.clone(); + app.session.project.name = "Atlas".into(); + app.ui.web_file = Some("Atlas.rgis".into()); + for (id, params, file) in [ + ("ui.exportLayer", json!({"layer": "Cities/Towns", "format": "geojson"}), "Cities_Towns.geojson".to_string()), + ("ui.exportLayer", json!({"layer": "Cities/Towns", "format": "shp"}), "Cities_Towns.zip".into()), + ("ui.exportTable", json!({"table": totals, "format": "csv"}), "Totals.csv".into()), + ("ui.exportRaster", json!({}), "Dem.tif".into()), + ("ui.exportMap", json!({}), format!("{map}.png")), + ("ui.exportLayout", json!({}), "Page.pdf".into()), + ("ui.printLayout", json!({}), "Page.pdf".into()), + ("ui.saveLayout", json!({}), "Page.rgislayout".into()), + ("ui.exportReport", json!({}), "List.pdf".into()), + ("ui.exportPresentation", json!({}), "Slides.html".into()), + ("ui.save", json!({}), "Atlas.rgis".into()), + ] { + app.session.active_layer = dem; + app.session.active_layout = Some(0); + app.offer_most = Some(10); + let mark = app.session.notice_mark(); + let e = app.run(id, params.clone()).unwrap_err(); + assert!(e.contains("MiB a command can download in the browser") && e.contains("desktop app"), "{id}: {e}"); + assert_eq!(taken.lock().unwrap().len(), 0, "{id}"); + assert!(!app.session.notices_since(mark).iter().any(|n| n.text.contains("offered")), "{id}"); + for most in [Some(usize::MAX), None] { + app.offer_most = most; + app.run(id, params.clone()).unwrap_or_else(|e| panic!("{id}: {e}")); + assert_eq!(std::mem::take(&mut *taken.lock().unwrap()), [file.clone()], "{id}"); + assert!(app.session.notices_since(mark).iter().any(|n| n.text.starts_with(&format!("Download offered: {file}"))), "{id}"); + assert!(!app.session.notices_since(mark).iter().any(|n| n.text.starts_with("Exported ")), "{id}"); + } + } + // A script on the same session writes to its path again. + let path = dir.path().join("after.geojson"); + app.run("share.exportLayer", json!({"layer": "Cities/Towns", "path": path})).unwrap(); + assert!(path.exists()); + } + /// The browser's Save Layout File downloads what `layout.save` writes, its header included, so /// an older RustGIS refuses what the layout uses that it can't keep (#2277). #[test] diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index f0cbaa2e26..ac21764aa1 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -106,7 +106,8 @@ they are offered, are dropped with a notice. A tool output dropped this way leav the geoprocessing history. A command is refused once its file passes what is left of the 256 MiB, as it is made where the format allows, and for a zipped format (a package, a zipped Shapefile, a KMZ) counting its files before they are zipped: choose fewer features or layers, a smaller size or -fewer pages, or use the desktop app. +fewer pages, or use the desktop app. The buttons that save, share and export in the web app run the +same commands, and what they download is held to the same 256 MiB. `share.exportLayer`, `data.convert`, `share.webMap`, `share.webLayer`, `share.geodataService` and `share.webScene` read a layer read in place whole for such a download, up to 256 MiB of From bedcaae2b349106d6a704c7afef843564f0e8569 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 22:36:52 -0600 Subject: [PATCH 2/4] test(ui): compare the offered name without a clone --- crates/ui-egui/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d4178363e7..5ef6a5155a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10333,7 +10333,7 @@ mod download_service_tests { for most in [Some(usize::MAX), None] { app.offer_most = most; app.run(id, params.clone()).unwrap_or_else(|e| panic!("{id}: {e}")); - assert_eq!(std::mem::take(&mut *taken.lock().unwrap()), [file.clone()], "{id}"); + assert_eq!(std::mem::take(&mut *taken.lock().unwrap()), [file.as_str()], "{id}"); assert!(app.session.notices_since(mark).iter().any(|n| n.text.starts_with(&format!("Download offered: {file}"))), "{id}"); assert!(!app.session.notices_since(mark).iter().any(|n| n.text.starts_with("Exported ")), "{id}"); } From 344499ca49f7130eddc8e1c6cf42b746ae1700d7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 00:39:09 -0600 Subject: [PATCH 3/4] refactor(engine): name the absence of a download limit, and say which buttons have one --- crates/engine/src/cmd/exports.rs | 10 +++++++--- crates/engine/src/cmd/gp.rs | 2 +- crates/engine/src/lib.rs | 4 ++-- crates/ui-egui/src/lib.rs | 9 ++++++--- docs/user-guide/sharing.md | 5 +++-- 5 files changed, 19 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 3cc713e5f2..7ad9378374 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -158,8 +158,9 @@ impl<'a> Output<'a> { /// A file that is written, or kept in the session: nothing limits it here. pub(crate) const UNLIMITED: Output<'static> = Output { path: "", room: None }; - /// A file the front end gets from the session itself, called `path` when it is refused: held to - /// the room a download has where files are downloaded. + /// A file the front end gets from the session itself, held to the room a download has where + /// files are downloaded. Its name isn't known until it is made, so a refusal calls it `path`, + /// what kind of file it is. pub(crate) fn here(s: &Session, path: &'a str) -> Result, String> { Ok(Output { path, room: s.download_room()? }) } @@ -289,12 +290,15 @@ pub(crate) fn mib(bytes: usize) -> usize { /// `rustgis_data::memory::planned` would give its floor there. pub const MAX_DOWNLOAD_BYTES: usize = 256 << 20; +/// What [`Session::offer_files`] is given for files that nothing limits but memory. +pub const NO_DOWNLOAD_LIMIT: usize = usize::MAX; + /// Every feature of layer `l`, read in place, for a file made in memory to be downloaded: refused /// past [`MAX_DOWNLOAD_BYTES`] of features, before any is read when the source's count alone says /// so. A definition query is applied after the read, so it doesn't make the read smaller. Where /// the file has no limit, neither has the read. pub(super) fn read_for_download(l: &rustgis_map::Layer, room: Room) -> Result<(Dataset, rustgis_map::Unreadable), String> { - if room.bytes == usize::MAX { l.load_all_counted() } else { read_for_download_after(l, 0) } + if room.bytes == NO_DOWNLOAD_LIMIT { l.load_all_counted() } else { read_for_download_after(l, 0) } } /// [`read_for_download`] for a file made of several layers, `held` bytes of whose features were diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 12b9612ffb..5204c080f9 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -3898,7 +3898,7 @@ fn queue(s: &mut Session, file_name: String, bytes: Arc>, from: Delivery Err(shared) => shared, }; let cap = s.download_cap(); - let held = if cap == usize::MAX { 0 } else { s.waiting_download_bytes() }; + let held = if cap == super::exports::NO_DOWNLOAD_LIMIT { 0 } else { s.waiting_download_bytes() }; // An export whose writer takes a limit was stopped at it; this is what holds the others (a // picture, an SVG, a PDF past its pages, the file a raster layer holds) to it. // Measured as the queue counts what waits: by what the file holds, its spare room included. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index fa25713442..a4188fdf3e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1863,7 +1863,7 @@ impl Session { /// For a front end whose button saves by downloading: until it is set back, a command that /// takes a path queues its file ([`Session::take_gp_files`]) as a browser's script does, held - /// to `most` bytes (`usize::MAX` for no limit but memory). It leaves saying that the file was + /// to `most` bytes ([`cmd::exports::NO_DOWNLOAD_LIMIT`] for no limit but memory). It leaves saying that the file was /// offered to the front end. Gives what was set before. pub fn offer_files(&mut self, most: Option) -> Option { std::mem::replace(&mut self.offering, most) @@ -1892,7 +1892,7 @@ impl Session { let waiting = self.waiting_download_bytes(); // No limit stays none whatever waits. let cap = self.download_cap(); - let bytes = if cap == usize::MAX { cap } else { cap.saturating_sub(waiting) }; + let bytes = if cap == cmd::exports::NO_DOWNLOAD_LIMIT { cap } else { cap.saturating_sub(waiting) }; if self.waiting_download_count() >= cmd::exports::MAX_DOWNLOADS || bytes == 0 { return Err(cmd::gp::queue_full(self.download_cap())); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5ef6a5155a..b0d3f450b9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3048,11 +3048,14 @@ impl RustGisApp { let name = name.replace(['/', '\\'], "_"); // Of something without a name: an extension alone isn't read as one. let name = if name.rfind('.') == Some(0) { format!("untitled{name}") } else { name }; - params["path"] = json!(name); + params.as_object_mut().ok_or("parameters are an object")?.insert("path".into(), json!(name)); let offered = offered.unwrap_or_else(|| Self::offered(&name)); // A phone's file goes to the system to save: nothing limits it but memory, as before. - let most = - if cfg!(any(target_os = "android", target_os = "ios")) { usize::MAX } else { rustgis_engine::cmd::exports::MAX_DOWNLOAD_BYTES }; + let most = if cfg!(any(target_os = "android", target_os = "ios")) { + rustgis_engine::cmd::exports::NO_DOWNLOAD_LIMIT + } else { + rustgis_engine::cmd::exports::MAX_DOWNLOAD_BYTES + }; #[cfg(test)] let most = self.offer_most.unwrap_or(most); let outer = (self.session.offer_files(Some(most)), self.offering.replace(offered)); diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index ac21764aa1..60fd8aac47 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -106,8 +106,9 @@ they are offered, are dropped with a notice. A tool output dropped this way leav the geoprocessing history. A command is refused once its file passes what is left of the 256 MiB, as it is made where the format allows, and for a zipped format (a package, a zipped Shapefile, a KMZ) counting its files before they are zipped: choose fewer features or layers, a smaller size or -fewer pages, or use the desktop app. The buttons that save, share and export in the web app run the -same commands, and what they download is held to the same 256 MiB. +fewer pages, or use the desktop app. The web app's buttons that save, share and export hold +what they download to the same 256 MiB, except Print Map, Export Model, the session log, the history +script and keyboard shortcuts. `share.exportLayer`, `data.convert`, `share.webMap`, `share.webLayer`, `share.geodataService` and `share.webScene` read a layer read in place whole for such a download, up to 256 MiB of From a91af9247281f7c9f89a2e57d5f442d42fac135c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 01:53:47 -0600 Subject: [PATCH 4/4] fix(ui): deliver the files already waiting before a button's own --- crates/engine/src/cmd/gp.rs | 9 ++++----- crates/ui-egui/src/lib.rs | 22 +++++++++++++++++++++- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 5204c080f9..6691f4dea3 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -3877,11 +3877,10 @@ pub(super) fn queue_export(s: &mut Session, mut wrote: super::exports::Wrote) -> /// Why no more can wait for download, of the `cap` bytes that waiting files may hold in all. pub(crate) fn queue_full(cap: usize) -> String { - format!( - "file export queue limit reached ({} files or {} MiB); split the task, model, or script into smaller runs", - super::exports::MAX_DOWNLOADS, - super::exports::mib(cap) - ) + let files = super::exports::MAX_DOWNLOADS; + // Without a limit on the bytes, only the files can be too many. + let bytes = if cap == super::exports::NO_DOWNLOAD_LIMIT { String::new() } else { format!(" or {} MiB", super::exports::mib(cap)) }; + format!("file export queue limit reached ({files} files{bytes}); split the task, model, or script into smaller runs") } /// Holds `bytes` for the front end to offer as the download `file_name` and acknowledge with diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b0d3f450b9..838e052267 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3048,7 +3048,7 @@ impl RustGisApp { let name = name.replace(['/', '\\'], "_"); // Of something without a name: an extension alone isn't read as one. let name = if name.rfind('.') == Some(0) { format!("untitled{name}") } else { name }; - params.as_object_mut().ok_or("parameters are an object")?.insert("path".into(), json!(name)); + params.as_object_mut().ok_or(tl!("parameters are an object"))?.insert("path".into(), json!(name)); let offered = offered.unwrap_or_else(|| Self::offered(&name)); // A phone's file goes to the system to save: nothing limits it but memory, as before. let most = if cfg!(any(target_os = "android", target_os = "ios")) { @@ -3058,6 +3058,9 @@ impl RustGisApp { }; #[cfg(test)] let most = self.offer_most.unwrap_or(most); + // A file another command left waiting goes first, saying what it says: this one's notice is + // for its own file. + let _ = self.deliver_gp_files(Ok(Value::Null)); let outer = (self.session.offer_files(Some(most)), self.offering.replace(offered)); // Run here, not on another thread: its file is offered as it ends. let ran = self.run_with_prepared(command, params, AppDispatch::Direct); @@ -10347,6 +10350,23 @@ mod download_service_tests { assert!(path.exists()); } + /// A file already waiting is delivered before a button's, so it says what it would have said and + /// doesn't take the button's line: a button's file the host refuses isn't said to be offered. + #[test] + fn a_file_already_waiting_doesnt_take_a_buttons_notice() { + let mut app = RustGisApp::with_sample().with_services(Services { + download: Some(Box::new(|name, _| if name == "first.geojson" { Ok(()) } else { Err("browser rejected download".into()) })), + ..Default::default() + }); + app.session.offer_files(Some(usize::MAX)); + app.session.run("map.save", &json!({"path": "first.geojson"})).unwrap(); + app.session.offer_files(None); + let mark = app.session.notice_mark(); + let e = app.run("ui.exportLayer", json!({"layer": "Cities", "format": "geojson"})).unwrap_err(); + assert!(e.contains("browser rejected download"), "{e}"); + assert!(!app.session.notices_since(mark).iter().any(|n| n.text.contains("Cities.geojson")), "{e}"); + } + /// The browser's Save Layout File downloads what `layout.save` writes, its header included, so /// an older RustGIS refuses what the layout uses that it can't keep (#2277). #[test]