From a5463c3ea6896c58cc6b1b25ae6c52a6882543d1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 20:31:08 -0600 Subject: [PATCH 01/10] 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 02/10] 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 03/10] 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 42dc73c8399cac45e712481a07a5b3d8411370af Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 01:38:18 -0600 Subject: [PATCH 04/10] fix(web): stop picture and document downloads as they pass the limit In the web app, a map, layout, report or presentation PNG, a layout SVG and a PDF were built whole and then compared with the room left for downloads. They are now held to it as they are made. - A downloaded PNG is written a row at a time from the pixmap into the limited buffer, without a second copy of the pixels. It decodes to the pixels encode_png's does; files that are written keep using encode_png. - A layout SVG is held to the room element by element and picture by picture. - A PDF is written into the limited buffer as it is made, and stream data is no longer copied into an object body first. The ribbon's buttons that call the engine's byte functions directly still have no limit. Part of #3153. --- crates/data/src/capped.rs | 12 +- crates/data/src/lib.rs | 1 + crates/data/src/png.rs | 160 +++++++++++++++++++++ crates/engine/src/cmd/exports.rs | 19 +++ crates/engine/src/cmd/layout/export.rs | 26 ++-- crates/engine/src/cmd/presentation.rs | 11 +- crates/engine/src/cmd/report.rs | 6 +- crates/engine/src/cmd/share.rs | 21 ++- crates/engine/src/cmd/view.rs | 2 +- crates/engine/src/tests/browser_exports.rs | 82 ++++++++++- crates/render/src/lib.rs | 10 +- crates/render/src/pdf.rs | 142 ++++++++++++------ crates/render/src/pdf/content.rs | 8 +- crates/render/src/pdf/fonts.rs | 3 +- crates/render/src/png.rs | 109 ++++++++++++++ crates/render/src/svg.rs | 88 +++++++++++- crates/render/src/svg/vectors.rs | 36 +++-- crates/render/tests/download_memory.rs | 63 ++++++++ 18 files changed, 699 insertions(+), 100 deletions(-) create mode 100644 crates/data/src/png.rs create mode 100644 crates/render/src/png.rs create mode 100644 crates/render/tests/download_memory.rs diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs index 2bb3dd920e..7563f3b783 100644 --- a/crates/data/src/capped.rs +++ b/crates/data/src/capped.rs @@ -48,13 +48,19 @@ impl Limit { } /// Whether there is a limit to pass: false for [`Limit::none`]. - pub(crate) fn bounded(&self) -> bool { + pub fn bounded(&self) -> bool { self.max != usize::MAX } + /// The most bytes the limit holds. + pub fn most(&self) -> usize { + self.max + } + /// Refuses, and notes the limit passed, when files that come to `bytes` can't be held: for a - /// writer to ask before it builds a large piece of them that would then be refused. - pub(crate) fn fits(&self, bytes: usize) -> Result<()> { + /// writer to ask before it builds a large piece of them that would then be refused, or as it + /// makes a file somewhere else than a buffer of this limit. + pub fn fits(&self, bytes: usize) -> Result<()> { if bytes <= self.max { return Ok(()); } diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 8f2258725f..3414c774d2 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -40,6 +40,7 @@ pub mod memory; pub mod ogc; pub mod osm; pub mod photo; +pub mod png; pub mod progress; pub mod provenance; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/data/src/png.rs b/crates/data/src/png.rs new file mode 100644 index 0000000000..017fa68e0c --- /dev/null +++ b/crates/data/src/png.rs @@ -0,0 +1,160 @@ +//! A PNG written a row at a time (ISO/IEC 15948), for a picture whose file is held to a limit +//! ([`crate::capped::Limit`]): it goes into the file as it is compressed, so neither a second copy +//! of its pixels nor its compressed stream is held beside it. + +use std::io::{Error, ErrorKind, Write}; + +use flate2::write::ZlibEncoder; +use flate2::{Compression, Crc}; + +use crate::capped::write_pieces; + +/// The bytes of a pixel: red, green, blue and alpha, 8 bits each. +const PIXEL: usize = 4; + +/// Writes an 8-bit RGBA picture of `width` × `height` pixels to `out` as a PNG. `row` is asked +/// for each row in turn from the top, and fills it with its pixels' red, green, blue and alpha, +/// the colours not multiplied by the alpha. It stops at the first write `out` refuses. +pub fn write_rgba(out: &mut W, width: u32, height: u32, mut row: impl FnMut(&mut [u8])) -> std::io::Result<()> { + let bytes = usize::try_from(width) + .ok() + .and_then(|w| w.checked_mul(PIXEL)) + .filter(|bytes| *bytes > 0 && *bytes < usize::MAX && height > 0) + .ok_or_else(|| Error::from(ErrorKind::InvalidInput))?; + out.write_all(b"\x89PNG\r\n\x1a\n")?; + let mut header = Vec::with_capacity(13); + header.extend_from_slice(&width.to_be_bytes()); + header.extend_from_slice(&height.to_be_bytes()); + // 8 bits a channel, colour with alpha, then the one compression, filter and no interlacing. + header.extend_from_slice(&[8, 6, 0, 0, 0]); + chunk(out, b"IHDR", &header)?; + // The rows make one zlib stream, cut into data chunks as it comes out. + let mut data = ZlibEncoder::new(ImageData(&mut *out), Compression::default()); + // This row and the one above it (zero above the first), and the smallest filtered form of the + // row so far beside the one being tried, each behind its filter's number. + let (mut line, mut above) = (vec![0; bytes], vec![0; bytes]); + let (mut best, mut tried) = (vec![0; bytes + 1], vec![0; bytes + 1]); + for _ in 0..height { + row(&mut line); + filter(&line, &above, &mut best, &mut tried); + data.write_all(&best)?; + std::mem::swap(&mut line, &mut above); + } + data.finish()?; + chunk(out, b"IEND", &[]) +} + +/// A chunk: its length, its four-letter kind, `data`, and the CRC-32 of the kind and the data. +fn chunk(out: &mut W, kind: &[u8; 4], data: &[u8]) -> std::io::Result<()> { + let length = u32::try_from(data.len()).map_err(|_| Error::from(ErrorKind::InvalidInput))?; + out.write_all(&length.to_be_bytes())?; + out.write_all(kind)?; + write_pieces(out, data)?; + let mut crc = Crc::new(); + crc.update(kind); + crc.update(data); + out.write_all(&crc.sum().to_be_bytes()) +} + +/// Writes what it is given to a PNG as image data chunks. +struct ImageData<'a, W: Write + ?Sized>(&'a mut W); + +impl Write for ImageData<'_, W> { + fn write(&mut self, data: &[u8]) -> std::io::Result { + if !data.is_empty() { + chunk(self.0, b"IDAT", data)?; + } + Ok(data.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.0.flush() + } +} + +/// Leaves in `best`, behind its filter's number, the filtered form of `line` (under `above`) that +/// is likely to compress smallest: the one whose bytes, taken as signed, sum to the least, as the +/// PNG specification suggests. `tried` is room for the others. +fn filter(line: &[u8], above: &[u8], best: &mut Vec, tried: &mut Vec) { + let mut least = u64::MAX; + for kind in 0..5 { + if let Some((number, filtered)) = tried.split_first_mut() { + *number = kind; + match kind { + 0 => predicted(line, above, filtered, |_, _, _| 0), + 1 => predicted(line, above, filtered, |left, _, _| left), + 2 => predicted(line, above, filtered, |_, up, _| up), + // The mean of the two, rounded down, without their sum. + 3 => predicted(line, above, filtered, |left, up, _| (left & up) + ((left ^ up) >> 1)), + _ => predicted(line, above, filtered, paeth), + } + // In pieces whose sums fit 32 bits, which add faster. + let sum = filtered + .chunks(1 << 16) + .map(|piece| u64::from(piece.iter().map(|b| u32::from((*b).min(b.wrapping_neg()))).sum::())) + .sum(); + if sum < least { + least = sum; + std::mem::swap(best, tried); + } + } + } +} + +/// Writes to `out` each byte of `line` less what `predict` makes of the bytes a pixel to its left, +/// above it, and above that left one; zero for those off the picture's left. +#[inline] +fn predicted(line: &[u8], above: &[u8], out: &mut [u8], predict: impl Fn(u8, u8, u8) -> u8) { + for ((to, byte), up) in out.iter_mut().zip(line).zip(above).take(PIXEL) { + *to = byte.wrapping_sub(predict(0, *up, 0)); + } + let rest = out.iter_mut().skip(PIXEL); + let right = line.get(PIXEL..).unwrap_or_default().iter().zip(line); + let upper = above.get(PIXEL..).unwrap_or_default().iter().zip(above); + for (to, ((byte, left), (up, corner))) in rest.zip(right.zip(upper)) { + *to = byte.wrapping_sub(predict(*left, *up, *corner)); + } +} + +/// The Paeth predictor (the PNG specification's): of the bytes left, above and above-left, the one +/// nearest `left + up - corner`, ties going to the left one and then the one above. +fn paeth(left: u8, up: u8, corner: u8) -> u8 { + let (a, b) = (i16::from(up) - i16::from(corner), i16::from(left) - i16::from(corner)); + let (to_left, to_up, to_corner) = (a.abs(), b.abs(), (a + b).abs()); + if to_left <= to_up && to_left <= to_corner { + left + } else if to_up <= to_corner { + up + } else { + corner + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::capped::Limit; + + /// A picture past its limit is refused as its file passes it, the rows after that never asked + /// for. + #[test] + fn a_png_past_its_limit_stops_asking_for_rows() { + // Noise, which hardly compresses: 4,000 bytes a row. + let mut state = 7u32; + let mut asked = 0; + let limit = Limit::new(40_000); + let made = limit.file(|out| { + write_rgba(out, 1000, 1000, |line| { + asked += 1; + line.fill_with(|| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }); + })?; + Ok(()) + }); + assert!(made.is_err() && limit.passed()); + // The compressor hands on what it makes every few tens of rows. + assert!(asked < 100, "{asked} rows asked for"); + } +} diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 04357ea7f7..221da73273 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -143,6 +143,20 @@ impl Room { } } +/// What `make` makes of a file held to the limit it is given. Where the file is downloaded +/// (`download`: the room it has, and its name) that is the room, and a file stopped as it passed +/// it is refused as such; where it is written, there is no limit but memory. +pub(crate) fn held_to( + download: Option<(Room, &str)>, + make: impl FnOnce(&Limit) -> Result, +) -> Result { + let limit = download.map_or_else(Limit::none, |(room, _)| Limit::new(room.bytes)); + make(&limit).map_err(|why| match download { + Some((room, path)) if limit.passed() => room.refusal(path), + _ => why.to_string(), + }) +} + /// 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"; @@ -164,6 +178,11 @@ impl<'a> Output<'a> { self.room.is_some() } + /// [`held_to`] for this file. + pub(crate) fn held_to(self, make: impl FnOnce(&Limit) -> Result) -> Result { + held_to(self.room.map(|room| (room, self.path)), make) + } + /// The most bytes it may come to. pub(crate) fn most(self) -> usize { self.room.map_or(usize::MAX, |room| room.bytes) diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index 2fb140a179..86c7277a88 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -33,8 +33,8 @@ pub fn layout_bytes_with( layout_bytes_for(s, li, pdf, dpi, all, georeference, options, None) } -/// [`layout_bytes_with`] for a file that may be downloaded to the path given: a PDF's pages are -/// then held to that room too, and stopped as they pass it. +/// [`layout_bytes_with`] for a file that may be downloaded to the path given: the file, and a +/// PDF's pages as they are drawn, are then held to that room, and stopped as they pass it. #[expect(clippy::too_many_arguments, reason = "the export's own settings")] fn layout_bytes_for( s: &mut Session, @@ -273,7 +273,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( } } else { let img = rustgis_render::layout::render(layout, &mut s.project.maps, dpi, &info)?; - png = Some(img.encode_png().map_err(|e| e.to_string())?); + png = Some(crate::cmd::exports::held_to(download, |limit| rustgis_render::png::within(&img, limit))?); } // A cancelled export stops here, its layout put back below. rustgis_data::progress::step(1).map_err(|e| e.to_string())?; @@ -312,7 +312,8 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( if !pdf { return png.ok_or_else(|| "nothing to draw".to_string()); } - let (bytes, outlined) = rustgis_render::pdf::write_with(&pages, &saved.name, options); + let (bytes, outlined) = + crate::cmd::exports::held_to(download, |limit| rustgis_render::pdf::write_with_within(&pages, &saved.name, options, limit))?; outlined_notice(s, &outlined); Ok(bytes) } @@ -501,11 +502,11 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Result Result { +/// pictures at `dpi`; a frame too large for vectors is a picture, and the export says so. Where +/// it is downloaded (`download`: its room and name), it is stopped as it passes the room. +fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd::exports::Room, &str)>) -> Result { let dpi = if dpi.is_finite() { dpi.clamp(36.0, 600.0) } else { 150.0 }; let current = s.project.layouts.get(li).ok_or("no layout")?.series.as_ref().map_or(0, |sr| sr.page); let series = series_info(s, li, current); @@ -536,7 +538,11 @@ pub(in crate::cmd::layout) fn layout_svg(s: &mut Session, li: usize, dpi: f64) - let note = rustgis_render::layout::clipped_text_notice(layout, &clipped); let gaps = rustgis_render::layout::sections_not_drawn(layout, &s.project.maps).into_iter().map(|g| (g, 1)).collect(); let ((drawn, unfitted), charts) = rustgis_render::layout::drawn_charts(|| { - rustgis_render::layout::unfitted_legends(|| rustgis_render::svg::layout_svg(layout, &mut s.project.maps, dpi, &info)) + rustgis_render::layout::unfitted_legends(|| { + crate::cmd::exports::held_to(download, |limit| { + rustgis_render::svg::layout_svg_within(layout, &mut s.project.maps, dpi, &info, limit) + }) + }) }); let (text, pictured) = drawn?; let chart_notes = chart_notice_lines(layout, &charts); diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index bc52ebf6e5..7526c486b5 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -1,7 +1,6 @@ //! Publish › Presentation (New and Import Presentation), Publish › Page (Map, Blank, Image, Video), and //! Publish › Save As (Presentation File) and Output (Export Presentation): presentations. -use base64::Engine; use rustgis_geom::Coord; use rustgis_map::Rgba; use rustgis_map::layout::{ElementKind, FrameShape, Layout}; @@ -513,8 +512,8 @@ pub fn export_bytes(s: &mut Session, i: usize, format: &str, dpi: f64) -> Result export_within(s, i, format, dpi, super::exports::Output::UNLIMITED) } -/// [`export_bytes`] for the file `out` describes: a downloaded PDF or slideshow stops at the page -/// that passes its room. +/// [`export_bytes`] for the file `out` describes: a downloaded file, and the pages of a PDF or +/// slideshow as they are drawn, are stopped as they pass its room. fn export_within(s: &mut Session, i: usize, format: &str, dpi: f64, out: super::exports::Output<'_>) -> Result<(Vec, usize), String> { let revision = |s: &Session| { rustgis_render::archive_revisions(s.project.presentations.get(i).into_iter().flat_map(|p| { @@ -548,7 +547,7 @@ fn export_bytes_inner( } if format == "png" { let img = draw_page(s, i, 0, dpi)?; - return Ok((img.encode_png().map_err(|e| e.to_string())?, 1)); + return Ok((out.held_to(|limit| rustgis_render::png::within(&img, limit))?, 1)); } let mut pdf_pages = Vec::new(); let mut slides = String::new(); @@ -570,7 +569,7 @@ fn export_bytes_inner( } else { let img = draw_page(s, i, k, dpi)?; let page = s.project.presentations.get(i).and_then(|p| p.pages.get(k)).ok_or("no page")?; - let png = base64::engine::general_purpose::STANDARD.encode(img.encode_png().map_err(|e| e.to_string())?); + let png = out.held_to(|limit| rustgis_render::png::base64_within(&img, limit, slides.len()))?; held += png.len(); let body = match &page.kind { // The poster is the drawn page, which already shows the title and caption. The @@ -608,7 +607,7 @@ fn export_bytes_inner( crate::durable::notify(s, &output_report); if format == "pdf" { super::layout::pictured_notices(s, &frames_pictured, &pages_pictured); - return Ok((rustgis_render::pdf::write(&pdf_pages, &name), n)); + return Ok((out.held_to(|limit| rustgis_render::pdf::write_within(&pdf_pages, &name, limit))?, n)); } let html = format!( r#" diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index f0e7c4ab43..15106a43e0 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1220,7 +1220,8 @@ fn report_pages_bytes( say_report_charts(s, &charts); say_report_clipped(s, &clipped); say_sections_not_drawn(s, pages, 1); - return Ok((img.encode_png().map_err(|e| e.to_string())?, pages.len())); + let png = super::exports::held_to(download, |limit| rustgis_render::png::within(&img, limit))?; + return Ok((png, pages.len())); } let (drawn, listed, shown) = listing(|| rustgis_render::report::pdf_page(doc, pages, k, dpi, &s.project.layouts, &mut s.project.maps)); @@ -1256,7 +1257,8 @@ fn report_pages_bytes( say_report_clipped(s, &clipped); super::layout::pictured_notices(s, &frames_pictured, &pages_pictured); say_sections_not_drawn(s, pages, n); - Ok((rustgis_render::pdf::write(&out, &doc.title), pages.len())) + let pdf = super::exports::held_to(download, |limit| rustgis_render::pdf::write_within(&out, &doc.title, limit))?; + Ok((pdf, pages.len())) } /// Says the section lines (#2863) the layouts of the first `n` of `pages` don't draw, as the diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index d0c0bedf2f..e1981505f3 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -7,6 +7,7 @@ pub(super) use table::table_work; use std::path::Path; +use rustgis_data::capped::Limit; use rustgis_data::io::{GpkgMode, GpkgTable, GpkgWritten}; use rustgis_data::raster::Crs; use rustgis_render::View; @@ -178,7 +179,7 @@ pub fn map_png_fitted(s: &mut Session, dpi: f64) -> Result, String> { /// without their cast shadows are said ([`saying_shadows`]). pub fn map_png(s: &mut Session, width: Option, height: Option, dpi: Option) -> Result, String> { let view_size = s.view_size; - saying_shadows(s, "The map image", |s| png_of(s.map_mut(), view_size, width, height, dpi)) + saying_shadows(s, "The map image", |s| png_of(s.map_mut(), view_size, width, height, dpi, &Limit::none())) } /// [`map_png`] for a caller that draws several frames inside one [`saying_shadows`], which says @@ -186,7 +187,7 @@ pub fn map_png(s: &mut Session, width: Option, height: Option, dpi: Op #[cfg(not(target_arch = "wasm32"))] pub(super) fn map_png_unsaid(s: &mut Session, width: Option, height: Option, dpi: Option) -> Result, String> { let view_size = s.view_size; - png_of(s.map_mut(), view_size, width, height, dpi) + png_of(s.map_mut(), view_size, width, height, dpi, &Limit::none()) } /// Runs `draw`, which draws maps or pages for `s` (an image, an export, a shared item), and says @@ -217,18 +218,20 @@ pub(crate) fn shadow_warnings(what: &str, said: &rustgis_render::ShadowsSaid) -> out } -/// Renders `map` at its camera in a view of `(vw, vh)` points (or a requested size) to PNG bytes. +/// Renders `map` at its camera in a view of `(vw, vh)` points (or a requested size) to PNG bytes, +/// held to `limit`. pub(super) fn png_of( map: &mut rustgis_map::Map, view_size: (f64, f64), width: Option, height: Option, dpi: Option, + limit: &Limit, ) -> Result, String> { let view = export_view(map.camera, view_size, width, height, dpi); // Past the canvas's limit the picture would be cut off at its top left: refused instead. fits_pixels(&view, false)?; - rustgis_render::render_png(map, &view) + rustgis_render::render_png_within(map, &view, limit) } /// Refuses an export of `view` with a side past the [`rustgis_render::MAX_SIDE`] pixels a canvas @@ -421,17 +424,21 @@ pub(crate) fn map_work(s: &Session, p: &Value) -> Result { return Err("cog is for a GeoTIFF (.tif or .tiff) export".into()); } let (mut map, view_size) = (s.map().detached(), s.view_size); - let download = s.download_room()?.is_some(); + let download = s.download_room()?; Ok(Box::new(move || { let mut shadows = Vec::new(); let mut held = None; let written = (|| { - let (png, said) = rustgis_render::shadows_said(|| png_of(&mut map, view_size, width, height, dpi)); + let (png, said) = rustgis_render::shadows_said(|| { + super::exports::held_to(download.map(|room| (room, path.as_str())), |limit| { + png_of(&mut map, view_size, width, height, dpi, limit) + }) + }); let png = png?; shadows = shadow_warnings(&path, &said); rustgis_data::progress::check().map_err(|e| e.to_string())?; let bytes = png.len(); - held = super::exports::place(download, &path, png)?; + held = super::exports::place(download.is_some(), &path, png)?; Ok(json!({"path": path, "bytes": bytes})) })(); // What the size limit did, and layers drawn without their cast shadows, are said of a diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index a1dff0a23d..cc4aff9c8f 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -266,7 +266,7 @@ pub(crate) fn orbit_work(s: &Session, p: &Value) -> Result) -> (String, Ve (name, bytes.to_vec(), answer) } +/// What a picture, or a slideshow of pictures, shows: its text without the pictures' data, and +/// their pixels. A downloaded PNG is compressed otherwise than a written one, so the two are +/// compared by what they decode to. +fn shown(file: &[u8]) -> (String, Vec) { + let picture = |png: &[u8]| crate::render::Pixmap::decode_png(png).unwrap(); + if file.starts_with(b"\x89PNG") { + return (String::new(), vec![picture(file)]); + } + let mut parts = std::str::from_utf8(file).unwrap().split("data:image/png;base64,"); + let mut text = parts.next().unwrap().to_string(); + let mut pictures = Vec::new(); + for part in parts { + let (data, after) = part.split_once('"').unwrap(); + pictures.push(picture(&base64::engine::general_purpose::STANDARD.decode(data).unwrap())); + text.push_str(after); + } + (text, pictures) +} + /// Each export command the browser can run downloads the file the desktop writes, under the /// path's name, and says of it what the desktop says, once the download is taken. #[test] @@ -77,7 +97,7 @@ fn a_browser_export_by_path_downloads_the_desktops_file_and_says_the_same() { ("data.convert", json!({"layer": "Places", "format": "csv"}), "z.csv", true), ("share.exportRaster", json!({"layer": "Dem"}), "dem.tif", true), ("share.exportRaster", json!({"layer": "Dem", "cog": true}), "cog.tif", true), - ("share.exportMap", json!({"width": 64, "height": 64}), "map.png", true), + ("share.exportMap", json!({"width": 64, "height": 64}), "map.png", false), ("share.exportMap", json!({"width": 64, "height": 64}), "map.tif", true), ("share.exportMap", json!({"width": 64, "height": 64, "cog": true}), "mapcog.tif", true), ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.pdf", false), @@ -119,6 +139,9 @@ fn a_browser_export_by_path_downloads_the_desktops_file_and_says_the_same() { assert!(bytes == written, "{command} {file}: {} bytes downloaded, {} written", bytes.len(), written.len()); } else { assert_eq!(bytes.get(..4), written.get(..4), "{command} {file}"); + if file.ends_with(".png") { + assert!(shown(&bytes) == shown(&written), "{command} {file}: other pixels"); + } } assert_eq!(said(&browser, mark), desktop_said, "{command} {file}"); let answer = answer.unwrap(); @@ -430,10 +453,10 @@ fn a_browser_export_over_the_limit_is_stopped_as_it_is_made() { ("share.exportMap", json!({"width": 64, "height": 64, "cog": true}), "mapcog.tif", STOPPED), ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.pdf", STOPPED), ("report.export", json!({"report": "List", "dpi": 72}), "list.pdf", STOPPED), - ("share.exportMap", json!({"width": 64, "height": 64}), "map.png", MADE), - ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.png", MADE), - ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.svg", MADE), - ("report.export", json!({"report": "List", "dpi": 72}), "list.png", MADE), + ("share.exportMap", json!({"width": 64, "height": 64}), "map.png", STOPPED), + ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.png", STOPPED), + ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.svg", STOPPED), + ("report.export", json!({"report": "List", "dpi": 72}), "list.png", STOPPED), ("share.exportRaster", json!({"layer": "Made"}), "made.tif", MADE), ]; for (command, ..) in crate::cmd::exports::IN_BACKGROUND { @@ -457,6 +480,49 @@ fn a_browser_export_over_the_limit_is_stopped_as_it_is_made() { } } +/// A picture or a document is held to the room as it is made, not compared with it once made: a +/// room a little under its size is refused as every export stopped there is. A picture's size +/// is room enough for it. +#[test] +fn a_browser_picture_or_document_past_its_room_is_stopped_as_it_is_made() { + let files = Files::new(); + let mut s = items(&files, true); + // Command, other parameters, file name, and how far under its size the room is set: two + // writes of a PDF may differ by a few bytes. + let cases = [ + ("share.exportMap", json!({"width": 64, "height": 64}), "map.png", 1), + ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.png", 1), + ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.svg", 1), + ("layout.export", json!({"layout": "Page", "dpi": 72}), "page.pdf", 64), + ("report.export", json!({"report": "List", "dpi": 72}), "list.png", 1), + ("report.export", json!({"report": "List", "dpi": 72}), "list.pdf", 64), + ("presentation.export", json!({"dpi": 48}), "s.png", 1), + ("presentation.export", json!({"dpi": 48}), "s.html", 1), + ("presentation.export", json!({"dpi": 48}), "s.pdf", 64), + ]; + let mut failed = Vec::new(); + for (command, params, file, under) in cases { + let export = |s: &mut Session, cap: Option| { + s.download_cap = cap; + s.run(command, &to(¶ms, file)) + }; + let pending = export(&mut s, None).unwrap_or_else(|e| panic!("{command} {file}: {e}")); + let (_, whole, answer) = deliver(&mut s, &pending, None); + answer.unwrap(); + let e = export(&mut s, Some(whole.len() - under)).unwrap_err(); + if !(e.contains(file) && e.contains("stopped once the file passed")) { + failed.push(e); + } + assert!(s.take_gp_files().is_empty(), "{command} {file}"); + // A PDF is also held to what its pages take before they are written, which may be more. + if under == 1 { + let pending = export(&mut s, Some(whole.len())).unwrap_or_else(|e| panic!("{command} {file}: {e}")); + deliver(&mut s, &pending, None).2.unwrap(); + } + } + assert!(failed.is_empty(), "{failed:#?}"); +} + /// The limit is what the downloads waiting leave of it: an export that would fit by itself is /// refused, saying what is waiting, and a full queue is refused before anything is made. #[test] @@ -638,9 +704,9 @@ fn file_cases() -> Vec<(&'static str, Value, &'static str, bool)> { ("report.save", json!({"report": "List"}), "r.rgisreport", true), ("report.saveTemplate", json!({"report": "List"}), "r.rgisrpttemplate", true), ("presentation.save", json!({}), "s.rgispres", true), - ("presentation.export", json!({}), "s.html", true), + ("presentation.export", json!({}), "s.html", false), ("presentation.export", json!({"dpi": 48}), "s.pdf", false), - ("presentation.export", json!({"dpi": 48}), "s.png", true), + ("presentation.export", json!({"dpi": 48}), "s.png", false), ("notebook.save", json!({}), "n.rgisnb", true), ("notebook.save", json!({}), "n.ipynb", true), ("model.export", json!({"name": "Ring"}), "ring.model.json", true), @@ -729,6 +795,8 @@ fn a_browser_file_command_downloads_the_desktops_file_and_says_the_same() { assert_eq!(name, file); if same_bytes { assert!(bytes == written, "{command} {file}: {} bytes downloaded, {} written", bytes.len(), written.len()); + } else if file.ends_with(".png") || file == "s.html" { + assert!(shown(&bytes) == shown(&written), "{command} {file}: other pictures or text"); } else { assert_same_shape(&bytes, &written, &format!("{command} {file}")); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 0392c64f5f..45e0c2afda 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -32,6 +32,7 @@ mod native_tiles; mod pattern_fill; pub mod pdf; mod picture; +pub mod png; mod point_marks; pub mod post; mod raster; @@ -394,6 +395,7 @@ use std::sync::OnceLock; pub use block::{FlatWalls, flat_walls}; pub(crate) use canvas::Canvas; +use rustgis_data::capped::Limit; use rustgis_data::query::Env; use rustgis_data::{Dataset, Geometry, GeometryType}; use rustgis_geom::{Coord, Extent, extent_to_merc, lonlat_to_merc}; @@ -9055,6 +9057,12 @@ pub(crate) fn draw_labels(pm: &mut Canvas, (unplaced, labels, layers): (&[Placed /// Renders a map with its labels, a scale bar and a north arrow to PNG bytes. /// Refuses an archive changed during rendering or encoding; a caller must not write a destination on error. pub fn render_png(map: &mut Map, view: &View) -> Result, String> { + render_png_within(map, view, &Limit::none()) +} + +/// [`render_png`] for a file held to `limit`, such as a download: the PNG is stopped as it passes +/// that, which the limit then says ([`Limit::passed`]). +pub fn render_png_within(map: &mut Map, view: &View, limit: &Limit) -> Result, String> { let revisions = archive_revisions([&*map]); let r = render_exported(map, view)?; let mut pm = Canvas::from_pixmap(r.pixmap); @@ -9063,7 +9071,7 @@ pub fn render_png(map: &mut Map, view: &View) -> Result, String> { } text::scale_bar(&mut pm, view, map.ground_res_at(&view.camera)); draw_attribution(&mut pm, &r.attribution, view.pixels_per_point as f32, (0.0, 0.0)); - let png = pm.into_pixmap().encode_png().map_err(|e| e.to_string())?; + let png = png::within(&pm.into_pixmap(), limit)?; revisions.finish(map, None, Some(png), "could not encode the image") } diff --git a/crates/render/src/pdf.rs b/crates/render/src/pdf.rs index 248113e2d9..50325c78a0 100644 --- a/crates/render/src/pdf.rs +++ b/crates/render/src/pdf.rs @@ -6,6 +6,9 @@ //! drawing's layers (layout elements, map layers, their labels) become optional content groups, //! which vector editors open as layers ([`Options::layers`]). +use std::io::Write; + +use rustgis_data::capped::Limit; use tiny_skia::Pixmap; use crate::vector::{Drawing, Item, deflate_rows}; @@ -156,8 +159,13 @@ fn page_mm(v: f64) -> f64 { /// The objects of a document being written, in the order written; each is numbered when /// reserved, so objects can refer to ones written later. -pub(crate) struct Doc { - out: Vec, +pub(crate) struct Doc<'a> { + /// Where it is written, as it is made. + out: &'a mut dyn Write, + /// How many bytes are written: where the next object starts. + at: usize, + /// Why a write was refused, as by a file passing its limit: nothing more is written then. + failed: Option, offsets: Vec>, /// Shared pictures' image objects, by their pixels' address and whether smoothed (see /// [`crate::vector::Image::shared`]): written once, placed wherever drawn. The pixels are @@ -165,17 +173,29 @@ pub(crate) struct Doc { pub(crate) images: std::collections::HashMap<(usize, bool), (std::sync::Arc, usize)>, } -impl Doc { - /// A document with only its header written. - fn new() -> Doc { - Doc::of_version("1.4") +impl<'a> Doc<'a> { + /// A document with only its header written to `out`. + #[cfg(test)] + fn new(out: &'a mut dyn Write) -> Doc<'a> { + Doc::of_version(out, "1.4") + } + + /// A document of PDF version `version` with only its header written to `out`. + fn of_version(out: &'a mut dyn Write, version: &str) -> Doc<'a> { + let mut doc = Doc { out, at: 0, failed: None, offsets: Vec::new(), images: std::collections::HashMap::new() }; + doc.write(format!("%PDF-{version}\n").as_bytes()); + doc.write(b"%\xE2\xE3\xCF\xD3\n"); + doc } - /// A document of PDF version `version` with only its header written. - fn of_version(version: &str) -> Doc { - let mut out = format!("%PDF-{version}\n").into_bytes(); - out.extend_from_slice(b"%\xE2\xE3\xCF\xD3\n"); - Doc { out, offsets: Vec::new(), images: std::collections::HashMap::new() } + /// Writes `bytes` next, unless a write was refused before. + fn write(&mut self, bytes: &[u8]) { + if self.failed.is_none() { + match self.out.write_all(bytes) { + Ok(()) => self.at += bytes.len(), + Err(e) => self.failed = Some(e), + } + } } /// A new object's number. @@ -186,16 +206,27 @@ impl Doc { /// Writes object `id`'s `body`; nothing for a number never reserved or already written. pub(crate) fn put(&mut self, id: usize, body: &[u8]) { + self.object(id, &[body]); + } + + /// [`Doc::put`] of a body made of `parts`, written one after the other. + fn object(&mut self, id: usize, parts: &[&[u8]]) { let Some(slot @ None) = self.offsets.get_mut(id.wrapping_sub(1)) else { return }; - *slot = Some(self.out.len()); - self.out.extend_from_slice(format!("{id} 0 obj\n").as_bytes()); - self.out.extend_from_slice(body); - self.out.extend_from_slice(b"\nendobj\n"); + *slot = Some(self.at); + self.write(format!("{id} 0 obj\n").as_bytes()); + for part in parts { + self.write(part); + } + self.write(b"\nendobj\n"); } /// Writes object `id` as a stream of `data`, its dictionary's other entries `dict`, /// compressed unless it already is (`deflated`). pub(crate) fn stream(&mut self, id: usize, dict: &str, data: &[u8], deflated: bool) { + // Nothing more is written, so nothing is compressed for it. + if self.failed.is_some() { + return; + } let z; let (data, filter) = if deflated { (data, " /Filter /FlateDecode") @@ -205,29 +236,25 @@ impl Doc { } else { (data, "") }; - let mut body = format!("<< {dict}{filter} /Length {} >>\nstream\n", data.len()).into_bytes(); - body.reserve(data.len() + 11); - body.extend_from_slice(data); - body.extend_from_slice(b"\nendstream"); - self.put(id, &body); + // The data is written from where it is, not copied into a body first. + let head = format!("<< {dict}{filter} /Length {} >>\nstream\n", data.len()); + self.object(id, &[head.as_bytes(), data, b"\nendstream"]); } - /// The finished document: objects reserved and never written become nulls. - fn finish(mut self, root: usize, info: usize) -> Vec { + /// Finishes the document, objects reserved and never written becoming nulls; why it isn't + /// whole, when a write was refused. + fn finish(mut self, root: usize, info: usize) -> std::io::Result<()> { for id in 1..=self.offsets.len() { self.put(id, b"null"); } - let xref = self.out.len(); - let mut out = self.out; - out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", self.offsets.len() + 1).as_bytes()); - for o in &self.offsets { - out.extend_from_slice(format!("{:010} 00000 n \n", o.unwrap_or(0)).as_bytes()); + let (xref, size) = (self.at, self.offsets.len() + 1); + self.write(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes()); + for at in 0..self.offsets.len() { + let offset = self.offsets.get(at).copied().flatten().unwrap_or(0); + self.write(format!("{offset:010} 00000 n \n").as_bytes()); } - out.extend_from_slice( - format!("trailer\n<< /Size {} /Root {root} 0 R /Info {info} 0 R >>\nstartxref\n{xref}\n%%EOF\n", self.offsets.len() + 1) - .as_bytes(), - ); - out + self.write(format!("trailer\n<< /Size {size} /Root {root} 0 R /Info {info} 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes()); + self.failed.map_or(Ok(()), Err) } } @@ -333,14 +360,41 @@ fn has_layer(items: &[Item]) -> bool { /// Writes the pages as a PDF document, with their layers, its text in outlines /// ([`Text::Outlines`]). pub fn write(pages: &[Page], title: &str) -> Vec { - write_with(pages, title, Options { text: Text::Outlines, ..Options::default() }).0 + write_with(pages, title, OUTLINED).0 +} + +/// [`write`] for a file held to `limit`, such as a download: stopped as it passes that. +pub fn write_within(pages: &[Page], title: &str, limit: &Limit) -> rustgis_data::Result> { + write_with_within(pages, title, OUTLINED, limit).map(|(file, _)| file) } +/// How [`write`] writes a document. +const OUTLINED: Options = Options { layers: true, text: Text::Outlines }; + /// Writes the pages as a PDF document, as `options` say, and the faces set in outlines though /// fonts were asked for. Each face is subset in one step; between faces it looks at Cancel /// (`rustgis_data::progress`), and once cancelled sets the faces left in outlines, unsaid: a /// cancelled export writes nothing. pub fn write_with(pages: &[Page], title: &str, options: Options) -> (Vec, Vec) { + let mut out = Vec::new(); + // Writing into memory isn't refused. + let outlined = write_to(&mut out, pages, title, options).unwrap_or_default(); + (out, outlined) +} + +/// [`write_with`] for a file held to `limit`, such as a download: the document is stopped as it +/// passes that, which the limit then says ([`Limit::passed`]), and the pages left aren't written. +pub fn write_with_within(pages: &[Page], title: &str, options: Options, limit: &Limit) -> rustgis_data::Result<(Vec, Vec)> { + let mut outlined = Vec::new(); + let file = limit.file(|out| { + outlined = write_to(out, pages, title, options)?; + Ok(()) + })?; + Ok((file, outlined)) +} + +/// [`write_with`]'s document written to `out` as it is made, up to the first write refused. +fn write_to(out: &mut dyn Write, pages: &[Page], title: &str, options: Options) -> std::io::Result> { // Every face's glyphs, gathered before any is written: a face is embedded or not as a whole, // and its glyphs' codes are the subset's. let mut used: Vec<(&'static ab_glyph::FontRef<'static>, Vec)> = Vec::new(); @@ -371,20 +425,24 @@ pub fn write_with(pages: &[Page], title: &str, options: Options) -> (Vec, Ve // holds is 1.4. let geo = pages.iter().any(|p| !p.viewports.is_empty()); let layered = options.layers && pages.iter().any(|p| matches!(&p.content, Content::Vector { items, .. } if has_layer(items))); - let mut doc = if geo { - Doc::of_version("1.7") + let version = if geo { + "1.7" } else if real.iter().any(|(_, e)| e.cff) { - Doc::of_version("1.6") + "1.6" } else if layered { - Doc::of_version("1.5") + "1.5" } else { - Doc::new() + "1.4" }; + let mut doc = Doc::of_version(out, version); let (catalog, tree, info) = (doc.reserve(), doc.reserve(), doc.reserve()); let ids: Vec = pages.iter().map(|_| doc.reserve()).collect(); let mut fonts = fonts::Fonts::with_real(&mut doc, real); let mut layers = Layers { on: layered, ..Layers::default() }; for (p, &page) in pages.iter().zip(&ids) { + if doc.failed.is_some() { + break; + } let (pw, ph) = (p.width_mm * 72.0 / 25.4, p.height_mm * 72.0 / 25.4); let (contents, resources) = match &p.content { Content::Picture { width, height, rgb_z } => { @@ -425,7 +483,8 @@ pub fn write_with(pages: &[Page], title: &str, options: Options) -> (Vec, Ve let kids: Vec = ids.iter().map(|i| format!("{i} 0 R")).collect(); doc.put(tree, format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids.join(" "), pages.len()).as_bytes()); doc.put(info, format!("<< /Title {} /Producer (RustGIS) >>", text_string(title)).as_bytes()); - (doc.finish(catalog, info), outlined) + doc.finish(catalog, info)?; + Ok(outlined) } /// Faces' places in the list of glyphs used, by their address, and the glyphs already listed. @@ -722,12 +781,13 @@ pub(crate) mod tests { #[test] fn unwritten_objects_become_nulls_and_writing_twice_keeps_the_first() { - let mut doc = Doc::new(); + let mut pdf = Vec::new(); + let mut doc = Doc::new(&mut pdf); let (a, b) = (doc.reserve(), doc.reserve()); doc.put(a, b"<< /Type /Catalog >>"); doc.put(a, b"<< /Twice true >>"); doc.put(99, b"never reserved"); - let pdf = doc.finish(a, b); + doc.finish(a, b).unwrap(); let objs = objects(&pdf); assert_eq!(objs.len(), 2); assert_eq!((objs[0].0.as_str(), objs[1].0.as_str()), ("<< /Type /Catalog >>", "null")); diff --git a/crates/render/src/pdf/content.rs b/crates/render/src/pdf/content.rs index 5f473cf219..27e4626d49 100644 --- a/crates/render/src/pdf/content.rs +++ b/crates/render/src/pdf/content.rs @@ -20,7 +20,7 @@ use crate::vector::{Brush, Clip, GlyphRun, Group, Image, Item, Pixels, Stroke}; /// Writes the content of a page `size` (drawing pixels) shown at `page` (points); its content /// stream's and resource dictionary's object numbers. pub(super) fn page( - doc: &mut Doc, + doc: &mut Doc<'_>, fonts: &mut Fonts, layers: &mut Layers, size: (f32, f32), @@ -120,8 +120,8 @@ struct State { miter: Option, } -struct Writer<'a> { - doc: &'a mut Doc, +struct Writer<'a, 'out> { + doc: &'a mut Doc<'out>, fonts: &'a mut Fonts, layers: &'a mut Layers, res: Resources, @@ -132,7 +132,7 @@ struct Writer<'a> { siblings: HashMap<(Option, String), usize>, } -impl Writer<'_> { +impl Writer<'_, '_> { /// Writes `items` in order. fn items(&mut self, out: &mut Vec, st: &mut State, items: &[Item]) { let mut rest = items.iter().peekable(); diff --git a/crates/render/src/pdf/fonts.rs b/crates/render/src/pdf/fonts.rs index d20836f72f..37bb40f274 100644 --- a/crates/render/src/pdf/fonts.rs +++ b/crates/render/src/pdf/fonts.rs @@ -351,7 +351,8 @@ mod tests { #[test] fn glyphs_share_a_font_until_it_holds_256() { let font = crate::text::label_font().unwrap(); - let mut doc = Doc::new(); + let mut out = Vec::new(); + let mut doc = Doc::new(&mut out); let mut fonts = Fonts::default(); let a = fonts.place(&mut doc, font, font.glyph_id('A'), 'A').unwrap(); let again = fonts.place(&mut doc, font, font.glyph_id('A'), 'A').unwrap(); diff --git a/crates/render/src/png.rs b/crates/render/src/png.rs new file mode 100644 index 0000000000..0e92ee5885 --- /dev/null +++ b/crates/render/src/png.rs @@ -0,0 +1,109 @@ +//! A pixmap as a PNG file, held to a limit where its file has one, such as a download. + +use base64::Engine; +use rustgis_data::capped::Limit; +use tiny_skia::Pixmap; + +/// `pixmap`'s PNG, held to `limit`. With a limit to pass, it is written a row at a time from the +/// pixels where they are, and stopped as it passes the limit, which then says so +/// ([`Limit::passed`]). Its pixels are those of [`Pixmap::encode_png`], which writes it when there +/// is no limit but memory. +pub fn within(pixmap: &Pixmap, limit: &Limit) -> Result, String> { + if !limit.bounded() { + return pixmap.encode_png().map_err(|e| e.to_string()); + } + let (width, height) = (pixmap.width(), pixmap.height()); + let across = usize::try_from(width).map_err(|e| e.to_string())?.max(1); + let mut rows = pixmap.pixels().chunks_exact(across); + limit + .file(|out| { + rustgis_data::png::write_rgba(out, width, height, |line| { + // The pixels are kept multiplied by their alpha; a PNG's colours aren't. + for (pixel, to) in rows.next().into_iter().flatten().zip(line.chunks_exact_mut(4)) { + let c = pixel.demultiply(); + to.copy_from_slice(&[c.red(), c.green(), c.blue(), c.alpha()]); + } + })?; + Ok(()) + }) + .map_err(|e| e.to_string()) +} + +/// `pixmap`'s PNG in base64, for a document held to `limit` of which `held` bytes are made: the +/// PNG is stopped once its base64 couldn't fit what is left, and the limit then says it passed. +pub fn base64_within(pixmap: &Pixmap, limit: &Limit, held: usize) -> Result { + // Base64 writes each three bytes as four characters. + let room = if limit.bounded() { Limit::new(limit.most().saturating_sub(held) / 4 * 3) } else { Limit::none() }; + let png = within(pixmap, &room); + if room.passed() { + limit.fits(usize::MAX).map_err(|e| e.to_string())?; + } + Ok(base64::engine::general_purpose::STANDARD.encode(png?)) +} + +#[cfg(test)] +mod tests { + use tiny_skia::PremultipliedColorU8; + + use super::*; + + /// A picture whose rows take turns at being noise and a smooth ramp (so that each row filter + /// is picked somewhere), its pixels opaque, seen through and wholly transparent. + fn picture(width: u32, height: u32) -> Pixmap { + let mut pixmap = Pixmap::new(width, height).unwrap(); + let mut state = 7u32; + for (i, pixel) in pixmap.pixels_mut().iter_mut().enumerate() { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let (x, y) = (i % width as usize, i / width as usize); + let [r, g, b, a] = match y % 4 { + 0 => state.to_le_bytes(), + 1 => [x as u8, (x / 3) as u8, y as u8, 255], + 2 => [(x + y) as u8, (2 * y) as u8, 9, 255], + _ => state.to_be_bytes(), + }; + let a = match (x + y / 4) % 3 { + 0 => 255, + 1 => a, + _ => 0, + }; + // Premultiplied: no channel above the alpha. + let under = |c: u8| (u16::from(c) * u16::from(a) / 255) as u8; + *pixel = PremultipliedColorU8::from_rgba(under(r), under(g), under(b), a).unwrap(); + } + pixmap + } + + fn decoded(png: &[u8]) -> (u32, u32, Vec) { + let image = image::load_from_memory_with_format(png, image::ImageFormat::Png).unwrap(); + assert_eq!(image.color(), image::ColorType::Rgba8); + (image.width(), image.height(), image.into_rgba8().into_raw()) + } + + /// A PNG held to a limit decodes to the pixels `encode_png`'s does, and fits a limit of its + /// own size but not a byte less. Without a limit it is `encode_png`'s. The widths are around + /// the 8 KiB pieces the file is written in, and one picture takes several data chunks. + #[test] + fn a_png_held_to_a_limit_decodes_as_encode_pngs() { + for (width, height) in [(1, 1), (1, 9), (7, 1), (3, 5), (2047, 6), (2048, 6), (2049, 6), (300, 301)] { + let pixmap = picture(width, height); + let whole = pixmap.encode_png().unwrap(); + assert_eq!(within(&pixmap, &Limit::none()).unwrap(), whole, "{width}x{height}"); + let held = within(&pixmap, &Limit::new(64 << 20)).unwrap(); + assert!(decoded(&held) == decoded(&whole), "{width}x{height}: other pixels"); + assert_eq!(within(&pixmap, &Limit::new(held.len())).unwrap(), held, "{width}x{height}"); + let limit = Limit::new(held.len() - 1); + assert!(within(&pixmap, &limit).is_err() && limit.passed(), "{width}x{height}"); + } + } + + /// A picture's base64 is held to what its document's limit leaves. + #[test] + fn a_base64_png_is_held_to_what_the_document_leaves() { + let pixmap = picture(40, 40); + let free = base64_within(&pixmap, &Limit::new(1 << 20), 0).unwrap(); + let limit = Limit::new(100 + free.len()); + assert_eq!(base64_within(&pixmap, &limit, 100).unwrap(), free); + assert!(!limit.passed()); + assert!(base64_within(&pixmap, &limit, 104).is_err() && limit.passed()); + } +} diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index ade177713b..6e87178061 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -10,7 +10,7 @@ mod vectors; use std::fmt::Write as _; -use base64::Engine; +use rustgis_data::capped::Limit; use rustgis_map::Map; use rustgis_map::layout::{ElementKind, FontFamily, Layout, LineHead, PT_PER_MM, TextAlign, frame_camera}; @@ -19,11 +19,28 @@ use crate::layout::{MAX_PIXELS, PageInfo, expand, page_geometry, record_element, /// Writes `layout` as an SVG document, pictures drawn at `dpi`, and the elements (id and name) /// drawn as pictures because their vectors would pass the budget. Refuses a source changed during drawing. pub fn layout_svg(layout: &Layout, maps: &mut [Map], dpi: f64, info: &PageInfo) -> Result<(String, Vec<(u32, String)>), String> { + layout_svg_within(layout, maps, dpi, info, &Limit::none()) +} + +/// [`layout_svg`] for a document held to `limit`, such as a download: what is made of it is held +/// to that as it is made, element by element, and it is stopped as it passes it, which the limit +/// then says ([`Limit::passed`]). +pub fn layout_svg_within( + layout: &Layout, + maps: &mut [Map], + dpi: f64, + info: &PageInfo, + limit: &Limit, +) -> Result<(String, Vec<(u32, String)>), String> { let _budget = crate::layout::legend_budget(); let revisions = crate::layout::archive_revisions(layout, maps); let mut source_error = None; - let result = layout_svg_inner(layout, maps, dpi, info, &mut source_error); + let result = layout_svg_inner(layout, maps, dpi, info, limit, &mut source_error); crate::layout::finish_legends()?; + // A document stopped by its limit fails for that, not for being a page that couldn't be drawn. + if limit.passed() { + return Err(format!("the file passes the {} bytes it may come to", limit.most())); + } revisions.finish_revision( crate::layout::archive_revisions(layout, maps), result, @@ -36,9 +53,11 @@ fn layout_svg_inner( maps: &mut [Map], dpi: f64, info: &PageInfo, + limit: &Limit, source_error: &mut Option, ) -> Option<(String, Vec<(u32, String)>)> { let mut defs = vectors::Defs::default(); + defs.limit = Some(limit); let mut pictured = Vec::new(); let mut body = elements(layout, maps, dpi, info, &mut defs, &mut pictured, source_error)?; let (pw, ph) = (layout.width, layout.height); @@ -64,8 +83,10 @@ fn layout_svg_inner( // The page's colour (#2855), white unless given; its channels alone, opaque as the PNG's. let paper = layout.paper.map_or_else(|| "#ffffff".to_string(), |c| format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())); let _ = writeln!(s, r##""##, num(pw), num(ph)); + let end = "\n"; + limit.fits(s.len().saturating_add(body.len()).saturating_add(end.len())).ok()?; body.insert_str(0, &s); - body.push_str("\n"); + body.push_str(end); Some((body, pictured)) } @@ -89,6 +110,8 @@ fn elements( // What the elements kept as vectors come to: held to one page's budget, as a PDF page is. let mut written = 0usize; for e in layout.elements.iter().filter(|e| e.visible) { + // Stopped here, before the next element is drawn, once the document has passed its limit. + defs.fits(s.len())?; let _ = writeln!(s, r#""#, e.id, esc(&e.name)); // Its background first, as a shape of its own (#2257): the content drawn as a picture // below leaves it out (`draw_page` draws backgrounds only on the whole page). @@ -233,12 +256,13 @@ fn elements( } s.push_str("\n"); } + defs.fits(s.len())?; // The pictures, at the resolution only they share (the elements kept as vectors take none). let picture_dpi = picture_dpi(layout, dpi, |e| as_pictures.contains(&e.id)); for id in as_pictures { let mut image_tag = String::new(); if let Some((image, [ix, iy, iw, ih])) = render_element(layout, id, maps, picture_dpi, (info, &env), source_error)? { - let png = image.encode_png().ok()?; + let png = defs.picture_base64(&image, s.len())?; let _ = writeln!( image_tag, r#""#, @@ -246,13 +270,14 @@ fn elements( num(iy), num(iw), num(ih), - base64::engine::general_purpose::STANDARD.encode(png) + png ); } let place = picture_place(id); if let Some(at) = s.find(&place) { s.replace_range(at..at + place.len(), &image_tag); } + defs.fits(s.len())?; } Some(s) } @@ -627,6 +652,59 @@ mod tests { assert!(layout_svg(&layout, &mut maps, 72.0, &PageInfo::default()).is_err()); } + /// A document held to a limit is stopped as it passes it, before what follows is drawn: here + /// a frame that can't be drawn, which an export that gets to it fails at. + #[test] + fn an_svg_past_its_limit_is_stopped_before_the_rest_is_drawn() { + use rustgis_data::{Dataset, GeometryType}; + let (mut layout, mut maps, frame) = page(); + let words = + serde_json::from_value(serde_json::json!({"Text": {"text": "word ".repeat(400), "size": 12.0, "color": [0, 0, 0, 255]}})) + .unwrap(); + layout.add("Words", (0.0, 0.0, 100.0, 20.0), words); + // The text goes first, then the frame. + let at = layout.elements.iter().position(|e| e.id == frame).unwrap(); + let moved = layout.elements.remove(at); + layout.elements.push(moved); + maps[0].add_dataset(Dataset::new("Missing", GeometryType::Point, vec![])); + let dir = tempfile::tempdir().unwrap(); + let mut source = rustgis_map::source::SourceLayer::default(); + source.path = Some(dir.path().join("missing.shp").display().to_string()); + maps[0].layers[0].source = Some(source); + let info = PageInfo::default(); + let limit = Limit::new(1000); + let refused = layout_svg_within(&layout, &mut maps, 72.0, &info, &limit); + assert!(refused.is_err() && limit.passed(), "{refused:?}"); + let limit = Limit::new(1 << 20); + assert!(layout_svg_within(&layout, &mut maps, 72.0, &info, &limit).is_err() && !limit.passed()); + } + + /// A document held to a limit fits one of its own size and no less: text, a recorded + /// element's vectors, and a frame drawn as a picture. + #[test] + fn an_svg_is_held_to_its_limit() { + use crate::vector::TEST_MAX_COST; + for cost in [None, Some(20_000)] { + let (mut layout, mut maps, frame) = page(); + let words = + serde_json::from_value(serde_json::json!({"Text": {"text": "Words", "size": 12.0, "color": [0, 0, 0, 255]}})).unwrap(); + layout.add("Words", (0.0, 0.0, 100.0, 20.0), words); + let bar = serde_json::from_value(serde_json::json!({"ScaleBar": {"frame": frame}})).unwrap(); + layout.add("Scale", (5.0, 60.0, 60.0, 10.0), bar); + let info = PageInfo::default(); + TEST_MAX_COST.with(|l| l.set(cost)); + let mut within = |limit: &Limit| layout_svg_within(&layout, &mut maps, 72.0, &info, limit); + let whole = within(&Limit::new(1 << 24)).unwrap(); + let fits = within(&Limit::new(whole.0.len())); + let limit = Limit::new(whole.0.len() - 1); + let over = within(&limit); + TEST_MAX_COST.with(|l| l.set(None)); + assert!(cost.is_none() || whole.0.contains("data:image/png;base64,"), "a frame as a picture"); + assert_eq!(fits.unwrap(), whole, "{cost:?}"); + assert!(over.is_err() && limit.passed(), "{cost:?}"); + } + } + #[test] fn line_heads_remain_vector_paths() { let mut layout = Layout::new("Arrows", 100.0, 80.0); diff --git a/crates/render/src/svg/vectors.rs b/crates/render/src/svg/vectors.rs index 65375febde..415242988b 100644 --- a/crates/render/src/svg/vectors.rs +++ b/crates/render/src/svg/vectors.rs @@ -8,15 +8,17 @@ use std::fmt::Write as _; use std::sync::Arc; use ab_glyph::{Font, OutlineCurve}; -use base64::Engine; +use rustgis_data::capped::Limit; use rustgis_map::effects::Blend; -use tiny_skia::{Color, FillRule, LineCap, LineJoin, Path, PathSegment, Transform}; +use tiny_skia::{Color, FillRule, LineCap, LineJoin, Path, PathSegment, Pixmap, Transform}; use crate::vector::{Brush, GlyphRun, Group, Image, Item, Pixels, Stroke}; /// What the items refer to, written once into the document's ``. #[derive(Default)] -pub(super) struct Defs { +pub(super) struct Defs<'a> { + /// What the document is held to, if anything: the body written so far and these together. + pub limit: Option<&'a Limit>, pub text: String, count: usize, /// Glyph outlines by face (its `FontRef`'s address) and glyph id: their ids. @@ -26,7 +28,22 @@ pub(super) struct Defs { images: HashMap<(usize, bool), (Arc, String)>, } -impl Defs { +impl Defs<'_> { + /// `None` once these and a body of `body` bytes pass the document's limit, which then says so. + pub(super) fn fits(&self, body: usize) -> Option<()> { + match self.limit { + Some(limit) => limit.fits(body.saturating_add(self.text.len())).ok(), + None => Some(()), + } + } + + /// `pixmap`'s PNG in base64, for a document whose body has `body` bytes so far: stopped as it + /// passes what the limit leaves. `None` then, and when it can't be encoded. + pub(super) fn picture_base64(&self, pixmap: &Pixmap, body: usize) -> Option { + let none = Limit::none(); + crate::png::base64_within(pixmap, self.limit.unwrap_or(&none), body.saturating_add(self.text.len())).ok() + } + /// A new id for a definition of `kind` (a gradient, a clip). fn id(&mut self, kind: &str) -> String { self.count += 1; @@ -39,6 +56,7 @@ impl Defs { pub(super) fn items(out: &mut String, defs: &mut Defs, items: &[Item]) -> Option<()> { let mut rest = items.iter().peekable(); while let Some(item) = rest.next() { + defs.fits(out.len())?; // An opaque fill then an opaque stroke of the same path: one element, filled and stroked. if let Item::Fill { path, brush: Brush::Solid(fill), rule, transform } = item && let Some(Item::Stroke { path: outline, color, stroke, transform: at }) = rest.peek() @@ -275,7 +293,7 @@ fn picture(out: &mut String, defs: &mut Defs, image: &Image) -> Option<()> { let opacity = if image.opacity < 1.0 { format!(r#" opacity="{}""#, num(image.opacity)) } else { String::new() }; let (px, rendering) = (&image.pixels, rendering_attr(image.smooth)); if !image.shared { - let png = png_base64(px)?; + let png = defs.picture_base64(&px.pixmap()?, out.len())?; let transform = transform_attr(image.transform); let _ = writeln!( out, @@ -290,7 +308,7 @@ fn picture(out: &mut String, defs: &mut Defs, image: &Image) -> Option<()> { let id = match defs.images.get(&key) { Some((_, id)) => id.clone(), None => { - let png = png_base64(px)?; + let png = defs.picture_base64(&px.pixmap()?, out.len())?; let id = defs.id("picture"); let _ = writeln!( defs.text, @@ -305,12 +323,6 @@ fn picture(out: &mut String, defs: &mut Defs, image: &Image) -> Option<()> { Some(()) } -/// `px` as a PNG, in base64; `None` if it can't be read back. -fn png_base64(px: &Pixels) -> Option { - let png = px.pixmap()?.encode_png().ok()?; - Some(base64::engine::general_purpose::STANDARD.encode(png)) -} - /// ` image-rendering="optimizeSpeed"` for a picture drawn blocky; nothing for a smooth one. fn rendering_attr(smooth: bool) -> &'static str { if smooth { "" } else { r#" image-rendering="optimizeSpeed""# } diff --git a/crates/render/tests/download_memory.rs b/crates/render/tests/download_memory.rs new file mode 100644 index 0000000000..b935a59eb3 --- /dev/null +++ b/crates/render/tests/download_memory.rs @@ -0,0 +1,63 @@ +//! The memory a downloaded picture or document takes: neither a second copy of the picture's +//! pixels nor a file past its room is built before the limit refuses it. A test binary of its +//! own, as the peak it reads is the whole process's. +#![cfg(target_os = "linux")] + +use rustgis_data::capped::Limit; +use rustgis_render::{Pixmap, pdf, png}; + +/// The pixels along a side of the picture: 16 MiB of them. +const SIDE: u32 = 2048; +/// The pages of the document, each the picture. +const PAGES: usize = 4; +/// The room each file is held to. +const ROOM: usize = 1 << 20; +/// The most the peak may grow while a file is refused: half the picture's pixels. +const MOST: u64 = 8 << 20; + +/// The most memory this process has held since the peak was last reset, in bytes. +fn peak_bytes() -> u64 { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + let line = status.lines().find_map(|l| l.strip_prefix("VmHWM:")).unwrap(); + line.trim().trim_end_matches("kB").trim().parse::().unwrap() * 1024 +} + +/// How far `run` takes the peak past what is held as it starts. +fn growth(run: impl FnOnce()) -> u64 { + // Linux sets the peak back to what is held now. + std::fs::write("/proc/self/clear_refs", "5").unwrap(); + let before = peak_bytes(); + run(); + peak_bytes().saturating_sub(before) +} + +#[test] +fn a_picture_or_document_past_its_room_is_not_built_for_it() { + // Opaque noise, which hardly compresses. + let mut picture = Pixmap::new(SIDE, SIDE).unwrap(); + let mut state = 7u32; + for (i, byte) in picture.data_mut().iter_mut().enumerate() { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + *byte = if i % 4 == 3 { 255 } else { (state >> 24) as u8 }; + } + let mut over = Vec::new(); + let grew = growth(|| { + let limit = Limit::new(ROOM); + assert!(png::within(&picture, &limit).is_err() && limit.passed()); + }); + if grew >= MOST { + over.push(format!("a PNG: the peak grew {} MiB", grew >> 20)); + } + + let pages: Vec = (0..PAGES).map(|_| pdf::Page::new(&picture, 210.0, 297.0)).collect(); + drop(picture); + assert!(pages.iter().map(pdf::Page::len).sum::() > 4 * MOST as usize); + let grew = growth(|| { + let limit = Limit::new(ROOM); + assert!(pdf::write_within(&pages, "Large", &limit).is_err() && limit.passed()); + }); + if grew >= MOST { + over.push(format!("a PDF: the peak grew {} MiB", grew >> 20)); + } + assert!(over.is_empty(), "{over:#?}"); +} From a91af9247281f7c9f89a2e57d5f442d42fac135c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 01:53:47 -0600 Subject: [PATCH 05/10] 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] From 968e552a0f45b19bda5c1844f50bdfe9fc71c55c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 01:27:35 -0600 Subject: [PATCH 06/10] fix(tiles): hold an archive's directories to its limit as tiles are added --- .../data/tests/projected_download_memory.rs | 4 +- crates/tiles/src/pmtiles.rs | 48 +++++++++++++++++-- 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/crates/data/tests/projected_download_memory.rs b/crates/data/tests/projected_download_memory.rs index f5013c69df..5c7eb00898 100644 --- a/crates/data/tests/projected_download_memory.rs +++ b/crates/data/tests/projected_download_memory.rs @@ -30,8 +30,8 @@ fn growth(run: impl FnOnce()) -> usize { } /// The CSV notices, counted before a file is written, then each format, of which `shp`, `parquet` -/// and `fgb` need the layer whole in the other system. The last write a layer of one feature, whose text alone is -/// as large, and count what KML loses of it. +/// and `fgb` need the layer whole in the other system. The `value` cases use a layer of one feature +/// whose text is as large as that whole layer: three formats, then what KML loses of it. const CASES: [&str; 13] = ["notices", "geojson", "csv", "kml", "kmz", "gpx", "shp", "parquet", "fgb", "value geojson", "value csv", "value kml", "value notices"]; diff --git a/crates/tiles/src/pmtiles.rs b/crates/tiles/src/pmtiles.rs index 79e6f6bef3..f03f9010fa 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -332,6 +332,14 @@ fn not_a_tile(z: u8, x: u32, y: u32) -> String { format!("{z}/{x}/{y} isn't a tile (zoom 0–30, x and y below 2^zoom)") } +/// The bytes of an archive's header. +const HEADER: usize = 127; + +/// The bytes `v` takes as a varint, seven bits to each. +fn varint_length(v: u64) -> usize { + ((v | 1).ilog2() / 7 + 1) as usize +} + /// How many bytes were written to it. struct Length(usize); @@ -369,6 +377,8 @@ pub struct Builder<'a> { data: Buffer<'a>, limit: &'a Limit, entries: Vec, + /// The least the directories come to, for the entries so far. + directory: usize, /// Where each tile stored lies in the data (offset, length), by the hash of its bytes. stored: HashMap>, hasher: RandomState, @@ -385,6 +395,7 @@ impl<'a> Builder<'a> { data: limit.buffer(), limit, entries: Vec::new(), + directory: 0, stored: HashMap::new(), hasher: RandomState::new(), contents: 0, @@ -434,9 +445,13 @@ impl<'a> Builder<'a> { e.run_length += 1; return Ok(()); } - // Each entry takes four bytes of a directory at least, so many of one tile's bytes can't pass - // the limit in what is held before the directories are made. - let least = (self.entries.len() + 1).saturating_mul(4).saturating_add(127); + // What it takes of the directories, as [`write_dir`] writes it: leaves take no less, so many + // of one tile's bytes are refused here, before the directories are made. + let after = self.entries.last(); + let next = after.is_some_and(|e| e.offset + e.length == offset); + let parts = [id - after.map_or(0, |e| e.tile_id), 1, length, if next { 0 } else { offset + 1 }]; + self.directory = parts.into_iter().map(varint_length).fold(self.directory, usize::saturating_add); + let least = self.directory.saturating_add(HEADER); self.limit.fits(self.data.written().len().saturating_add(least)).map_err(|e| e.to_string())?; self.entries.push(Entry { tile_id: id, offset, length, run_length: 1 }); Ok(()) @@ -1299,6 +1314,33 @@ fn gunzip(b: &[u8]) -> Result, String> { pub(crate) mod tests { use super::*; + /// Many tiles of two payloads take two bytes of data and a large directory: refused as the + /// tiles are added, before the directories are made, and the same archive fits its own size. + #[test] + fn an_archives_directories_are_held_to_its_limit_as_tiles_are_added() { + let about = NewArchive { + tile_type: TileType::Png, + gzipped_tiles: false, + bounds: [-180.0, -85.0, 180.0, 85.0], + metadata: serde_json::json!({}), + }; + let build = |limit: &Limit| { + let mut archive = Builder::new(limit); + let mut ids: Vec<(u64, u32, u32)> = (0..64).flat_map(|y| (0..64).map(move |x| (tile_id(12, x, y), x, y))).collect(); + ids.sort_unstable(); + for (n, (_, x, y)) in ids.into_iter().enumerate() { + archive.push(12, x, y, &[(n % 2) as u8]).map_err(|_| n)?; + } + archive.finish(&about).map_err(|_| usize::MAX) + }; + let whole = build(&Limit::none()).unwrap(); + assert_eq!(build(&Limit::new(whole.len())).unwrap(), whole); + assert_eq!(build(&Limit::new(whole.len() - 1)), Err(usize::MAX)); + // Half the room: stopped at about half the tiles. + let half = build(&Limit::new(whole.len() / 2)).unwrap_err(); + assert!((1500..2500).contains(&half), "{half}"); + } + #[test] fn retired_context_cannot_start_or_join_archive_reads() { let _turn = crate::cache::turn(); From 16e68e355d31ca525fcc97baf6e8f642ce16b3e1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 03:17:03 -0600 Subject: [PATCH 07/10] fix(engine): hold the web app's printed map to the download limit --- crates/engine/src/cmd/exports.rs | 5 +++ crates/engine/src/cmd/gp.rs | 4 +-- crates/engine/src/cmd/share.rs | 9 ++++-- crates/engine/src/cmd/sharing.rs | 4 +-- crates/engine/src/tests/browser_exports.rs | 36 ++++++++++++++++++++++ crates/render/src/png.rs | 4 +-- docs/user-guide/sharing.md | 4 +-- 7 files changed, 55 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 24b0906238..bc5dbd2967 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -179,6 +179,11 @@ impl<'a> Output<'a> { Ok(Output { path, room: s.download_room()? }) } + /// Whether it is held to a limit: downloaded, to a front end that has one. + pub(crate) fn limited(self) -> bool { + self.most() != NO_DOWNLOAD_LIMIT + } + /// Whether it is made to be downloaded. pub(crate) fn downloads(self) -> bool { self.room.is_some() diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 727c5fd4d7..474c845b60 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -3921,8 +3921,8 @@ fn queue(s: &mut Session, file_name: String, bytes: Arc>, from: Delivery }; let cap = s.download_cap(); 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. + // An export whose writer takes a limit was stopped at it; this is what holds the others, such as + // the file a raster layer holds, to it. // Measured as the queue counts what waits: by what the file holds, its spare room included. let size = bytes.capacity(); if matches!(from, Delivery::Export(_)) && size > cap { diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index e4ae5327c7..4d2fc96ec0 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -358,11 +358,13 @@ fn export_view( /// inch of screen, kept as vectors with what is pixels by nature drawn at `dpi`. pub fn map_pdf(s: &mut Session, dpi: f64) -> Result, String> { let revisions = rustgis_render::archive_revisions([s.map()]); - let result = saying_shadows(s, "The map PDF", |s| map_pdf_inner(s, dpi)); + let name = format!("{}.pdf", s.map().name); + let out = super::exports::Output::here(s, &name)?; + let result = saying_shadows(s, "The map PDF", |s| map_pdf_inner(s, dpi, out)); revisions.finish_revision(rustgis_render::archive_revisions([s.map()]), Some(result), "could not draw the map")? } -fn map_pdf_inner(s: &mut Session, dpi: f64) -> Result, String> { +fn map_pdf_inner(s: &mut Session, dpi: f64, out: super::exports::Output<'_>) -> Result, String> { let (vw, vh) = s.view_size; let ppp = (dpi / 96.0).clamp(0.5, 6.0); let view = @@ -384,7 +386,8 @@ fn map_pdf_inner(s: &mut Session, dpi: f64) -> Result, String> { } else { rustgis_render::pdf::Page::drawing(drawing, w, h) }; - Ok(rustgis_render::pdf::write(&[page], &s.map().name)) + out.check(page.len())?; + out.held_to(|limit| rustgis_render::pdf::write_within(&[page], &s.map().name, limit)) } /// `share.exportMap`: draws the active map as it is now to a PNG, or a GeoTIFF for a `.tif` or diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 7629a3f0d0..9550412fd7 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -376,11 +376,11 @@ fn map_of(s: &Session, p: &Value) -> Result { /// A streamed layer shares its whole source, not the features read for the current view; what /// that read couldn't read as it is (rows left out, dates read as null or rounded) is said. -/// For a download, the layers read are held together to what the web app reads for one +/// For a download with a limit, the layers read are held together to what the web app reads for one /// ([`super::exports::read_for_download_after`]), `held` counting their bytes. fn load_whole(s: &mut Session, l: &mut Layer, out: Output<'_>, held: &mut usize) -> Result<(), String> { if l.is_streamed() { - let (ds, unread) = if out.downloads() { super::exports::read_for_download_after(l, *held)? } else { l.load_all_counted()? }; + let (ds, unread) = if out.limited() { super::exports::read_for_download_after(l, *held)? } else { l.load_all_counted()? }; *held = held.saturating_add(ds.features.held_bytes()); l.dataset = ds; super::whole::Unread::of(l.name.clone(), unread).say(s); diff --git a/crates/engine/src/tests/browser_exports.rs b/crates/engine/src/tests/browser_exports.rs index 81d36b2b46..ae99b90719 100644 --- a/crates/engine/src/tests/browser_exports.rs +++ b/crates/engine/src/tests/browser_exports.rs @@ -885,6 +885,42 @@ fn a_browser_item_over_the_limit_is_stopped_as_it_is_made() { } } +/// Where the file has no limit, neither has the read of a layer read in place, for an export or a +/// share. +#[test] +fn a_read_for_a_download_without_a_limit_has_none() { + let files = Files::new(); + let mut s = session(&files, false); + streamed(&mut s, "Many", Some(10_000_000), 0, true); + for (command, file) in [("share.exportLayer", "z.geojson"), ("share.webLayer", "z.zip")] { + let params = json!({"layer": "Many", "path": file}); + s.offer_files(Some(crate::cmd::exports::MAX_DOWNLOAD_BYTES)); + let e = s.run(command, ¶ms).unwrap_err(); + assert!(e.contains("more than the 256 MiB"), "{command}: {e}"); + s.offer_files(Some(crate::cmd::exports::NO_DOWNLOAD_LIMIT)); + let pending = s.run(command, ¶ms).unwrap_or_else(|e| panic!("{command}: {e}")); + let (name, bytes, _) = deliver(&mut s, &pending, None); + assert!(name == file && !bytes.is_empty(), "{command}: {name}"); + } +} + +/// Print Map's PDF, which the interface downloads itself, is held to the room a download has. +#[test] +fn a_browsers_printed_map_is_held_to_its_room() { + let files = Files::new(); + let mut s = session(&files, true); + s.download_cap = Some(100); + let e = crate::cmd::share::map_pdf(&mut s, 96.0).unwrap_err(); + assert!(e.contains(".pdf: stopped once the file passed"), "{e}"); + s.download_cap = None; + let whole = crate::cmd::share::map_pdf(&mut s, 96.0).unwrap(); + s.download_cap = Some(whole.len() - 1); + assert!(crate::cmd::share::map_pdf(&mut s, 96.0).is_err()); + // Written, nothing holds it, and it is the same file. + s.queue_gp_files = false; + assert_eq!(crate::cmd::share::map_pdf(&mut s, 96.0).unwrap(), whole); +} + /// 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/render/src/png.rs b/crates/render/src/png.rs index 0e92ee5885..8d12b67834 100644 --- a/crates/render/src/png.rs +++ b/crates/render/src/png.rs @@ -19,9 +19,9 @@ pub fn within(pixmap: &Pixmap, limit: &Limit) -> Result, String> { .file(|out| { rustgis_data::png::write_rgba(out, width, height, |line| { // The pixels are kept multiplied by their alpha; a PNG's colours aren't. - for (pixel, to) in rows.next().into_iter().flatten().zip(line.chunks_exact_mut(4)) { + for (pixel, to) in rows.next().into_iter().flatten().zip(line.as_chunks_mut::<4>().0) { let c = pixel.demultiply(); - to.copy_from_slice(&[c.red(), c.green(), c.blue(), c.alpha()]); + *to = [c.red(), c.green(), c.blue(), c.alpha()]; } })?; Ok(()) diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index 09e70cfcca..a5575e0a86 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -114,8 +114,8 @@ the geoprocessing history. A command is refused once its file passes what is lef 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 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. +what they download to the same 256 MiB, except 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 9a6959555914034efde8785f39a6f98a9e67f647 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 04:33:27 -0600 Subject: [PATCH 08/10] fix(render): don't count an SVG's places for pictures, and print a map's pixels without a PNG between --- crates/engine/src/cmd/share.rs | 3 +-- crates/render/src/lib.rs | 17 +++++++++++++++-- crates/render/src/pdf.rs | 9 +++++++-- crates/render/src/pdf/content.rs | 4 ++++ crates/render/src/svg.rs | 29 ++++++++++++++++++++++++----- crates/tiles/src/pmtiles.rs | 4 ++-- 6 files changed, 53 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 4d2fc96ec0..485ad93a70 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -374,8 +374,7 @@ fn map_pdf_inner(s: &mut Session, dpi: f64, out: super::exports::Output<'_>) -> let (w, h) = (mm(view.width), mm(view.height)); let page = if drawing.overflowed() { // Too large for vectors: the map as one picture, as it is drawn on screen. - let png = rustgis_render::render_png(s.map_mut(), &view)?; - let pm = rustgis_render::decode_png(&png).ok_or("could not draw the map")?; + let pm = rustgis_render::render_pixmap(s.map_mut(), &view)?; // Said once the picture is drawn. The budget counts the drawing's pictures (rasters, // tiles) as well as its shapes. let (mb, items) = (rustgis_render::vector::MAX_COST >> 20, rustgis_render::vector::MAX_ITEMS / 1_000_000); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 2eeefd0828..8097f13100 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -9236,6 +9236,20 @@ pub fn render_png(map: &mut Map, view: &View) -> Result, String> { /// that, which the limit then says ([`Limit::passed`]). pub fn render_png_within(map: &mut Map, view: &View, limit: &Limit) -> Result, String> { let revisions = archive_revisions([&*map]); + let png = png::within(&exported_pixmap(map, view)?, limit)?; + revisions.finish(map, None, Some(png), "could not encode the image") +} + +/// The picture [`render_png`] encodes, for a caller that puts its pixels elsewhere. Refuses an +/// archive changed during rendering. +pub fn render_pixmap(map: &mut Map, view: &View) -> Result { + let revisions = archive_revisions([&*map]); + let pixmap = exported_pixmap(map, view)?; + revisions.finish(map, None, Some(pixmap), "could not draw the image") +} + +/// The map drawn for an export, with its labels, a scale bar, a north arrow and its credits. +fn exported_pixmap(map: &mut Map, view: &View) -> Result { let r = render_exported(map, view)?; let mut pm = Canvas::from_pixmap(r.pixmap); for l in r.unplaced.iter().chain(&r.labels) { @@ -9243,8 +9257,7 @@ pub fn render_png_within(map: &mut Map, view: &View, limit: &Limit) -> Result Doc<'a> { } } + /// Whether a write was refused, so that nothing more is written. + pub(crate) fn refused(&self) -> bool { + self.failed.is_some() + } + /// A new object's number. pub(crate) fn reserve(&mut self) -> usize { self.offsets.push(None); @@ -224,7 +229,7 @@ impl<'a> Doc<'a> { /// compressed unless it already is (`deflated`). pub(crate) fn stream(&mut self, id: usize, dict: &str, data: &[u8], deflated: bool) { // Nothing more is written, so nothing is compressed for it. - if self.failed.is_some() { + if self.refused() { return; } let z; @@ -440,7 +445,7 @@ fn write_to(out: &mut dyn Write, pages: &[Page], title: &str, options: Options) let mut fonts = fonts::Fonts::with_real(&mut doc, real); let mut layers = Layers { on: layered, ..Layers::default() }; for (p, &page) in pages.iter().zip(&ids) { - if doc.failed.is_some() { + if doc.refused() { break; } let (pw, ph) = (p.width_mm * 72.0 / 25.4, p.height_mm * 72.0 / 25.4); diff --git a/crates/render/src/pdf/content.rs b/crates/render/src/pdf/content.rs index 27e4626d49..c446561817 100644 --- a/crates/render/src/pdf/content.rs +++ b/crates/render/src/pdf/content.rs @@ -137,6 +137,10 @@ impl Writer<'_, '_> { fn items(&mut self, out: &mut Vec, st: &mut State, items: &[Item]) { let mut rest = items.iter().peekable(); while let Some(item) = rest.next() { + // Nothing more is written once a write was refused (a picture that passed the limit). + if self.doc.refused() { + return; + } // An opaque fill then an opaque stroke of the same path (a polygon and its outline): the // path written once, filled and stroked together. (A see-through pair stays apart: a // shape filled and stroked together composites as one, unlike two drawn in turn.) diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 6e87178061..f678216a28 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -107,11 +107,13 @@ fn elements( // The elements drawn as pictures (past the budget): their places, filled in at the end at // the resolution they share. let mut as_pictures: Vec = Vec::new(); + // What those places take of `s` until they are filled, which isn't the document's. + let mut places = 0usize; // What the elements kept as vectors come to: held to one page's budget, as a PDF page is. let mut written = 0usize; for e in layout.elements.iter().filter(|e| e.visible) { // Stopped here, before the next element is drawn, once the document has passed its limit. - defs.fits(s.len())?; + defs.fits(s.len().saturating_sub(places))?; let _ = writeln!(s, r#""#, e.id, esc(&e.name)); // Its background first, as a shape of its own (#2257): the content drawn as a picture // below leaves it out (`draw_page` draws backgrounds only on the whole page). @@ -250,19 +252,21 @@ fn elements( } pictured.push((e.id, e.name.clone())); } - s.push_str(&picture_place(e.id)); + let place = picture_place(e.id); + places += place.len(); + s.push_str(&place); as_pictures.push(e.id); } } s.push_str("\n"); } - defs.fits(s.len())?; + defs.fits(s.len().saturating_sub(places))?; // The pictures, at the resolution only they share (the elements kept as vectors take none). let picture_dpi = picture_dpi(layout, dpi, |e| as_pictures.contains(&e.id)); for id in as_pictures { let mut image_tag = String::new(); if let Some((image, [ix, iy, iw, ih])) = render_element(layout, id, maps, picture_dpi, (info, &env), source_error)? { - let png = defs.picture_base64(&image, s.len())?; + let png = defs.picture_base64(&image, s.len().saturating_sub(places))?; let _ = writeln!( image_tag, r#""#, @@ -276,8 +280,9 @@ fn elements( let place = picture_place(id); if let Some(at) = s.find(&place) { s.replace_range(at..at + place.len(), &image_tag); + places = places.saturating_sub(place.len()); } - defs.fits(s.len())?; + defs.fits(s.len().saturating_sub(places))?; } Some(s) } @@ -679,6 +684,20 @@ mod tests { assert!(layout_svg_within(&layout, &mut maps, 72.0, &info, &limit).is_err() && !limit.passed()); } + /// The places kept for pictures until they are drawn aren't the document's: elements off the + /// page, which leave nothing there, don't count against its limit. + #[test] + fn an_svgs_places_for_pictures_dont_count_against_its_limit() { + let (mut layout, mut maps, frame) = page(); + for _ in 0..100 { + let bar = serde_json::from_value(serde_json::json!({"ScaleBar": {"frame": frame}})).unwrap(); + layout.add("Off", (-500.0, -500.0, 60.0, 10.0), bar); + } + let info = PageInfo::default(); + let whole = layout_svg(&layout, &mut maps, 72.0, &info).unwrap(); + assert_eq!(layout_svg_within(&layout, &mut maps, 72.0, &info, &Limit::new(whole.0.len())).unwrap(), whole); + } + /// A document held to a limit fits one of its own size and no less: text, a recorded /// element's vectors, and a frame drawn as a picture. #[test] diff --git a/crates/tiles/src/pmtiles.rs b/crates/tiles/src/pmtiles.rs index f03f9010fa..ce0e2b0b09 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -473,7 +473,7 @@ impl<'a> Builder<'a> { let mut root = write_dir(&entries); let mut leaves = Vec::new(); let mut per_leaf = 4096usize; - while 127 + root.len() > HEAD as usize { + while HEADER + root.len() > HEAD as usize { leaves.clear(); let mut index = Vec::new(); for chunk in entries.chunks(per_leaf) { @@ -485,7 +485,7 @@ impl<'a> Builder<'a> { root = write_dir(&index); per_leaf = per_leaf.checked_mul(2).ok_or("too many tiles")?; } - let root_at = 127u64; + let root_at = HEADER as u64; let meta_at = root_at + root.len() as u64; let leaf_at = meta_at + meta.len() as u64; let data_at = leaf_at + leaves.len() as u64; From 2167d4c1c93f86343130d1696bd5c9e93a666eaf Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 05:19:04 -0600 Subject: [PATCH 09/10] fix(render): hold Print Map to its file's size, and stop a PDF page and a PNG where they should --- crates/data/src/png.rs | 4 +++- crates/engine/src/cmd/share.rs | 1 - crates/engine/src/tests/browser_exports.rs | 3 +++ crates/render/src/pdf/content.rs | 4 ++++ 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/data/src/png.rs b/crates/data/src/png.rs index 017fa68e0c..7b66044777 100644 --- a/crates/data/src/png.rs +++ b/crates/data/src/png.rs @@ -14,7 +14,8 @@ const PIXEL: usize = 4; /// Writes an 8-bit RGBA picture of `width` × `height` pixels to `out` as a PNG. `row` is asked /// for each row in turn from the top, and fills it with its pixels' red, green, blue and alpha, -/// the colours not multiplied by the alpha. It stops at the first write `out` refuses. +/// the colours not multiplied by the alpha. It stops at the first write `out` refuses, and +/// between rows on Cancel. pub fn write_rgba(out: &mut W, width: u32, height: u32, mut row: impl FnMut(&mut [u8])) -> std::io::Result<()> { let bytes = usize::try_from(width) .ok() @@ -35,6 +36,7 @@ pub fn write_rgba(out: &mut W, width: u32, height: u32, mut r let (mut line, mut above) = (vec![0; bytes], vec![0; bytes]); let (mut best, mut tried) = (vec![0; bytes + 1], vec![0; bytes + 1]); for _ in 0..height { + crate::progress::check().map_err(|e| Error::other(e.to_string()))?; row(&mut line); filter(&line, &above, &mut best, &mut tried); data.write_all(&best)?; diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 485ad93a70..37dc11e68a 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -385,7 +385,6 @@ fn map_pdf_inner(s: &mut Session, dpi: f64, out: super::exports::Output<'_>) -> } else { rustgis_render::pdf::Page::drawing(drawing, w, h) }; - out.check(page.len())?; out.held_to(|limit| rustgis_render::pdf::write_within(&[page], &s.map().name, limit)) } diff --git a/crates/engine/src/tests/browser_exports.rs b/crates/engine/src/tests/browser_exports.rs index ae99b90719..781e689a29 100644 --- a/crates/engine/src/tests/browser_exports.rs +++ b/crates/engine/src/tests/browser_exports.rs @@ -916,6 +916,9 @@ fn a_browsers_printed_map_is_held_to_its_room() { let whole = crate::cmd::share::map_pdf(&mut s, 96.0).unwrap(); s.download_cap = Some(whole.len() - 1); assert!(crate::cmd::share::map_pdf(&mut s, 96.0).is_err()); + // By the file's own size, not the drawing's, which is compressed as it is written. + s.download_cap = Some(whole.len()); + assert_eq!(crate::cmd::share::map_pdf(&mut s, 96.0).unwrap(), whole); // Written, nothing holds it, and it is the same file. s.queue_gp_files = false; assert_eq!(crate::cmd::share::map_pdf(&mut s, 96.0).unwrap(), whole); diff --git a/crates/render/src/pdf/content.rs b/crates/render/src/pdf/content.rs index c446561817..3b5514c013 100644 --- a/crates/render/src/pdf/content.rs +++ b/crates/render/src/pdf/content.rs @@ -435,6 +435,10 @@ impl Writer<'_, '_> { /// Writes what `f` writes inside `g`'s clip, moved by its transform; nothing when the /// transform folds it flat. fn clipped(&mut self, out: &mut Vec, st: &mut State, g: &Group, f: impl FnOnce(&mut Self, &mut Vec, &mut State)) { + // Nothing more is written once a write was refused, the clip (one for each layer) included. + if self.doc.refused() { + return; + } let saved = st.clone(); out.extend_from_slice(b"q\n"); if let Some(clip) = &g.clip { From 59e381cada0225d896871da2e6a239525d2cceb4 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 05:58:41 -0600 Subject: [PATCH 10/10] fix(render): leave the places kept for pictures out of every check of an SVG's limit --- crates/render/src/svg.rs | 19 ++++++++++--------- crates/render/src/svg/vectors.rs | 12 ++++++++++-- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index f678216a28..e03294df99 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -107,13 +107,11 @@ fn elements( // The elements drawn as pictures (past the budget): their places, filled in at the end at // the resolution they share. let mut as_pictures: Vec = Vec::new(); - // What those places take of `s` until they are filled, which isn't the document's. - let mut places = 0usize; // What the elements kept as vectors come to: held to one page's budget, as a PDF page is. let mut written = 0usize; for e in layout.elements.iter().filter(|e| e.visible) { // Stopped here, before the next element is drawn, once the document has passed its limit. - defs.fits(s.len().saturating_sub(places))?; + defs.fits(s.len())?; let _ = writeln!(s, r#""#, e.id, esc(&e.name)); // Its background first, as a shape of its own (#2257): the content drawn as a picture // below leaves it out (`draw_page` draws backgrounds only on the whole page). @@ -253,20 +251,20 @@ fn elements( pictured.push((e.id, e.name.clone())); } let place = picture_place(e.id); - places += place.len(); + defs.places += place.len(); s.push_str(&place); as_pictures.push(e.id); } } s.push_str("\n"); } - defs.fits(s.len().saturating_sub(places))?; + defs.fits(s.len())?; // The pictures, at the resolution only they share (the elements kept as vectors take none). let picture_dpi = picture_dpi(layout, dpi, |e| as_pictures.contains(&e.id)); for id in as_pictures { let mut image_tag = String::new(); if let Some((image, [ix, iy, iw, ih])) = render_element(layout, id, maps, picture_dpi, (info, &env), source_error)? { - let png = defs.picture_base64(&image, s.len().saturating_sub(places))?; + let png = defs.picture_base64(&image, s.len())?; let _ = writeln!( image_tag, r#""#, @@ -280,9 +278,9 @@ fn elements( let place = picture_place(id); if let Some(at) = s.find(&place) { s.replace_range(at..at + place.len(), &image_tag); - places = places.saturating_sub(place.len()); + defs.places = defs.places.saturating_sub(place.len()); } - defs.fits(s.len().saturating_sub(places))?; + defs.fits(s.len())?; } Some(s) } @@ -689,10 +687,13 @@ mod tests { #[test] fn an_svgs_places_for_pictures_dont_count_against_its_limit() { let (mut layout, mut maps, frame) = page(); - for _ in 0..100 { + for _ in 0..1000 { let bar = serde_json::from_value(serde_json::json!({"ScaleBar": {"frame": frame}})).unwrap(); layout.add("Off", (-500.0, -500.0, 60.0, 10.0), bar); } + // After them, vectors on the page, checked against the limit item by item. + let bar = serde_json::from_value(serde_json::json!({"ScaleBar": {"frame": frame}})).unwrap(); + layout.add("On", (5.0, 60.0, 60.0, 10.0), bar); let info = PageInfo::default(); let whole = layout_svg(&layout, &mut maps, 72.0, &info).unwrap(); assert_eq!(layout_svg_within(&layout, &mut maps, 72.0, &info, &Limit::new(whole.0.len())).unwrap(), whole); diff --git a/crates/render/src/svg/vectors.rs b/crates/render/src/svg/vectors.rs index 415242988b..85268eac98 100644 --- a/crates/render/src/svg/vectors.rs +++ b/crates/render/src/svg/vectors.rs @@ -19,6 +19,9 @@ use crate::vector::{Brush, GlyphRun, Group, Image, Item, Pixels, Stroke}; pub(super) struct Defs<'a> { /// What the document is held to, if anything: the body written so far and these together. pub limit: Option<&'a Limit>, + /// What the places kept for pictures take of that body until they are filled, which isn't the + /// document's. + pub places: usize, pub text: String, count: usize, /// Glyph outlines by face (its `FontRef`'s address) and glyph id: their ids. @@ -29,10 +32,15 @@ pub(super) struct Defs<'a> { } impl Defs<'_> { + /// What is made of the document, its body `body` bytes so far. + fn made(&self, body: usize) -> usize { + body.saturating_sub(self.places).saturating_add(self.text.len()) + } + /// `None` once these and a body of `body` bytes pass the document's limit, which then says so. pub(super) fn fits(&self, body: usize) -> Option<()> { match self.limit { - Some(limit) => limit.fits(body.saturating_add(self.text.len())).ok(), + Some(limit) => limit.fits(self.made(body)).ok(), None => Some(()), } } @@ -41,7 +49,7 @@ impl Defs<'_> { /// passes what the limit leaves. `None` then, and when it can't be encoded. pub(super) fn picture_base64(&self, pixmap: &Pixmap, body: usize) -> Option { let none = Limit::none(); - crate::png::base64_within(pixmap, self.limit.unwrap_or(&none), body.saturating_add(self.text.len())).ok() + crate::png::base64_within(pixmap, self.limit.unwrap_or(&none), self.made(body)).ok() } /// A new id for a definition of `kind` (a gradient, a clip).