diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs index 5186de460a..2bb3dd920e 100644 --- a/crates/data/src/capped.rs +++ b/crates/data/src/capped.rs @@ -39,6 +39,14 @@ impl Limit { self.passed.load(Ordering::Relaxed) } + /// The file `write` makes in a buffer held to this limit: refused as soon as it would pass + /// it, whatever `write` makes of the refused write. + pub fn file(&self, write: impl FnOnce(&mut dyn Write) -> Result<()>) -> Result> { + let mut out = self.buffer(); + let made = write(&mut out); + self.whole(made.map(|()| out.into_inner())) + } + /// Whether there is a limit to pass: false for [`Limit::none`]. pub(crate) fn bounded(&self) -> bool { self.max != usize::MAX diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index ac7d972048..c37e234dcd 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1116,7 +1116,7 @@ fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> R "kmz" => { crate::interop::write_kml(ds, name_field(ds), &mut out)?; let kml = out.into_inner(); - (zipped(&[("doc.kml".to_string(), kml)], limit)?, without_geometry(ds)) + (crate::zip::write_within(&[("doc.kml".to_string(), kml)], limit)?, without_geometry(ds)) } "gpx" => { crate::interop::write_gpx(ds, name_field(ds), &mut out)?; @@ -1128,7 +1128,7 @@ fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> R ds.name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ') { c } else { '_' }).collect(); let base = if base.trim().is_empty() { "layer".to_string() } else { base }; let entries: Vec<(String, Vec)> = parts.into_iter().map(|(e, b)| (format!("{base}.{e}"), b)).collect(); - (zipped(&entries, limit)?, left_out) + (crate::zip::write_within(&entries, limit)?, left_out) } other => return Err(DataError::Unsupported(other.to_string())), }) @@ -1136,17 +1136,6 @@ fn projected_bytes_within(ds: &Dataset, ext: &str, crs: Crs, limit: &Limit) -> R limit.whole(made) } -/// A zip of `entries`, which were held to `limit` as they were made: they stay counted against it -/// while the archive is made, and the archive is written within what they leave, so the two -/// together never pass it. -fn zipped(entries: &[(String, Vec)], limit: &Limit) -> Result> { - let parts: usize = entries.iter().map(|(_, bytes)| bytes.capacity()).sum(); - let _parts = limit.hold(parts)?; - let mut out = limit.buffer(); - let made = crate::zip::write_to(entries, &mut out).map_err(DataError::Format); - limit.whole(made.map(|()| out.into_inner())) -} - /// The text `data.convert` makes of a dataset in longitude/latitude, in `format` (`geojson`, /// `csv`, `kml`, `gpx`, else WKT in a CSV), within `limit`. KML and GPX name placemarks by the /// field `name_field`. @@ -2445,14 +2434,24 @@ pub fn to_geojson_text(ds: &Dataset) -> Result { } /// [`to_geojson_text`]'s collection, written to `out`, buffered: its serializer writes a few -/// bytes at a time. -fn write_geojson(ds: &Dataset, out: &mut impl std::io::Write) -> Result<()> { +/// bytes at a time. The features are written as they are walked, so a sink that refuses a write +/// ([`crate::capped::Limit::file`]) stops it there. +pub fn write_geojson(ds: &Dataset, out: &mut (impl std::io::Write + ?Sized)) -> Result<()> { let mut writer = GeoJsonWriter::new(std::io::BufWriter::new(out), &ds.name, &ds.fields)?; writer.write(&ds.features)?; std::io::Write::flush(&mut writer.finish()?)?; Ok(()) } +/// [`write_geojson`] for an OGC API Features `items` document, which also says how many features +/// it returns (`numberReturned`). +pub fn write_geojson_items(ds: &Dataset, out: &mut (impl std::io::Write + ?Sized)) -> Result<()> { + let mut writer = GeoJsonWriter::new(std::io::BufWriter::new(out), &ds.name, &ds.fields)?; + writer.write(&ds.features)?; + std::io::Write::flush(&mut writer.finish_returning(ds.features.len())?)?; + Ok(()) +} + /// A feature as a GeoJSON Feature, its attributes named by `fields`. fn feature_to_geojson(fields: &[Field], feature: &crate::Feature) -> Json { // Making a value can't fail: every key is text. @@ -2538,6 +2537,12 @@ impl GeoJsonWriter { self.out.write_all(b"]}")?; Ok(self.out) } + + /// [`GeoJsonWriter::finish`] with a `numberReturned` member of `returned`. + fn finish_returning(mut self, returned: usize) -> Result { + write!(self.out, r#"],"numberReturned":{returned}}}"#)?; + Ok(self.out) + } } // --------------------------------------------------------------------------------------------- diff --git a/crates/data/src/row_access.rs b/crates/data/src/row_access.rs index 62cb8bbd7b..db74a4a6ea 100644 --- a/crates/data/src/row_access.rs +++ b/crates/data/src/row_access.rs @@ -56,6 +56,11 @@ impl Features { self.rows.is_empty() } + /// The memory the rows hold, their geometry, attribute text and spare capacity included. + pub fn held_bytes(&self) -> usize { + crate::source::chunk_memory::features_bytes(&self.rows) + } + /// Row `row`, if there is one. pub fn row(&self, row: usize) -> Option> { self.rows.get(row).map(|row| RowRef { row }) diff --git a/crates/data/src/zip.rs b/crates/data/src/zip.rs index 7f7edb869d..0a4f164dee 100644 --- a/crates/data/src/zip.rs +++ b/crates/data/src/zip.rs @@ -2,7 +2,7 @@ use std::io::{Seek, SeekFrom, Write}; -use crate::capped::{PIECE, write_pieces}; +use crate::capped::{Limit, PIECE, write_pieces}; /// Most entries read from an archive (plain zip holds at most 65,535; ZIP64 isn't read). const MAX_ENTRIES: usize = 65_535; @@ -45,51 +45,38 @@ pub fn write(entries: &[(String, Vec)]) -> Result, String> { Ok(out.into_inner()) } +/// [`write`]'s archive of `entries` within `limit`: the entries, held already, stay counted +/// against it while the archive is made, and the archive is written within what they leave, so +/// the two together never pass it. +pub fn write_within(entries: &[(String, Vec)], limit: &Limit) -> crate::Result> { + let parts: usize = entries.iter().map(|(_, bytes)| bytes.capacity()).sum(); + let _parts = limit.hold(parts)?; + let mut out = limit.buffer(); + let made = write_to(entries, &mut out).map_err(crate::DataError::Format); + limit.whole(made.map(|()| out.into_inner())) +} + /// [`write`]'s archive, written to `out`, empty as it starts, as it is made (a buffer held to a -/// limit stops it there). Each entry is deflated into `out` a piece at a time, so besides `out` -/// it holds the central directory, a piece and the compressor. +/// limit stops it there), the central directory too. Each entry is deflated into `out` a piece at +/// a time, so besides `out` it holds a few numbers for each entry, a piece and the compressor. pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut (impl Write + Seek)) -> Result<(), String> { let too_big = || "the archive is too large for a zip file".to_string(); let failed = |e: std::io::Error| e.to_string(); let count = u16::try_from(entries.len()).map_err(|_| too_big())?; // How much of the archive is written: where the next entry starts. let mut written: usize = 0; - let mut central = Vec::new(); + // What each entry's central record repeats of it. + let mut records = Vec::with_capacity(entries.len()); for (name, data) in entries { let n = name.as_bytes(); let name_len = u16::try_from(n.len()).map_err(|_| too_big())?; let data_len = u32::try_from(data.len()).map_err(|_| too_big())?; let crc = crc32(data); let offset = u32::try_from(written).map_err(|_| too_big())?; - let header = |sig: u32, central: bool, method: u16, body_len: u32| { - let mut h = Vec::new(); - h.extend_from_slice(&sig.to_le_bytes()); - if central { - h.extend_from_slice(&20u16.to_le_bytes()); // made by - } - h.extend_from_slice(&20u16.to_le_bytes()); // needed to extract - h.extend_from_slice(&0x0800u16.to_le_bytes()); // UTF-8 names - h.extend_from_slice(&method.to_le_bytes()); - h.extend_from_slice(&0u16.to_le_bytes()); // time - h.extend_from_slice(&0x21u16.to_le_bytes()); // date: 1980-01-01 - h.extend_from_slice(&crc.to_le_bytes()); - h.extend_from_slice(&body_len.to_le_bytes()); - h.extend_from_slice(&data_len.to_le_bytes()); - h.extend_from_slice(&name_len.to_le_bytes()); - h.extend_from_slice(&0u16.to_le_bytes()); // extra - if central { - h.extend_from_slice(&0u16.to_le_bytes()); // comment - h.extend_from_slice(&0u16.to_le_bytes()); // disk - h.extend_from_slice(&0u16.to_le_bytes()); // internal attributes - h.extend_from_slice(&0u32.to_le_bytes()); // external attributes - h.extend_from_slice(&offset.to_le_bytes()); - } - h.extend_from_slice(n); - h - }; // The header goes before the body, whose method and length are known only after it: its // place is taken, then it is written again. - let local = header(0x0403_4B50, false, 0, 0); + let mut record = Record { method: 0, crc, body_len: 0, data_len, name_len, offset }; + let local = record.header(n, false); out.write_all(&local).map_err(failed)?; let body_at = written.saturating_add(local.len()) as u64; let (method, body_len) = match deflate_to(data, out).map_err(failed)? { @@ -101,17 +88,25 @@ pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut (impl Write + Se (0, data.len()) } }; - let body_len_32 = u32::try_from(body_len).map_err(|_| too_big())?; + record.method = method; + record.body_len = u32::try_from(body_len).map_err(|_| too_big())?; let end = body_at.saturating_add(body_len as u64); out.seek(SeekFrom::Start(written as u64)).map_err(failed)?; - out.write_all(&header(0x0403_4B50, false, method, body_len_32)).map_err(failed)?; + out.write_all(&record.header(n, false)).map_err(failed)?; out.seek(SeekFrom::Start(end)).map_err(failed)?; written = written.saturating_add(local.len()).saturating_add(body_len); - central.extend_from_slice(&header(0x0201_4B50, true, method, body_len_32)); + records.push(record); } let cd_offset = u32::try_from(written).map_err(|_| too_big())?; - let cd_len = u32::try_from(central.len()).map_err(|_| too_big())?; - let mut end = central; + // A record at a time: a directory of many entries is never held apart from `out`. + let mut cd_size: usize = 0; + for ((name, _), record) in entries.iter().zip(&records) { + let central = record.header(name.as_bytes(), true); + out.write_all(¢ral).map_err(failed)?; + cd_size = cd_size.saturating_add(central.len()); + } + let cd_len = u32::try_from(cd_size).map_err(|_| too_big())?; + let mut end = Vec::new(); end.extend_from_slice(&0x0605_4B50u32.to_le_bytes()); end.extend_from_slice(&[0, 0, 0, 0]); end.extend_from_slice(&count.to_le_bytes()); @@ -122,6 +117,46 @@ pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut (impl Write + Se out.write_all(&end).map_err(failed) } +/// An entry as its local header and its central record describe it. +struct Record { + method: u16, + crc: u32, + body_len: u32, + data_len: u32, + name_len: u16, + offset: u32, +} + +impl Record { + /// The entry's central record, or its local header, followed by its name `n`. + fn header(&self, n: &[u8], central: bool) -> Vec { + let mut h = Vec::new(); + h.extend_from_slice(&if central { 0x0201_4B50u32 } else { 0x0403_4B50 }.to_le_bytes()); + if central { + h.extend_from_slice(&20u16.to_le_bytes()); // made by + } + h.extend_from_slice(&20u16.to_le_bytes()); // needed to extract + h.extend_from_slice(&0x0800u16.to_le_bytes()); // UTF-8 names + h.extend_from_slice(&self.method.to_le_bytes()); + h.extend_from_slice(&0u16.to_le_bytes()); // time + h.extend_from_slice(&0x21u16.to_le_bytes()); // date: 1980-01-01 + h.extend_from_slice(&self.crc.to_le_bytes()); + h.extend_from_slice(&self.body_len.to_le_bytes()); + h.extend_from_slice(&self.data_len.to_le_bytes()); + h.extend_from_slice(&self.name_len.to_le_bytes()); + h.extend_from_slice(&0u16.to_le_bytes()); // extra + if central { + h.extend_from_slice(&0u16.to_le_bytes()); // comment + h.extend_from_slice(&0u16.to_le_bytes()); // disk + h.extend_from_slice(&0u16.to_le_bytes()); // internal attributes + h.extend_from_slice(&0u32.to_le_bytes()); // external attributes + h.extend_from_slice(&self.offset.to_le_bytes()); + } + h.extend_from_slice(n); + h + } +} + /// `data` deflated into `out` at level 6, the bytes `compress_to_vec` makes: its length when that /// is less than `data`'s, else `None` once it would come to as much, with less than that written. fn deflate_to(data: &[u8], out: &mut impl Write) -> std::io::Result> { @@ -393,6 +428,47 @@ fn read_within(bytes: &[u8], want: impl Fn(&str) -> bool, budget: usize, spreads mod tests { use super::*; + /// An archive that notes the largest piece offered to it. + #[derive(Default)] + struct Pieces { + archive: std::io::Cursor>, + largest: usize, + } + + impl Write for Pieces { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.largest = self.largest.max(bytes.len()); + self.archive.write(bytes) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl Seek for Pieces { + fn seek(&mut self, to: SeekFrom) -> std::io::Result { + self.archive.seek(to) + } + } + + /// Many small entries make a large central directory: it is handed to the output a record at + /// a time, so a limit on the output stops it there, and it is never held apart. + #[test] + fn the_central_directory_is_written_a_record_at_a_time() { + let entries: Vec<(String, Vec)> = (0..500).map(|i| (format!("entry-{i:04}"), vec![b'x'])).collect(); + let mut out = Pieces::default(); + write_to(&entries, &mut out).unwrap(); + // A central record is 46 bytes and the 10 of its name; the directory is 28,000. + assert_eq!(out.largest, 46 + entries[0].0.len()); + let archive = out.archive.into_inner(); + assert_eq!(read(&archive).unwrap(), entries); + // Room for every entry and all but the last of the directory is refused. + let held: usize = entries.iter().map(|(_, bytes)| bytes.capacity()).sum(); + let limit = Limit::new(held + archive.len() - 1); + assert!(write_within(&entries, &limit).is_err() && limit.passed()); + } + /// An entry's body is what deflating it in one call at level 6 gives when that is smaller, /// else the entry as it is, with the next record straight after: for entries shorter and /// longer than a piece, that deflate or not. diff --git a/crates/engine/src/cmd/deeplearning.rs b/crates/engine/src/cmd/deeplearning.rs index c73c7e4740..b4b922e578 100644 --- a/crates/engine/src/cmd/deeplearning.rs +++ b/crates/engine/src/cmd/deeplearning.rs @@ -3,7 +3,6 @@ //! in the project and shared as packages, and rasters cut into web map tiles. use std::collections::HashMap; -use std::path::Path; use rustgis_analysis::neural::{self, MAX_SAMPLES_PER_CLASS, Mlp}; use rustgis_analysis::rasterops; @@ -76,10 +75,11 @@ pub fn commands() -> Vec { r#"{"layer": raster, "model"?: a trained model's name, "training"?: polygon layer, "classField"?: field, "bands"?: [1-based], "hidden"?: [units], "epochs"?: 1..500 (without a model: train one first, as dl.train), "name"?: output, "ran"?: (internal: classes the app has worked out)}"#, ), C::new("dl.package", "Deep Learning Package", "Publish › Package", |s, p| { - let path = ps(p, "path").ok_or("path is required")?; - let bytes = package(s, p)?; - rustgis_data::io::write_atomic(Path::new(path), &bytes).map_err(|e| format!("{path}: {e}"))?; - Ok(json!({"path": path, "bytes": bytes.len()})) + super::exports::file_command(s, "dl.package", p, |s, out| { + let bytes = package_within(s, p, out)?; + let answer = json!({"path": out.path, "bytes": bytes.len()}); + Ok(super::exports::Made::new(bytes, answer)) + }) }).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_model) @@ -385,9 +385,14 @@ pub(crate) fn classify_work(s: &Session, p: &Value) -> Result Result, String> { + package_within(s, p, super::exports::Output::UNLIMITED) +} + +/// [`package`] for the file `out` describes. +pub(super) fn package_within(s: &Session, p: &Value, out: super::exports::Output<'_>) -> Result, String> { let i = model_index(s, p)?; let m = s.project.dl_models.get(i).ok_or("no model")?; - let model = serde_json::to_vec_pretty(m).map_err(|e| e.to_string())?; + let model = out.json_pretty(m)?; let about = json!({ "format": "RustGIS deep learning package", "version": 1, @@ -399,7 +404,10 @@ pub fn package(s: &Session, p: &Value) -> Result, String> { "accuracy": m.accuracy, }); let about = serde_json::to_vec_pretty(&about).map_err(|e| e.to_string())?; - rustgis_data::zip::write(&[("model.json".into(), model), ("package.json".into(), about)]) + let mut parts = out.parts(); + parts.push("model.json".into(), model)?; + parts.push("package.json".into(), about)?; + parts.zip() } /// Web Mercator tile bounds (metres) of tile (z, x, y). @@ -413,15 +421,21 @@ fn tile_bounds(z: u32, x: u32, y: u32) -> (f64, f64, f64, f64) { /// Cuts a raster into XYZ web map tiles (PNG, transparent outside the raster). fn hosted(s: &mut Session, p: &Value) -> CmdResult { - let path = ps(p, "path").ok_or("path is required")?.to_string(); - let (bytes, mut info) = hosted_bytes(s, p)?; - rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; - info["path"] = json!(path); - Ok(info) + super::exports::file_command(s, "imagery.hostedImagery", p, |s, out| { + let (bytes, mut info) = hosted_within(s, p, out)?; + info["path"] = json!(out.path); + Ok(super::exports::Made::new(bytes, info)) + }) } /// The tiles of a raster as a zip, and what's in it. pub fn hosted_bytes(s: &mut Session, p: &Value) -> Result<(Vec, Value), String> { + hosted_within(s, p, super::exports::Output::UNLIMITED) +} + +/// [`hosted_bytes`] for the file `out` describes: a downloaded one stops at the tile that passes +/// its room. +pub(super) fn hosted_within(s: &mut Session, p: &Value, out: super::exports::Output<'_>) -> Result<(Vec, Value), String> { let r = raster(s, p)?; let lname = ps(p, "layer").unwrap_or_default().to_string(); let mut layer = s.map().layer_by_name(&lname).cloned().ok_or("no such layer")?; @@ -477,8 +491,8 @@ pub fn hosted_bytes(s: &mut Session, p: &Value) -> Result<(Vec, Value), Stri map.basemap = rustgis_map::Basemap::Blank; map.graticule = false; map.layers = vec![layer]; - let mut entries = Vec::new(); - let mut held = 0usize; + let mut parts = out.parts(); + let (mut held, mut n) = (0usize, 0usize); for (z, x, y) in &jobs { let (min_x, min_y, max_x, max_y) = tile_bounds(*z, *x, *y); let camera = rustgis_map::Camera { @@ -508,7 +522,8 @@ pub fn hosted_bytes(s: &mut Session, p: &Value) -> Result<(Vec, Value), Stri if held > MAX_TILE_BYTES { return Err(format!("the tiles passed {} MB at zoom {z}; lower maxZoom", MAX_TILE_BYTES >> 20)); } - entries.push((format!("tiles/{z}/{x}/{y}.png"), png)); + parts.push(format!("tiles/{z}/{x}/{y}.png"), png)?; + n += 1; } } let c = e.center(); @@ -521,10 +536,9 @@ pub fn hosted_bytes(s: &mut Session, p: &Value) -> Result<(Vec, Value), Stri "bounds": [e.min_x, e.min_y, e.max_x, e.max_y], "center": [c.x, c.y, min_z], }); - let n = entries.len(); - entries.push(("tiles.json".into(), serde_json::to_vec_pretty(&tilejson).map_err(|e| e.to_string())?)); - entries.push(("index.html".into(), viewer(&lname, min_z, max_z, c).into_bytes())); - let bytes = rustgis_data::zip::write(&entries)?; + parts.push("tiles.json".into(), serde_json::to_vec_pretty(&tilejson).map_err(|e| e.to_string())?)?; + parts.push("index.html".into(), viewer(&lname, min_z, max_z, c).into_bytes())?; + let bytes = parts.zip()?; Ok((bytes, json!({"tiles": n, "minZoom": min_z, "maxZoom": max_z}))) } diff --git a/crates/engine/src/cmd/exports.rs b/crates/engine/src/cmd/exports.rs index 0e060c1f3a..04357ea7f7 100644 --- a/crates/engine/src/cmd/exports.rs +++ b/crates/engine/src/cmd/exports.rs @@ -9,13 +9,17 @@ //! The browser has no filesystem to write a path in ([`Session::downloads_files`]): there //! [`write_here`] names the export after the path's file, its work gives the bytes back instead //! of writing them ([`place`]), and the front end offers them as a download, as it does a tool's -//! file output (`gp.fileDelivered`). +//! file output (`gp.fileDelivered`). A command that saves, packages or shares a file at once +//! ([`file_command`], [`download_command`]) is downloaded the same way, and one that needs the +//! file to stay where it is refuses. use std::borrow::Cow; +use std::io::Write; use std::sync::Arc; -use rustgis_data::Dataset; use rustgis_data::capped::Limit; +use rustgis_data::{DataError, Dataset}; +use serde::Serialize; use serde_json::Value; use crate::{CmdResult, Session}; @@ -121,12 +125,11 @@ impl Room { /// Why `path`'s file, stopped as it passed the room, can't be downloaded, and what to do. pub(crate) fn refusal(self, path: &str) -> String { let cap = mib(self.bytes.saturating_add(self.waiting)); - let ways = "export less (a selection of features, a smaller size or fewer pages), use the Export buttons, or use the desktop app"; if self.waiting == 0 { - format!("{path}: stopped once the file passed the {cap} MiB a command can download in the browser; {ways}") + format!("{path}: stopped once the file passed the {cap} MiB a command can download in the browser; {SMALLER}") } else { format!( - "{path}: stopped once the file passed what is left of the {cap} MiB that downloads can hold in the browser, {} MiB of it taken by those already waiting; split the task, model, or script into smaller runs, {ways}", + "{path}: stopped once the file passed what is left of the {cap} MiB that downloads can hold in the browser, {} MiB of it taken by those already waiting; split the task, model, or script into smaller runs, {SMALLER}", mib(self.waiting) ) } @@ -140,6 +143,136 @@ 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"; + +/// 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. +#[derive(Clone, Copy)] +pub(crate) struct Output<'a> { + pub(crate) path: &'a str, + room: Option, +} + +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 }; + + /// Whether it is made to be downloaded. + pub(crate) fn downloads(self) -> bool { + self.room.is_some() + } + + /// The most bytes it may come to. + pub(crate) fn most(self) -> usize { + self.room.map_or(usize::MAX, |room| room.bytes) + } + + /// Why it can't be downloaded, having passed the room. + pub(crate) fn refusal(self) -> String { + self.room.map_or_else(|| format!("{}: the file would be too large", self.path), |room| room.refusal(self.path)) + } + + /// Refuses once `held` bytes of the file, or of what it is made of, pass the room. + pub(crate) fn check(self, held: usize) -> Result<(), String> { + if held > self.most() { Err(self.refusal()) } else { Ok(()) } + } + + /// The file `write` makes, stopped as soon as it passes the room. + pub(crate) fn file(self, write: impl FnOnce(&mut dyn Write) -> Result<(), String>) -> Result, String> { + self.file_up_to(usize::MAX, || self.refusal(), write) + } + + /// [`Output::file`] for a kind of file that holds `most` bytes, refused past them with + /// `too_large`; where the room is less, past that, with its refusal. + pub(crate) fn file_up_to( + self, + most: usize, + too_large: impl FnOnce() -> String, + write: impl FnOnce(&mut dyn Write) -> Result<(), String>, + ) -> Result, String> { + let limit = Limit::new(most.min(self.most())); + let made = made_within(&limit, write); + if limit.passed() { + return Err(if self.most() < most { self.refusal() } else { too_large() }); + } + made + } + + /// `value` as compact JSON, stopped at the room. + pub(crate) fn json(self, value: &T) -> Result, String> { + self.file(|out| serde_json::to_writer(out, value).map_err(|e| e.to_string())) + } + + /// `value` as indented JSON, stopped at the room. + pub(crate) fn json_pretty(self, value: &T) -> Result, String> { + self.file(|out| serde_json::to_writer_pretty(out, value).map_err(|e| e.to_string())) + } + + /// A zip archive whose entries are made one at a time ([`Parts`]). + pub(crate) fn parts(self) -> Parts<'a> { + Parts { out: self, held: 0, entries: Vec::new() } + } +} + +/// The file `write` makes within `limit` ([`Limit::file`]), or why it didn't, in its own words. +fn made_within(limit: &Limit, write: impl FnOnce(&mut dyn Write) -> Result<(), String>) -> Result, String> { + let mut failed = None; + let made = limit.file(|out| { + // A serializer writes a token at a time, each a call into `out` and a look at the limit. + let mut pieces = std::io::BufWriter::with_capacity(16 << 10, out); + match write(&mut pieces) { + Ok(()) => Ok(pieces.flush()?), + Err(why) => { + // What is left unwritten goes with the file, rather than be written as it is dropped. + let _ = pieces.into_parts(); + failed = Some(why); + Err(DataError::Format(String::new())) + } + } + }); + made.map_err(|e| failed.unwrap_or_else(|| e.to_string())) +} + +/// The entries of a zip archive as they are made, together held to its file's room, then the +/// archive made within what they leave of it ([`rustgis_data::zip::write_within`]). +pub(crate) struct Parts<'a> { + out: Output<'a>, + held: usize, + entries: Vec<(String, Vec)>, +} + +impl Parts<'_> { + /// Adds the entry `name` that `write` makes, stopped as the entries pass the room. + pub(crate) fn make(&mut self, name: String, write: impl FnOnce(&mut dyn Write) -> Result<(), String>) -> Result<(), String> { + let limit = Limit::new(self.out.most().saturating_sub(self.held)); + let made = made_within(&limit, write); + if limit.passed() { + return Err(self.out.refusal()); + } + self.push(name, made?) + } + + /// Adds the entry `name`, made already, refused once the entries pass the room. + pub(crate) fn push(&mut self, name: String, mut bytes: Vec) -> Result<(), String> { + // Spare room counts against the archive's limit while it is made. + bytes.shrink_to_fit(); + self.held = self.held.saturating_add(bytes.len()); + self.out.check(self.held)?; + self.entries.push((name, bytes)); + Ok(()) + } + + /// The archive of the entries. + pub(crate) fn zip(self) -> Result, String> { + match self.out.room { + None => rustgis_data::zip::write(&self.entries), + Some(room) => room.encode(self.out.path, |limit| rustgis_data::zip::write_within(&self.entries, limit)), + } + } +} + /// `bytes` in MiB, rounded up. pub(crate) fn mib(bytes: usize) -> usize { bytes.div_ceil(1 << 20) @@ -155,12 +288,19 @@ pub(crate) const MAX_DOWNLOAD_BYTES: usize = 256 << 20; /// 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) +} + +/// [`read_for_download`] for a file made of several layers, `held` bytes of whose features were +/// read before this one's: together they are held to [`MAX_DOWNLOAD_BYTES`]. +pub(super) fn read_for_download_after(l: &rustgis_map::Layer, held: usize) -> Result<(Dataset, rustgis_map::Unreadable), String> { + let needs = if held == 0 { "the layer needs" } else { "with the layers read before it, the layer needs" }; let refusal = format!( - "{}: the layer needs more than the {} MiB of features the web app reads for a download; zoom in, select the features you need, use Make Layer From Selected Features and export that layer, or use the desktop app", + "{}: {needs} more than the {} MiB of features the web app reads for a download; zoom in, select the features you need, use Make Layer From Selected Features and export that layer, or use the desktop app", l.name, MAX_DOWNLOAD_BYTES >> 20 ); - l.load_all_counted_up_to(MAX_DOWNLOAD_BYTES as u64, &refusal) + l.load_all_counted_up_to(MAX_DOWNLOAD_BYTES.saturating_sub(held) as u64, &refusal) } /// Export `command`'s parameters when its file is downloaded: `path` cut to the download's name, @@ -173,7 +313,7 @@ fn for_download<'a>(command: &str, p: &'a Value) -> Result<(Cow<'a, Value>, Vec< let mut name = path.rsplit(['/', '\\']).next().unwrap_or_default().to_string(); if matches!(name.as_str(), "" | "." | "..") { return Err(format!( - "{path}: the browser downloads an export under the file name its path ends in, and this one has none; end it in a name such as map.png" + "{path}: the browser downloads a file under the name its path ends in, and this one has none; end it in a file name, such as map.png" )); } let folder = name != path; @@ -203,11 +343,17 @@ fn for_download<'a>(command: &str, p: &'a Value) -> Result<(Cow<'a, Value>, Vec< Ok((Cow::Owned(p), notes)) } -/// Background exports that render map, layout, report, or scene text with installed fonts. +/// Exports that render map, layout, report, presentation or scene text with installed fonts. fn uses_fonts(command: &str) -> bool { - matches!(command, "share.exportMap" | "layout.export" | "report.export" | "map.exportOrbit" | "map.exportBlock") + matches!(command, "share.exportMap" | "layout.export" | "report.export" | "presentation.export" | "map.exportOrbit" | "map.exportBlock") } +/// Why a font-drawing export is refused while the CJK font folders are still being scanned. +const CJK_PENDING: &str = "CJK font folder scan is still running; try exporting again in a moment"; + +/// What is said of an export during which that scan started. +const CJK_STARTED: &str = "CJK font folder scan started during this export; re-run it once the scan finishes if CJK text is missing."; + #[cfg(test)] thread_local! { static TEST_CJK_SCAN_PENDING: std::cell::Cell = const { std::cell::Cell::new(false) }; @@ -227,7 +373,7 @@ fn cjk_scan_pending() -> bool { pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult { let &(_, name, start) = IN_BACKGROUND.iter().find(|(c, ..)| *c == command).ok_or_else(|| format!("{command} isn't an export"))?; if uses_fonts(command) && cjk_scan_pending() { - return Err("CJK font folder scan is still running; try exporting again in a moment".into()); + return Err(CJK_PENDING.into()); } // Only an export that takes a path is named after it (Publish to Source writes the layer's // own source, and says itself what the browser can't do). @@ -249,10 +395,7 @@ pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult } })?; if pending_cjk { - wrote.diagnostics.push(( - rustgis_data::diagnostics::Severity::Warning, - "CJK font folder scan started during this export; re-run it once the scan finishes if CJK text is missing.".into(), - )); + wrote.diagnostics.push((rustgis_data::diagnostics::Severity::Warning, CJK_STARTED.into())); } s.check_continuation(&owner).map_err(|why| { // A download not yet offered wrote nothing. @@ -268,6 +411,161 @@ pub(crate) fn write_here(s: &mut Session, p: &Value, command: &str) -> CmdResult said(s, wrote) } +/// A file a command makes at once, on the thread that runs it ([`file_command`]). +pub(crate) struct Made { + pub(crate) bytes: Vec, + /// What the command answers once the file is written, or its download is taken. + pub(crate) answer: Value, + /// What it says once the file is out, after what making it said. + pub(crate) notes: rustgis_data::loss::Notes, + /// The line saying the file is out. Without one, a download says it was offered. + pub(crate) done: Option, + /// What a download does to the session once taken. + pub(crate) taken: Option>, +} + +impl Made { + /// `bytes`, answered with `answer`, with nothing more to say of them. + pub(crate) fn new(bytes: Vec, answer: Value) -> Self { + Made { bytes, answer, notes: Default::default(), done: None, taken: None } + } +} + +/// `command`'s file, made by `build` for the path it is given: written there, or, where files are +/// downloaded ([`Session::downloads_files`]), offered as a download ([`download_command`]). +pub(crate) fn file_command( + s: &mut Session, + command: &str, + p: &Value, + build: impl FnOnce(&mut Session, Output<'_>) -> Result, +) -> CmdResult { + if s.downloads_files() { + return download_command(s, command, p, build); + } + // A file drawn with installed fonts waits for their folders to be read, as the downloaded + // one does, and says when a scan started while it was drawn. + if uses_fonts(command) && cjk_scan_pending() { + return Err(CJK_PENDING.into()); + } + let mark = s.notice_mark(); + let path = super::ps(p, "path").ok_or("path is required")?; + let out = Output { path, room: None }; + let (made, pending_cjk) = + if uses_fonts(command) { rustgis_render::fonts::track_pending_cjk(|| build(s, out)) } else { (build(s, out), false) }; + let made = made?; + rustgis_data::io::write_atomic(std::path::Path::new(path), &made.bytes).map_err(|e| format!("{path}: {e}"))?; + for note in made.notes { + s.say(note); + } + if pending_cjk { + s.warn(CJK_STARTED); + } + s.retain_written_notices(mark); + if let Some(done) = made.done { + s.notify_written(done); + } + Ok(made.answer) +} + +/// Queues the file `build` makes for the front end to offer as a download, under the file name +/// `p`'s path ends in. `build` is given that name and the room the downloads waiting leave +/// ([`Session::download_room`], refused before anything is made when no more can wait), and +/// makes the file within it. The answer says it is pending, with what will be said of it; that +/// is said, and `command`'s answer given, once the front end has taken the download +/// (`gp.fileDelivered`). A download not taken says only why. +pub(crate) fn download_command( + s: &mut Session, + command: &str, + p: &Value, + build: impl FnOnce(&mut Session, Output<'_>) -> Result, +) -> CmdResult { + if uses_fonts(command) && cjk_scan_pending() { + return Err(CJK_PENDING.into()); + } + let (p, renamed) = for_download(command, p)?; + let name = super::ps(&p, "path").ok_or("path is required")?.to_string(); + let owner = s.continuation()?; + owner.check()?; + let out = Output { path: &name, room: s.download_room()? }; + // What making the file says waits with it. + let (made, held) = s.holding_notices(|s| { + let (made, pending_cjk) = + if uses_fonts(command) { rustgis_render::fonts::track_pending_cjk(|| build(s, out)) } else { (build(s, out), false) }; + let mut made = made?; + for note in std::mem::take(&mut made.notes) { + s.say(note); + } + if pending_cjk { + s.warn(CJK_STARTED); + } + Ok::<_, String>(made) + }); + let made = match made.and_then(|made| s.check_continuation(&owner).map(|()| made)) { + Ok(made) => made, + // No file: said as a command that fails says it. + Err(why) => { + for notice in held { + s.relay_notice(notice); + } + return Err(why); + } + }; + let said: Vec = held.iter().map(|notice| notice.text.clone()).collect(); + // 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}")); + let then: Then = Box::new(move |s: &mut Session, _: &mut Value| { + if let Some(taken) = taken { + taken(s); + } + s.notify_written(done); + let mark = s.notice_mark(); + for notice in held { + s.relay_notice(notice); + } + s.retain_written_notices(mark); + Ok(()) + }); + let wrote = Wrote { + answer, + notes: renamed.into_iter().collect(), + diagnostics: Vec::new(), + refused_notes: Vec::new(), + written_path: Some(name), + download: Some(Arc::new(bytes)), + then: Some(then), + #[cfg(not(target_arch = "wasm32"))] + owner: None, + #[cfg(not(target_arch = "wasm32"))] + crs_used: Vec::new(), + }; + let mut out = match super::gp::queue_export(s, wrote) { + Ok(out) => out, + Err(why) => { + for notice in unsent { + s.relay_notice(notice); + } + return Err(why); + } + }; + if let Some(messages) = out["messages"].as_array_mut() { + messages.extend(said.into_iter().map(Value::String)); + } + Ok(out) +} + +/// Refuses, where files are downloaded, a `path` a command would write for a layer to read its +/// pixels from: a download can't be read back. +pub(crate) fn no_layer_file(s: &Session, p: &Value) -> Result<(), String> { + match super::ps(p, "path").map(str::trim).filter(|path| !path.is_empty()) { + Some(path) if s.downloads_files() => Err(format!( + "{path}: the web app can't write a file for the layer to read; leave out path (the project keeps the result), then download it with share.exportRaster" + )), + _ => Ok(()), + } +} + /// Keeps a completed file visible when its result cannot be delivered to the session. pub(crate) fn completion_refused(written_path: Option<&str>, why: String) -> String { match written_path { @@ -732,5 +1030,37 @@ mod tests { let table_err = write_here(&mut s, &serde_json::json!({"layer": "NoSuchLayer", "path": "out.csv"}), "share.exportTable").unwrap_err(); assert!(!table_err.contains("CJK font folder scan"), "{table_err}"); + + // A file command that draws with fonts waits on the desktop too, before anything is made. + let made = std::cell::Cell::new(false); + let build = |_: &mut Session, _: Output<'_>| { + made.set(true); + Err::("not reached".into()) + }; + let err = file_command(&mut s, "presentation.export", &serde_json::json!({"path": "deck.pdf"}), build).unwrap_err(); + assert!(err.contains("CJK font folder scan is still running"), "{err}"); + assert!(!made.get()); + } + + /// A download the queue refuses (a file not made within the room, past the limit) says what + /// making it said, as one that isn't made does. The command here only reads the project, so + /// its failure withdraws no warnings. + #[test] + fn a_download_the_queue_refuses_says_what_making_it_said() { + let mut s = Session::new(crate::Project::default()); + s.queue_gp_files = true; + s.download_cap = Some(10); + let big_file = crate::CommandSpec::new("test.bigFile", "Big file", "Test", |s, p| { + download_command(s, "test.bigFile", p, |s, _| { + s.warn("made it with a note"); + Ok(Made::new(vec![0; 100], serde_json::Value::Null)) + }) + }); + s.registry.commands.push(big_file.view()); + let mark = s.notice_mark(); + let err = s.run("test.bigFile", &serde_json::json!({"path": "big.bin"})).unwrap_err(); + assert!(err.contains("big.bin"), "{err}"); + assert!(s.notices_since(mark).iter().any(|n| n.text == "made it with a note"), "{:?}", s.notices_since(mark)); + assert!(s.take_gp_files().is_empty()); } } diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 41dd0250dd..96d2f73680 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -3903,9 +3903,10 @@ fn queue(s: &mut Session, file_name: String, bytes: Arc>, from: Delivery let size = bytes.capacity(); if matches!(from, Delivery::Export(_)) && size > cap { return Err(format!( - "{file_name}: {} MiB, more than the {} MiB a command can download in the browser; export less (a selection of features, a smaller size or fewer pages), use the Export buttons, or use the desktop app", + "{file_name}: {} MiB, more than the {} MiB a command can download in the browser; {}", mib(size), - mib(cap) + mib(cap), + super::exports::SMALLER )); } if s.waiting_download_count() >= MAX_DOWNLOADS || size > cap.saturating_sub(held) { diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 6c92d161e4..31127f4f70 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -446,6 +446,7 @@ fn warp_to_fit(s: &mut Session, p: &Value, layer: &str, r: &Raster) -> CmdResult None | Some(Value::Null) => None, Some(v) => Some(v.as_f64().filter(|c| c.is_finite() && *c > 0.0).ok_or("cellSize is a positive number, in the output's units")?), }; + super::exports::no_layer_file(s, p)?; let path = match p.get("path") { None | Some(Value::Null) => None, Some(v) => Some(v.as_str().filter(|t| is_tif(t)).ok_or("path is a *.tif or *.tiff file")?.to_string()), @@ -505,6 +506,7 @@ const EXTENT: &str = "extent is a polygon layer's name, [west, south, east, nort /// extent, or on another raster's grid, each cell sampled at its centre or taken from every /// pixel whose centre falls in it (see `rustgis_analysis::warp::project`). A new layer. fn project_raster(s: &mut Session, p: &Value) -> CmdResult { + super::exports::no_layer_file(s, p)?; let r = raster(s, p)?; r.require_coordinates()?; let method = match p.get("resampling") { @@ -574,6 +576,7 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { /// `path` when given and makes the layer; once it is added, its notices are said and a text /// field's class table is added. pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result { + super::exports::no_layer_file(s, p)?; let ln = rasterize_name(p)?; let l = s.map().layer_by_name(ln).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{ln}'"))?; let ds = &l.dataset; @@ -2541,6 +2544,7 @@ const MOSAIC_PIECE: usize = 1 << 20; /// and where a file format's reader and the GeoTIFF writer look: some formats are read without a /// look. pub(crate) fn mosaic_rasters_work(s: &Session, p: &Value) -> Result { + super::exports::no_layer_file(s, p)?; let inputs = p.get("inputs").and_then(Value::as_array).ok_or("inputs is a list of raster layers or file paths")?; if inputs.len() < 2 { return Err("a mosaic needs two or more rasters".into()); @@ -3398,12 +3402,43 @@ fn mesh(s: &mut Session, p: &Value) -> CmdResult { // The mesh is laid out in metres on the ground, which a scan has none of. r.require_coordinates()?; let step = uint(p, "step").unwrap_or(((r.width.max(r.height) / 300).max(1)) as u64).clamp(1, 1000) as i64; - let (cx, cy) = r.cell_size_m(); let (nc, nr) = ((r.width as i64 - 1) / step + 1, (r.height as i64 - 1) / step + 1); if nc * nr > 1_000_000 { return Err("the mesh would be too large; use a larger step".into()); } - let mut obj = format!("# {} surface mesh exported by RustGIS\no {}\n", r.name, r.name.replace(char::is_whitespace, "_")); + match ps(p, "path") { + Some(_) if s.downloads_files() => super::exports::download_command(s, "imagery.mesh", p, |_, out| { + let mut counts = (0, 0); + let obj = out.file(|w| { + counts = write_surface(w, &r, step)?; + Ok(()) + })?; + let answer = json!({"path": out.path, "vertices": counts.0, "faces": counts.1}); + Ok(super::exports::Made::new(obj, answer)) + }), + Some(path) => { + let mut obj = Vec::new(); + let (v, faces) = write_surface(&mut obj, &r, step)?; + rustgis_data::io::write_atomic(std::path::Path::new(path), &obj).map_err(|e| format!("{path}: {e}"))?; + s.retain_written_notices(written); + Ok(json!({"path": path, "vertices": v, "faces": faces})) + } + None => { + let mut obj = Vec::new(); + let (v, faces) = write_surface(&mut obj, &r, step)?; + let text = String::from_utf8(obj).map_err(|e| e.to_string())?; + Ok(json!({"text": text, "vertices": v, "faces": faces})) + } + } +} + +/// Writes surface model `r`, every `step`th cell, to `w` as an OBJ mesh, a line at a time: how +/// many vertices and faces it has. A raster with no surface to mesh is refused. +fn write_surface(w: &mut dyn std::io::Write, r: &Raster, step: i64) -> Result<(usize, usize), String> { + let (cx, cy) = r.cell_size_m(); + let (nc, nr) = ((r.width as i64 - 1) / step + 1, (r.height as i64 - 1) / step + 1); + let failed = |e: std::io::Error| e.to_string(); + writeln!(w, "# {} surface mesh exported by RustGIS\no {}", r.name, r.name.replace(char::is_whitespace, "_")).map_err(failed)?; let mut ids = vec![0usize; (nc * nr) as usize]; let mut v = 0usize; for j in 0..nr { @@ -3413,7 +3448,7 @@ fn mesh(s: &mut Session, p: &Value) -> CmdResult { if let Some(slot) = ids.get_mut((j * nc + i) as usize) { *slot = v; } - obj.push_str(&format!("v {:.2} {:.2} {:.2}\n", i as f64 * step as f64 * cx, z, j as f64 * step as f64 * cy)); + writeln!(w, "v {:.2} {:.2} {:.2}", i as f64 * step as f64 * cx, z, j as f64 * step as f64 * cy).map_err(failed)?; } } } @@ -3423,11 +3458,11 @@ fn mesh(s: &mut Session, p: &Value) -> CmdResult { for i in 0..nc - 1 { let (a, b2, c, d) = (id(i, j), id(i + 1, j), id(i + 1, j + 1), id(i, j + 1)); if a > 0 && b2 > 0 && c > 0 { - obj.push_str(&format!("f {a} {c} {b2}\n")); + writeln!(w, "f {a} {c} {b2}").map_err(failed)?; faces += 1; } if a > 0 && c > 0 && d > 0 { - obj.push_str(&format!("f {a} {d} {c}\n")); + writeln!(w, "f {a} {d} {c}").map_err(failed)?; faces += 1; } } @@ -3435,14 +3470,7 @@ fn mesh(s: &mut Session, p: &Value) -> CmdResult { if faces == 0 { return Err("the raster has no surface to mesh".into()); } - match ps(p, "path") { - Some(path) => { - rustgis_data::io::write_atomic(std::path::Path::new(path), obj.as_bytes()).map_err(|e| format!("{path}: {e}"))?; - s.retain_written_notices(written); - Ok(json!({"path": path, "vertices": v, "faces": faces})) - } - None => Ok(json!({"text": obj, "vertices": v, "faces": faces})), - } + Ok((v, faces)) } /// The literal raster/secondary inputs used by this module, without reading any pixels/files. diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 48a0d1b6a8..93092c533d 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -3,7 +3,6 @@ //! Package, Save As and Output; Command Search for map/template imports). use std::borrow::Cow; -use std::fmt::Write as _; use std::path::Path; use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType}; @@ -12,6 +11,7 @@ use rustgis_map::palette::{RampFormat, read_ramps}; use rustgis_map::{Layer, Map, Ramp}; use serde_json::{Value, json}; +use super::exports::Output; use super::{b, f, need_feature_layer, need_layer, ps}; use crate::project::{StyleItem, Task, TaskStep}; use crate::{CmdResult, CommandSpec as C, Project, Session}; @@ -66,11 +66,11 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view(), // Map and layer files. - C::new("map.save", "Save Map File", "Publish › Save As", |s, p| save_item(s, "map", p)).inputs(map_save_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("map.save", "Save Map File", "Publish › Save As", |s, p| save_item(s, "map.save", "map", p)).inputs(map_save_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.rgismap", "map"?: name}"#), C::new("map.import", "Import", "Command Search", import_maps).roles(&[crate::ParamRole { key: "text", role: crate::Role::Document(crate::Document::Map) }]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(r#"{"path": "*.rgismap|*.rgis|*.rgispkg" | "text": map file JSON | "data": base64 file}"#), - C::new("layer.save", "Save Layer File", "Publish › Save As", |s, p| save_item(s, "layer", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("layer.save", "Save Layer File", "Publish › Save As", |s, p| save_item(s, "layer.save", "layer", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_layer) .params(r#"{"layer"?, "path": "*.rgislyr"}"#), @@ -168,7 +168,7 @@ pub fn commands() -> Vec { if s.project.styles.len() == before { Err(format!("no style '{name}'")) } else { Ok(Value::Null) } }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": style}"#), - C::new("style.save", "Save Style Items", "Publish › Save As", |s, p| save_item(s, "styles", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("style.save", "Save Style Items", "Publish › Save As", |s, p| save_item(s, "style.save", "styles", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.rgisstyle"}"#), // Custom colour ramps. @@ -212,14 +212,14 @@ pub fn commands() -> Vec { if s.project.ramps.len() == before { Err(format!("no colour ramp '{name}'")) } else { Ok(Value::Null) } }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": colour ramp}"#), - C::new("ramp.save", "Save Color Ramps", "Publish › Save As", |s, p| save_item(s, "ramps", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("ramp.save", "Save Color Ramps", "Publish › Save As", |s, p| save_item(s, "ramp.save", "ramps", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.rgisramp"}"#), // Project templates. - C::new("project.saveTemplate", "Save Project Template", "Publish › Save As", |s, p| save_item(s, "template", p)).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("project.saveTemplate", "Save Project Template", "Publish › Save As", |s, p| save_item(s, "project.saveTemplate", "template", p)).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.rgistemplate", "name"?: template name}"#), - C::new("project.newTemplate", "New Custom Template", "Publish › Save As", |s, p| save_item(s, "template", p)).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("project.newTemplate", "New Custom Template", "Publish › Save As", |s, p| save_item(s, "project.newTemplate", "template", p)).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.rgistemplate", "name"?: template name}"#), C::new("project.fromTemplate", "Open Custom Template", "Command Search", |s, p| { @@ -247,13 +247,13 @@ pub fn commands() -> Vec { .view() .params(r#"{"path"?: "*.rgistemplate", "text"?: template JSON, "data"?: base64 file, "name"?: new project name}"#), // Packages. - C::new("project.package", "Package Project", "Publish › Package", |s, p| save_item(s, "projectPackage", p)).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("project.package", "Package Project", "Publish › Package", |s, p| save_item(s, "project.package", "projectPackage", p)).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.rgispkg"}"#), - C::new("map.package", "Package Map", "Publish › Package", |s, p| save_item(s, if b(p, "mobile").unwrap_or(false) { "mobilePackage" } else { "mapPackage" }, p)).inputs(map_package_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("map.package", "Package Map", "Publish › Package", |s, p| save_item(s, "map.package", if b(p, "mobile").unwrap_or(false) { "mobilePackage" } else { "mapPackage" }, p)).inputs(map_package_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.rgismpk", "mobile"?: bool (simplify geometry and drop hidden layers, for phones and tablets), "tolerance"?: degrees}"#), - C::new("gp.package", "Package Results", "Publish › Package", |s, p| save_item(s, "gpPackage", p)).inputs(gp_package_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("gp.package", "Package Results", "Publish › Package", |s, p| save_item(s, "gp.package", "gpPackage", p)).inputs(gp_package_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.rgisgpk"}"#), // Layer templates. @@ -403,7 +403,7 @@ pub fn commands() -> Vec { if s.project.tasks.len() == before { Err(format!("no task '{name}'")) } else { Ok(Value::Null) } }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"task": name}"#), - C::new("task.save", "Save Task Item", "Publish › Save As", |s, p| save_item(s, "task", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("task.save", "Save Task Item", "Publish › Save As", |s, p| save_item(s, "task.save", "task", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"task"?: name, "path": "*.rgistask"}"#), C::new("task.import", "Import Task", "Analyze › Tasks", |s, p| { @@ -429,14 +429,10 @@ pub fn commands() -> Vec { ] } -fn to_json(v: &T) -> Result, String> { - serde_json::to_vec(v).map_err(|e| e.to_string()) -} - /// A task's file: the task, with `requires` listing what its steps need when they need anything /// (as a model's file does). A RustGIS that checks `requires` (#2867 on) refuses what it would run /// without; one that doesn't ignores the key, as it does for any task file today (#2818). -fn task_json(t: &Task) -> Result, String> { +fn task_json(t: &Task, out: Output<'_>) -> Result, String> { // A struct, not a `serde_json::Value`, which would sort the task's keys. #[derive(serde::Serialize)] struct TaskFile<'a> { @@ -446,7 +442,7 @@ fn task_json(t: &Task) -> Result, String> { requires: Vec<&'static str>, } let requires = crate::project::task_capabilities(&t.steps); - serde_json::to_vec(&TaskFile { task: t, requires }).map_err(|e| e.to_string()) + out.json(&TaskFile { task: t, requires }) } /// Whether command `id` can be added as a task's step (`task.addStep`): a built-in command, and @@ -872,7 +868,7 @@ fn template(p: &Project) -> (Project, TemplateLosses) { /// Packages only completed imports; runtime download reservations cannot be reopened. /// Refuses JSON beyond the project or ZIP inflation limit before creating the archive. -fn package_project(s: &mut Session, notes: &mut rustgis_data::loss::Notes) -> Result, String> { +fn package_project(s: &mut Session, notes: &mut rustgis_data::loss::Notes, out: Output<'_>) -> Result, String> { s.project.ensure_imports_complete()?; let mut p = s.project.clone(); let mut budget = MAX_EMBED; @@ -887,13 +883,16 @@ fn package_project(s: &mut Session, notes: &mut rustgis_data::loss::Notes) -> Re let limit = crate::project::max_bytes().min(rustgis_data::zip::MAX_TOTAL as u64); let room = limit.saturating_sub(readme.len() as u64); let package_too_large = || format!("the project is too large to package (maximum {} MiB)", limit >> 20); - let (text, report) = crate::durable::output_owned(p, |p| crate::project::json_within(p, room)?.ok_or_else(package_too_large))?; + let most = usize::try_from(room).unwrap_or(usize::MAX); + let (text, report) = crate::durable::output_owned(p, |p| { + out.file_up_to(most, package_too_large, |w| serde_json::to_writer(w, p).map_err(|e| e.to_string())) + })?; crate::durable::notify(s, &report); notes.extend(linked); - rustgis_data::zip::write(&[ - (format!("{}.{}", safe(&name), crate::project::EXTENSION), text.into_bytes()), - ("README.txt".into(), readme.into_bytes()), - ]) + let mut parts = out.parts(); + parts.push(format!("{}.{}", safe(&name), crate::project::EXTENSION), text)?; + parts.push("README.txt".into(), readme.into_bytes())?; + parts.zip() } pub(crate) fn safe(name: &str) -> String { @@ -919,7 +918,13 @@ fn mobile_map(mut m: Map) -> Map { } /// A package of the active map; `mobile` drops hidden layers and simplifies geometry. -fn package_map(s: &mut Session, mobile: bool, tol: f64, linked: &mut rustgis_data::loss::Notes) -> Result, String> { +fn package_map( + s: &mut Session, + mobile: bool, + tol: f64, + linked: &mut rustgis_data::loss::Notes, + out: Output<'_>, +) -> Result, String> { let mut m = embedded_map(s.map(), &mut MAX_EMBED.clone()); if mobile { m = mobile_map(m); @@ -961,11 +966,14 @@ fn package_map(s: &mut Session, mobile: bool, tol: f64, linked: &mut rustgis_dat linked.extend(left_linked("Package Map", [&m])); let name = m.name.clone(); // With the map file's header, so an older reader refuses what it can't draw. - let (bytes, report) = crate::durable::output_owned(m, crate::project::map_file_bytes)?; + let (bytes, report) = crate::durable::output_owned(m, |m| crate::project::map_file_within(m, out))?; crate::durable::notify(s, &report); let kind = if mobile { "mobile map package" } else { "map package" }; let readme = format!("{} — a RustGIS {kind}.\nAdd it to a project with Data › Import.\n", name); - let archive = rustgis_data::zip::write(&[(format!("{}.rgismap", safe(&name)), bytes), ("README.txt".into(), readme.into_bytes())])?; + let mut parts = out.parts(); + parts.push(format!("{}.rgismap", safe(&name)), bytes)?; + parts.push("README.txt".into(), readme.into_bytes())?; + let archive = parts.zip()?; for said in notes.without_polar().messages("Mobile map package, simplifying") { s.notify(said, false); } @@ -976,14 +984,14 @@ fn package_map(s: &mut Session, mobile: bool, tol: f64, linked: &mut rustgis_dat } /// The geoprocessing history with the layers its runs made, as GeoJSON. -fn package_gp(s: &mut Session) -> Result, String> { +fn package_gp(s: &mut Session, out: Output<'_>) -> Result, String> { if s.project.gp_history.is_empty() { return Err("no geoprocessing has been run yet".into()); } - let (history, report) = - crate::durable::output(&mut s.project.gp_history, None, |h| serde_json::to_vec_pretty(h).map_err(|e| e.to_string()))?; + let (history, report) = crate::durable::output(&mut s.project.gp_history, None, |h| out.json_pretty(h))?; crate::durable::notify(s, &report); - let mut entries = vec![("history.json".to_string(), history)]; + let mut parts = out.parts(); + parts.push("history.json".to_string(), history)?; let mut files = std::collections::HashSet::new(); let mut unplaced = (0usize, Vec::new()); for (_, l) in gp_result_layers(s) { @@ -1002,9 +1010,9 @@ fn package_gp(s: &mut Session) -> Result, String> { unplaced.0 += lost; unplaced.1.push(l.name.clone()); } - entries.push((file, rustgis_data::io::to_geojson(&ds).to_string().into_bytes())); + parts.make(file, |w| rustgis_data::io::write_geojson(&ds, w).map_err(|e| e.to_string()))?; } - let archive = rustgis_data::zip::write(&entries)?; + let archive = parts.zip()?; if let Some(said) = rustgis_data::unplaced_note("Geoprocessing package", &unplaced.1.join(", "), unplaced.0) { s.say(said); } @@ -1228,29 +1236,22 @@ pub(crate) fn names_place(v: &Value, keys: &[&str], depth: usize) -> bool { /// are extruded to a height, lines are polylines (OBJ only), points are small cubes. Coordinates /// are metres east and north of the layer's south-west corner. fn export_3d(s: &mut Session, p: &Value) -> CmdResult { - let written = s.notice_mark(); - let path = ps(p, "path").ok_or("path is required")?.to_string(); - if path.to_ascii_lowercase().ends_with(".stl") { - let (bytes, report, construction_notes) = stl_bytes(s, p)?; - rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; - for note in construction_notes { - s.say(note); - } - s.retain_written_notices(written); - s.notify_written(format!("Exported {path}")); - return Ok(json!({ - "path": path, "bytes": bytes.len(), "triangles": report.triangles, - "skippedDegenerate": report.degenerate, "linesDropped": report.lines, "capsFanned": report.fanned, - })); - } - let (obj, construction_notes) = obj_text(s, p)?; - rustgis_data::io::write_atomic(Path::new(&path), obj.as_bytes()).map_err(|e| format!("{path}: {e}"))?; - for note in construction_notes { - s.say(note); - } - s.retain_written_notices(written); - s.notify_written(format!("Exported {path}")); - Ok(json!({"path": path, "bytes": obj.len()})) + super::exports::file_command(s, "share.export3d", p, |s, out| { + let path = out.path; + let (bytes, answer, notes) = if path.to_ascii_lowercase().ends_with(".stl") { + let (bytes, report, notes) = stl_bytes(s, p, out)?; + let answer = json!({ + "path": path, "bytes": bytes.len(), "triangles": report.triangles, + "skippedDegenerate": report.degenerate, "linesDropped": report.lines, "capsFanned": report.fanned, + }); + (bytes, answer, notes) + } else { + let (obj, notes) = obj_text(s, p, out)?; + let answer = json!({"path": path, "bytes": obj.len()}); + (obj, answer, notes) + }; + Ok(super::exports::Made { notes: notes.into(), done: Some(format!("Exported {path}")), ..super::exports::Made::new(bytes, answer) }) + }) } /// Largest OBJ text or STL file written (512 MiB). @@ -1298,6 +1299,8 @@ struct Mesh { fanned: usize, /// Whether polylines are kept (OBJ) or only counted (STL, which can't hold them). keep_lines: bool, + /// The estimated size it stops at, and why. + most: (usize, String), /// Polygons left out because their outer ring has fewer than 3 vertices. skipped: usize, /// Holes left out because they have fewer than 3 vertices, so their areas stay solid. @@ -1356,14 +1359,10 @@ impl Mesh { Ok(()) } + /// Counts `bytes` more of the file's estimated size, refused past what the mesh may come to. fn grow(&mut self, bytes: usize) -> Result<(), String> { self.bytes += bytes; - // STL's estimate is its exact size, so it stops where the writer would. - if self.bytes > if self.keep_lines { MAX_MESH } else { MAX_OBJ } { - Err("the 3D file would be too large; export fewer features".into()) - } else { - Ok(()) - } + if self.bytes > self.most.0 { Err(self.most.1.clone()) } else { Ok(()) } } } @@ -1392,8 +1391,12 @@ fn placed_extent(ds: &Dataset, to: &rustgis_data::raster::Reprojection) -> Resul Ok(left_out.then_some(kept)) } -/// A feature layer as a mesh. -fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result { +/// Why a 3D export past its own limits is refused. +const TOO_LARGE_3D: &str = "the 3D file would be too large; export fewer features"; + +/// A feature layer as a mesh, for the file `out`: one for a download stops once it is estimated +/// past what a file that fits can be. +fn layer_mesh(s: &Session, p: &Value, keep_lines: bool, out: Output<'_>) -> Result { let id = s.layer_id(p)?; let l = s.map().layer(id).ok_or("no such layer")?; let hf = ps(p, "heightField").map(|n| l.dataset.field_index(n).ok_or_else(|| format!("no field '{n}'"))).transpose()?; @@ -1419,7 +1422,22 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result let m = rustgis_geom::lonlat_to_merc(c); ((m.x - origin.x) * k, (m.y - origin.y) * k) }; - let mut mesh = Mesh { keep_lines, layer: l.name.clone(), ..Mesh::default() }; + // A download's mesh is held to the most it can be estimated at when its file fits the room, + // and at least 16 MiB, so one far past the room is refused before much is built; the writer + // holds the file to the room itself. OBJ's estimate runs up to 3 times over (36 bytes for a + // vertex of 14, 24 for a face of 8). STL's counts the zero-area sides of a flat solid, which + // its writer leaves out: up to 4 times over, a triangle's 8 for the 2 kept. A layer of shapes + // with no area at all can be estimated further over still, so the refusal speaks of the model + // and not of the file. + const FLOOR: usize = 16 << 20; + let own = if keep_lines { MAX_MESH } else { MAX_OBJ }; + let room = out.most().saturating_mul(if keep_lines { 3 } else { 4 }).max(FLOOR); + let most = if room < own { + (room, format!("{}: the 3D model is too large to build for a download; {}", out.path, super::exports::SMALLER)) + } else { + (own, TOO_LARGE_3D.to_string()) + }; + let mut mesh = Mesh { keep_lines, most, layer: l.name.clone(), ..Mesh::default() }; let rows = l.visible_rows(); for (row, ft) in l.dataset.features.iter().enumerate() { if row.is_multiple_of(256) { @@ -1619,45 +1637,38 @@ fn ring_area(r: &[(f64, f64)]) -> f64 { a / 2.0 } -/// A feature layer as Wavefront OBJ text. -fn obj_text(s: &mut Session, p: &Value) -> Result<(String, Vec), String> { - let mesh = layer_mesh(s, p, true)?; +/// A feature layer as Wavefront OBJ text, written for the file `out`. +fn obj_text(s: &mut Session, p: &Value, out: Output<'_>) -> Result<(Vec, Vec), String> { + let mesh = layer_mesh(s, p, true, out)?; mesh_notices(s, &mesh); - let mut obj = String::new(); let l = s.layer_id(p).ok().and_then(|id| s.map().layer(id)); let name = l.map(|l| l.name.replace(char::is_whitespace, "_")).unwrap_or_default(); - let _ = write!(obj, "# {name} exported by RustGIS\no {name}\n"); + let too_large = || TOO_LARGE_3D.to_string(); + let obj = out.file_up_to(MAX_OBJ, too_large, |w| write_obj(w, &name, &mesh).map_err(|e| e.to_string()))?; + Ok((obj, mesh.constructions.notes())) +} + +/// `mesh` as the OBJ object `name`, written to `w` a line at a time. +fn write_obj(w: &mut dyn std::io::Write, name: &str, mesh: &Mesh) -> std::io::Result<()> { + write!(w, "# {name} exported by RustGIS\no {name}\n")?; let ids = |v: &[usize]| v.iter().map(|i| (i + 1).to_string()).collect::>().join(" "); for item in &mesh.items { match item { - Item::Vertex([x, y, z], false) => { - let _ = writeln!(obj, "v {x:.2} {y:.2} {z:.2}"); - } + Item::Vertex([x, y, z], false) => writeln!(w, "v {x:.2} {y:.2} {z:.2}")?, Item::Vertex([x, y, z], true) => { if *y == 0.0 { - let _ = writeln!(obj, "v {x:.2} 0 {z:.2}"); + writeln!(w, "v {x:.2} 0 {z:.2}")?; } else { - let _ = writeln!(obj, "v {x:.2} {y:.2} {z:.2}"); + writeln!(w, "v {x:.2} {y:.2} {z:.2}")?; } } - Item::Tri(v, _) => { - let _ = writeln!(obj, "f {}", ids(v)); - } - Item::Quad(v, _) => { - let _ = writeln!(obj, "f {}", ids(v)); - } - Item::Poly(v, _) => { - let _ = writeln!(obj, "f {}", ids(v)); - } - Item::Polyline(v) => { - let _ = writeln!(obj, "l {}", ids(v)); - } - } - if obj.len() > MAX_OBJ { - return Err("the 3D file would be too large; export fewer features".into()); + Item::Tri(v, _) => writeln!(w, "f {}", ids(v))?, + Item::Quad(v, _) => writeln!(w, "f {}", ids(v))?, + Item::Poly(v, _) => writeln!(w, "f {}", ids(v))?, + Item::Polyline(v) => writeln!(w, "l {}", ids(v))?, } } - Ok((obj, mesh.constructions.notes())) + Ok(()) } /// What an STL export left out or approximated. @@ -1677,7 +1688,7 @@ const MAX_STL_TRIANGLES: usize = (MAX_OBJ - 84) / 50; /// [`stl_bytes`] with a smaller triangle cap, to test the size guard. #[cfg(test)] pub(crate) fn stl_with_cap(s: &Session, p: &Value, cap: usize) -> Result { - mesh_stl(&layer_mesh(s, p, false)?, cap).map(|(_, r)| r.triangles) + mesh_stl(&layer_mesh(s, p, false, Output::UNLIMITED)?, cap, Output::UNLIMITED).map(|(_, r)| r.triangles) } /// Says what a layer's mesh left out, or used in place of a feature's own value. @@ -1713,9 +1724,9 @@ pub(crate) fn fanned_caps_note(n: usize) -> String { } /// A feature layer as binary STL, noting what it leaves out. -fn stl_bytes(s: &mut Session, p: &Value) -> Result<(Vec, StlReport, Vec), String> { - let mesh = layer_mesh(s, p, false)?; - let (bytes, report) = mesh_stl(&mesh, MAX_STL_TRIANGLES)?; +fn stl_bytes(s: &mut Session, p: &Value, out: Output<'_>) -> Result<(Vec, StlReport, Vec), String> { + let mesh = layer_mesh(s, p, false, out)?; + let (bytes, report) = mesh_stl(&mesh, MAX_STL_TRIANGLES, out)?; mesh_notices(s, &mesh); if mesh.flat > 0 { s.say(rustgis_data::loss::Note::loss( @@ -1744,8 +1755,9 @@ fn stl_bytes(s: &mut Session, p: &Value) -> Result<(Vec, StlReport, Vec Result<(Vec, StlReport), String> { +/// three vertices as little-endian f32 and a zero attribute. Written for the file `out`: it stops +/// at the first triangle kept that would pass its room. +fn mesh_stl(mesh: &Mesh, max_triangles: usize, out: Output<'_>) -> Result<(Vec, StlReport), String> { // The mesh is east, up and south; STL is written east, north and up, as slicers expect. let mut verts: Vec<[f64; 3]> = mesh.items.iter().filter_map(|it| if let Item::Vertex([x, y, z], _) = it { Some([*x, -*z, *y]) } else { None }).collect(); @@ -1758,8 +1770,8 @@ fn mesh_stl(mesh: &Mesh, max_triangles: usize) -> Result<(Vec, StlReport), S } let at = |n: usize| verts.get(n).copied(); // Each triangle is written as it comes (50 bytes), and the count filled in at the end. - let mut out = b"RustGIS binary STL, metres, Z up".to_vec(); - out.resize(84, 0); + let mut file = b"RustGIS binary STL, metres, Z up".to_vec(); + file.resize(84, 0); let mut count = 0usize; let mut degenerate = 0; let mut add = |ids: [usize; 3], orient: Orient| -> Result<(), String> { @@ -1787,16 +1799,17 @@ fn mesh_stl(mesh: &Mesh, max_triangles: usize) -> Result<(Vec, StlReport), S if count > max_triangles || count > u32::MAX as usize { return Err("the STL file would be too large; export fewer features".into()); } + out.check(file.len() + 50)?; let (b, c, n) = if flip { (c, b, [-n[0], -n[1], -n[2]]) } else { (b, c, n) }; for x in n { - out.extend_from_slice(&((x / len) as f32).to_le_bytes()); + file.extend_from_slice(&((x / len) as f32).to_le_bytes()); } for v in [a, b, c] { for x in v { - out.extend_from_slice(&(x as f32).to_le_bytes()); + file.extend_from_slice(&(x as f32).to_le_bytes()); } } - out.extend_from_slice(&0u16.to_le_bytes()); + file.extend_from_slice(&0u16.to_le_bytes()); Ok(()) }; for item in &mesh.items { @@ -1826,11 +1839,11 @@ fn mesh_stl(mesh: &Mesh, max_triangles: usize) -> Result<(Vec, StlReport), S }); } let n = u32::try_from(count).map_err(|_| "the STL file would be too large; export fewer features".to_string())?; - if let Some(slot) = out.get_mut(80..84) { + if let Some(slot) = file.get_mut(80..84) { slot.copy_from_slice(&n.to_le_bytes()); } let report = StlReport { triangles: count, degenerate, lines: mesh.lines, fanned: mesh.fanned }; - Ok((out, report)) + Ok((file, report)) } /// The (unnormalised) normal of a triangle, counter-clockwise from the side it faces. @@ -1883,6 +1896,16 @@ pub fn item_bytes(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec /// Builds an item and returns construction-loss notes for publication only after delivery. 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) +} + +/// [`item_output`] for the file `out` describes: a downloaded one is stopped as it passes its room. +fn item_output_within( + s: &mut Session, + kind: &str, + p: &Value, + out: Output<'_>, +) -> Result<(String, Vec, rustgis_data::loss::Notes), String> { let mut construction_notes: rustgis_data::loss::Notes = (match kind { "map" => { let m = saved_map(s, p)?; @@ -1908,7 +1931,7 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve crate::project::ensure_map_imports_complete(map)?; let map = embedded_map(map, &mut MAX_EMBED.clone()); let name = map.name.clone(); - (name, durable_bytes_with(s, map, crate::project::map_file_bytes)?) + (name, durable_bytes_with(s, map, |map| crate::project::map_file_within(map, out))?) } "layer" => { let id = s.layer_id(p)?; @@ -1918,19 +1941,19 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve } let layer = embed_layer(l, &mut MAX_EMBED.clone()); let name = layer.name.clone(); - (name, durable_bytes_with(s, layer, crate::project::layer_file_bytes)?) + (name, durable_bytes_with(s, layer, |layer| crate::project::layer_file_within(layer, out))?) } "styles" => { if s.project.styles.is_empty() { return Err("the project has no styles; make one with New Style".into()); } - ("styles".to_string(), to_json(&s.project.styles)?) + ("styles".to_string(), out.json(&s.project.styles)?) } "ramps" => { if s.project.ramps.is_empty() { return Err("the project has no custom colour ramps; add some with Add Color Ramp File".into()); } - ("ramps".to_string(), to_json(&s.project.ramps)?) + ("ramps".to_string(), out.json(&s.project.ramps)?) } "template" => { s.project.ensure_imports_complete()?; @@ -1939,7 +1962,7 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve t.name = super::within("name", "a template's name", n, 200)?; } let name = t.name.clone(); - let bytes = durable_bytes(s, t)?; + let bytes = durable_bytes_with(s, t, |t| out.json(t))?; if source_references > 0 { s.notify(format!("{source_references} data source reference(s) left out of the template, which keeps no features"), false); } @@ -1954,7 +1977,7 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve } (name, bytes) } - "projectPackage" => (s.project.name.clone(), package_project(s, &mut construction_notes)?), + "projectPackage" => (s.project.name.clone(), package_project(s, &mut construction_notes, out)?), "fieldPackage" => { let (name, bytes, notes) = super::field::package_output(s, p)?; construction_notes.extend(notes); @@ -1962,59 +1985,59 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve } "mapPackage" | "mobilePackage" => { let tol = f(p, "tolerance").unwrap_or(0.001).clamp(0.0, 1.0); - (s.map().name.clone(), package_map(s, kind == "mobilePackage", tol, &mut construction_notes)?) + (s.map().name.clone(), package_map(s, kind == "mobilePackage", tol, &mut construction_notes, out)?) } - "gpPackage" => ("results".to_string(), package_gp(s)?), + "gpPackage" => ("results".to_string(), package_gp(s, out)?), "bookmarks" => (format!("{} bookmarks", s.map().name), super::navigate::bookmarks_file(s.map())?), "task" => { let t = task_mut(s, p)?; let name = t.name.clone(); - let (bytes, report) = crate::durable::output(t, None, task_json)?; + let (bytes, report) = crate::durable::output(t, None, |t| task_json(t, out))?; crate::durable::notify(s, &report); (name, bytes) } "obj" => { let id = s.layer_id(p)?; let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); - let (text, notes) = obj_text(s, p)?; + let (bytes, notes) = obj_text(s, p, out)?; construction_notes = notes.into(); - (name, text.into_bytes()) + (name, bytes) } "stl" => { let id = s.layer_id(p)?; let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); - let (bytes, _, notes) = stl_bytes(s, p)?; + let (bytes, _, notes) = stl_bytes(s, p, out)?; construction_notes = notes.into(); (name, bytes) } "report" | "reportTemplate" => { let i = super::report::index(s, p)?; let name = s.project.reports.get(i).map(|r| r.name.clone()).unwrap_or_default(); - (name, super::report::report_file(s, i, kind == "reportTemplate")?) + (name, super::report::report_within(s, i, kind == "reportTemplate", out)?) } "presentation" => { let i = super::presentation::index(s, p)?; let name = s.project.presentations.get(i).map(|r| r.name.clone()).unwrap_or_default(); - (name, super::presentation::presentation_file(s, i)?) + (name, super::presentation::presentation_within(s, i, out)?) } "notebook" | "jupyter" => { let i = super::notebook::index(s, p)?; let name = s.project.notebooks.get(i).map(|r| r.name.clone()).unwrap_or_default(); - (name, super::notebook::notebook_file(s, i, kind == "jupyter")?) + (name, super::notebook::notebook_within(s, i, kind == "jupyter", out)?) } "dlPackage" => { let name = match ps(p, "model") { Some(n) => n.to_string(), None => s.project.dl_models.last().map(|m| m.name.clone()).ok_or("train a model first")?, }; - (name.clone(), super::deeplearning::package(s, &json!({"model": name}))?) + (name.clone(), super::deeplearning::package_within(s, &json!({"model": name}), out)?) } "hostedImagery" => { let name = ps(p, "layer").unwrap_or("tiles").to_string(); - (format!("{name}_tiles"), super::deeplearning::hosted_bytes(s, p)?.0) + (format!("{name}_tiles"), super::deeplearning::hosted_within(s, p, out)?.0) } k if super::sharing::KINDS.iter().any(|x| x.0 == k) => { - let (name, bytes, _, notes) = super::sharing::share_output(s, k, p)?; + let (name, bytes, _, notes) = super::sharing::share_output(s, k, p, out)?; construction_notes = notes.into(); super::sharing::note_label_classes(s, k, p); super::sharing::note_export(s, k, p, &name); @@ -2026,22 +2049,13 @@ pub fn item_output(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Ve Ok((format!("{}.{ext}", safe(&name)), bytes, construction_notes)) } -/// Writes an item to `path`. -pub(crate) fn save_item(s: &mut Session, kind: &str, p: &Value) -> CmdResult { - let written = s.notice_mark(); - let path = ps(p, "path").ok_or("path is required")?.to_string(); - let (_, bytes, notes) = item_output(s, kind, p)?; - rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; - for note in notes { - s.say(note); - } - s.retain_written_notices(written); - Ok(json!({"path": path, "bytes": bytes.len()})) -} - -/// Consumes the existing item draft, emitting losses after serialization has completed. -fn durable_bytes(s: &mut Session, value: T) -> Result, String> { - durable_bytes_with(s, value, to_json) +/// Writes an item to `path`, or downloads it in the browser, as `command`. +pub(crate) fn save_item(s: &mut Session, command: &str, kind: &str, p: &Value) -> CmdResult { + super::exports::file_command(s, command, p, |s, out| { + let (_, bytes, notes) = item_output_within(s, kind, p, out)?; + let answer = json!({"path": out.path, "bytes": bytes.len()}); + Ok(super::exports::Made { notes, ..super::exports::Made::new(bytes, answer) }) + }) } /// Serializes an item through its document writer, after the same durable-field transaction. diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 6d7b985a41..552c8c8074 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -403,11 +403,10 @@ pub fn commands() -> Vec { .view() .params(r#"{"layout"?, "path": "*.png|*.pdf|*.svg" (PNG/SVG: current page; SVG: each element a group of its own; text and shapes as SVG, map frames and surrounds as vectors, rasters and tiles in them as pictures at dpi), "dpi"?: 72..600, "allPages"?: bool (PDF only; default true: every map series page, up to 500; false: the current page), "georeference"?: bool (PDF only; default true: map frames carry their coordinates, a GeoPDF; false: none), "pdf"?: {"layers"?: bool (default true: each element, and in a map frame each layer and its labels, a PDF layer that vector editors open as a layer; false: none), "text"?: "fonts" (default: text in its faces, embedded as subsets, editable in a vector editor; a face that can't be is set in outlines, and said)|"outlines" (glyphs as outlines, as print shops ask)}}"#), C::new("layout.save", "Save Layout File", "Publish › Save As", |s, p| { - let path = ps(p, "path").ok_or("path is required")?; - let l = active(s, p)?.clone(); - let bytes = crate::project::layout_file_bytes(&l)?; - rustgis_data::io::write_atomic(Path::new(path), &bytes).map_err(|e| format!("{path}: {e}"))?; - Ok(json!({"path": path})) + super::exports::file_command(s, "layout.save", p, |s, out| { + let l = active(s, p)?.clone(); + Ok(super::exports::Made::new(crate::project::layout_file_within(&l, out)?, json!({"path": out.path}))) + }) }).inputs(object_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"layout"?, "path": "*.rgislayout"}"#), diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index b9a8191e73..d2555583fd 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -165,6 +165,9 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu Some(Value::String(path)) if path.trim().to_ascii_lowercase().ends_with(".png") => Some(path.trim().to_string()), Some(_) => return Err("coverage is the path of a .png file to write the coverage grid to".into()), }; + if let Some(path) = coverage_path.as_deref().filter(|_| s.downloads_files()) { + return Err(format!("{path}: the web app can't write the coverage image to a path; leave out coverage, or use the desktop app")); + } // No orientation asked: the one the area's map comes out larger on, from its extents east to // west and north to south on the map's projection and the room the style leaves the map. let profile = match &auto { diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 2b659c7dda..f5d94d7135 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -179,7 +179,7 @@ pub fn commands() -> Vec { Ok(Value::Null) }).inputs(bookmark_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name": string, "to": index (0: first; past the end: last), "map"?: name}"#), - C::new("bookmark.save", "Export Bookmarks", "Home › Navigate › Bookmarks", |s, p| super::items::save_item(s, "bookmarks", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("bookmark.save", "Export Bookmarks", "Home › Navigate › Bookmarks", |s, p| super::items::save_item(s, "bookmark.save", "bookmarks", p)).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.rgisbookmarks"}"#), C::new("bookmark.import", "Import Bookmarks", "Home › Navigate › Bookmarks", import_bookmarks).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) diff --git a/crates/engine/src/cmd/notebook.rs b/crates/engine/src/cmd/notebook.rs index 8e17fd6e34..26770be671 100644 --- a/crates/engine/src/cmd/notebook.rs +++ b/crates/engine/src/cmd/notebook.rs @@ -235,11 +235,11 @@ pub fn commands() -> Vec { .when(need_notebook) .params(r#"{"notebook"?, "cell"?: index (default: every command cell, stopping at an error)}"#), C::new("notebook.save", "Save Notebook", "Notebook", |s, p| { - let path = ps(p, "path").ok_or("path is required")?; - let i = index(s, p)?; - let bytes = notebook_file(s, i, path.to_ascii_lowercase().ends_with(".ipynb"))?; - rustgis_data::io::write_atomic(Path::new(path), &bytes).map_err(|e| format!("{path}: {e}"))?; - Ok(json!({"path": path})) + super::exports::file_command(s, "notebook.save", p, |s, out| { + let i = index(s, p)?; + let bytes = notebook_within(s, i, out.path.to_ascii_lowercase().ends_with(".ipynb"), out)?; + Ok(super::exports::Made::new(bytes, json!({"path": out.path}))) + }) }) .roles(&[]) .effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) @@ -624,10 +624,15 @@ fn jupyter_file(nb: &Notebook) -> Value { /// The notebook as a RustGIS notebook or (nbformat 4) Jupyter notebook. pub fn notebook_file(s: &mut Session, i: usize, jupyter: bool) -> Result, String> { + notebook_within(s, i, jupyter, super::exports::Output::UNLIMITED) +} + +/// [`notebook_file`] for the file `out` describes. +pub(super) fn notebook_within(s: &mut Session, i: usize, jupyter: bool, out: super::exports::Output<'_>) -> Result, String> { let nb = s.project.notebooks.get_mut(i).ok_or("no notebook")?; let (bytes, report) = crate::durable::output(nb, None, |nb| { let v = if jupyter { jupyter_file(nb) } else { serde_json::to_value(nb).map_err(|e| e.to_string())? }; - serde_json::to_vec_pretty(&v).map_err(|e| e.to_string()) + out.json_pretty(&v) })?; crate::durable::notify(s, &report); Ok(bytes) diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index 260ca9d761..3abd2c6c2f 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -1,8 +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 std::path::Path; - use base64::Engine; use rustgis_geom::Coord; use rustgis_map::Rgba; @@ -167,36 +165,33 @@ pub fn commands() -> Vec { .when(need_presentation) .params(r#"{"presentation"?, "page": index}"#), C::new("presentation.save", "Presentation File", "Publish › Save As", |s, p| { - let written = s.notice_mark(); - let path = ps(p, "path").ok_or("path is required")?; - let i = index(s, p)?; - let bytes = presentation_file(s, i)?; - rustgis_data::io::write_atomic(Path::new(path), &bytes).map_err(|e| format!("{path}: {e}"))?; - s.retain_written_notices(written); - Ok(json!({"path": path})) + super::exports::file_command(s, "presentation.save", p, |s, out| { + let i = index(s, p)?; + Ok(super::exports::Made::new(presentation_within(s, i, out)?, json!({"path": out.path}))) + }) }).inputs(object_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_presentation) .params(r#"{"presentation"?, "path": "*.rgispres"}"#), C::new("presentation.export", "Export Presentation", "Publish › Output", |s, p| { - let written = s.notice_mark(); - let path = ps(p, "path").ok_or("path is required")?.to_string(); - let i = index(s, p)?; - let dpi = f(p, "dpi").unwrap_or(120.0).clamp(48.0, 300.0); - let lower = path.to_ascii_lowercase(); - let format = if lower.ends_with(".html") || lower.ends_with(".htm") { - "html" - } else if lower.ends_with(".png") { - "png" - } else if lower.ends_with(".pdf") { - "pdf" - } else { - return Err("export to a .pdf, .html or .png file".into()); - }; - let (bytes, pages) = export_bytes(s, i, format, dpi)?; - rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; - s.retain_written_notices(written); - Ok(json!({"path": path, "pages": pages, "bytes": bytes.len()})) + super::exports::file_command(s, "presentation.export", p, |s, out| { + let path = out.path; + let i = index(s, p)?; + let dpi = f(p, "dpi").unwrap_or(120.0).clamp(48.0, 300.0); + let lower = path.to_ascii_lowercase(); + let format = if lower.ends_with(".html") || lower.ends_with(".htm") { + "html" + } else if lower.ends_with(".png") { + "png" + } else if lower.ends_with(".pdf") { + "pdf" + } else { + return Err("export to a .pdf, .html or .png file".into()); + }; + let (bytes, pages) = export_within(s, i, format, dpi, out)?; + let answer = json!({"path": path, "pages": pages, "bytes": bytes.len()}); + Ok(super::exports::Made::new(bytes, answer)) + }) }).inputs(export_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_presentation) @@ -358,8 +353,13 @@ fn say_title_statistics(s: &mut Session, i: usize, k: usize) { /// A presentation file. pub fn presentation_file(s: &mut Session, i: usize) -> Result, String> { + presentation_within(s, i, super::exports::Output::UNLIMITED) +} + +/// [`presentation_file`] for the file `out` describes. +pub(super) fn presentation_within(s: &mut Session, i: usize, out: super::exports::Output<'_>) -> Result, String> { let pres = s.project.presentations.get_mut(i).ok_or("no presentation")?; - let (bytes, report) = crate::durable::output(pres, None, |p| serde_json::to_vec_pretty(p).map_err(|e| e.to_string()))?; + let (bytes, report) = crate::durable::output(pres, None, |p| out.json_pretty(p))?; crate::durable::notify(s, &report); Ok(bytes) } @@ -509,6 +509,12 @@ pub(crate) fn playable(source: &str) -> &str { /// The presentation as a PDF, a self-contained HTML slideshow or a PNG of its first page, and /// the number of pages written. pub fn export_bytes(s: &mut Session, i: usize, format: &str, dpi: f64) -> Result<(Vec, usize), String> { + 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. +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| { p.pages @@ -518,11 +524,20 @@ pub fn export_bytes(s: &mut Session, i: usize, format: &str, dpi: f64) -> Result })) }; let before = revision(s); - let result = super::share::saying_shadows(s, "The presentation", |s| export_bytes_inner(s, i, format, dpi)); - before.finish_revision(revision(s), Some(result), "could not draw the presentation")? + let result = super::share::saying_shadows(s, "The presentation", |s| export_bytes_inner(s, i, format, dpi, out)); + let (bytes, pages) = before.finish_revision(revision(s), Some(result), "could not draw the presentation")??; + // With what a PDF or a slideshow holds around its pages. + out.check(bytes.len())?; + Ok((bytes, pages)) } -fn export_bytes_inner(s: &mut Session, i: usize, format: &str, dpi: f64) -> Result<(Vec, usize), String> { +fn export_bytes_inner( + s: &mut Session, + i: usize, + format: &str, + dpi: f64, + out: super::exports::Output<'_>, +) -> Result<(Vec, usize), String> { // Only the size and name are copied: the pages can hold many megabytes of pictures, so each // is read in place after it's drawn. let (name, width, height, n) = @@ -583,6 +598,8 @@ fn export_bytes_inner(s: &mut Session, i: usize, format: &str, dpi: f64) -> Resu let notes = if page.notes.is_empty() { String::new() } else { format!("", html_escape(&page.notes)) }; slides.push_str(&format!("
{body}{notes}
\n", page.seconds)); } + // Where the file is downloaded, what it holds so far is held to the room it has too. + out.check(if format == "pdf" { held } else { slides.len() })?; if held > BUDGET { return Err(format!("the export passed {} MB at page {}; export at a lower dpi", BUDGET >> 20, k + 1)); } diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index f48ade0fa4..f5e6625576 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -122,11 +122,21 @@ fn export_log(s: &mut Session, p: &Value) -> CmdResult { // Written entry by entry, so a long log isn't held as text first; a failure part way leaves // an existing file as it was. let n = s.log.len(); - rustgis_data::io::write_atomic_with(&path, |w| s.log.write(w, format == "csv")).map_err(|e| format!("{}: {e}", path.display()))?; // Entries dropped past the log's limits aren't in the file: said. let dropped = s.log.dropped_said().map(|d| format!("; not in it: {d}")).unwrap_or_default(); - s.notify_written(format!("Exported the session log ({n} entries) to {}{dropped}", path.display())); - Ok(json!({"path": path.display().to_string(), "entries": n, "format": format})) + let said = |path: &str| format!("Exported the session log ({n} entries) to {path}{dropped}"); + let answer = |path: &str| json!({"path": path, "entries": n, "format": format}); + if s.downloads_files() { + return super::exports::download_command(s, "project.exportLog", p, |s, out| { + let bytes = out.file(|w| s.log.write(w, format == "csv").map_err(|e| format!("{}: {e}", out.path)))?; + let path = out.path; + Ok(super::exports::Made { done: Some(said(path)), ..super::exports::Made::new(bytes, answer(path)) }) + }); + } + rustgis_data::io::write_atomic_with(&path, |w| s.log.write(w, format == "csv")).map_err(|e| format!("{}: {e}", path.display()))?; + let path = path.display().to_string(); + s.notify_written(said(&path)); + Ok(answer(&path)) } /// `project.clearLog`: empties the log, which then holds this command's own entry, so a cleared @@ -851,19 +861,8 @@ fn open_text(s: &mut Session, p: &Value) -> CmdResult { /// never goes over a data file, a package or any other kind of file, including when the /// project was opened from a file with another extension. fn write(s: &mut Session, path: PathBuf) -> CmdResult { - let path = if path.extension().is_none() { path.with_extension(crate::project::EXTENSION) } else { path }; + let path = project_path(path)?; let destination = std::path::absolute(&path).map_err(|error| format!("{}: {error}", path.display()))?; - if !crate::project::is_project_file(&path.to_string_lossy()) { - let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - return Err(if ext == crate::project::PACKAGE_EXTENSION { - "a project saves to a .rgis file; Package Project (project.package) writes a .rgispkg package".into() - } else if ext.is_empty() || ext == crate::project::EXTENSION { - // `foo.` and `a.rgis.` end in a bare dot; `atlas.rgis/` names a folder. - "a project saves to a .rgis file".into() - } else { - format!("a project saves to a .rgis file, not a .{ext} one") - }); - } let construction_notes = s.construction_output_notes()?; let report = s.project.save(&destination)?; let stripped = report.layer_addresses(); @@ -880,6 +879,72 @@ fn write(s: &mut Session, path: PathBuf) -> CmdResult { Ok(json!({"path": path.display().to_string(), "stripped": stripped})) } +/// `path` as the project file a save writes (`.rgis` added when it has no extension), refused +/// when it names another kind of file. +fn project_path(path: PathBuf) -> Result { + let path = if path.extension().is_none() { path.with_extension(crate::project::EXTENSION) } else { path }; + if !crate::project::is_project_file(&path.to_string_lossy()) { + let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + return Err(if ext == crate::project::PACKAGE_EXTENSION { + "a project saves to a .rgis file; Package Project (project.package) writes a .rgispkg package".into() + } else if ext.is_empty() || ext == crate::project::EXTENSION { + // `foo.` and `a.rgis.` end in a bare dot; `atlas.rgis/` names a folder. + "a project saves to a .rgis file".into() + } else { + format!("a project saves to a .rgis file, not a .{ext} one") + }); + } + Ok(path) +} + +/// [`write`] where files are downloaded: the project downloads as the file `path` names, and with +/// `rename` (Save As) takes that file's name once the download is taken, unless it was renamed +/// meanwhile. It isn't marked saved, and no file becomes the project's: the browser doesn't say +/// whether it saved the download. +fn download(s: &mut Session, command: &str, path: PathBuf, rename: bool) -> CmdResult { + let path = project_path(path)?.to_string_lossy().into_owned(); + super::exports::download_command(s, command, &json!({"path": path}), |s, out| { + let file = out.path; + let construction_notes = s.construction_output_notes()?; + let old = s.project.name.clone(); + let stem = std::path::Path::new(file).file_stem().and_then(|x| x.to_str()).map(str::trim).filter(|x| !x.is_empty()); + let name = match stem { + Some(stem) if rename => stem.chars().take(200).collect(), + _ => old.clone(), + }; + // The file holds the name Save As gives the project; the project takes it with the download. + s.project.name.clone_from(&name); + let saved = s.project.saved_with(None, |p| { + let max = crate::project::max_bytes(); + let most = usize::try_from(max).unwrap_or(usize::MAX); + let too_large = || crate::project::too_large_to_save(max); + let text = out.file_up_to(most, too_large, |w| serde_json::to_writer(w, p).map_err(|e| e.to_string()))?; + String::from_utf8(text).map_err(|e| e.to_string()) + }); + s.project.name.clone_from(&old); + let (text, report) = saved?; + if let Some(n) = stem.map(|stem| stem.chars().count()).filter(|n| rename && *n > 200) { + s.notify( + format!("Save Project As: the file's name is {n} characters, so the project's name is its first 200 characters"), + false, + ); + } + crate::durable::notify(s, &report); + for note in construction_notes { + s.say(note); + } + let answer = json!({"path": file, "stripped": report.layer_addresses()}); + let done = format!("Download offered: {file}. The browser doesn't say whether it saved the file."); + let taken: Box = Box::new(move |s: &mut Session| { + if name != old && s.project.name == old { + s.project.name = name; + s.mark_unsaved(); + } + }); + Ok(super::exports::Made { done: Some(done), taken: Some(taken), ..super::exports::Made::new(text.into_bytes(), answer) }) + }) +} + /// Names the project after its file, as Save As does, so a renamed or copied file opens under /// its own name. A file name over 200 characters is cut to 200, and that is said. fn name_from_file(s: &mut Session, file: &std::path::Path) { @@ -892,14 +957,21 @@ fn name_from_file(s: &mut Session, file: &std::path::Path) { } } +/// Saves the project to the path given, else to its own file. fn save(s: &mut Session, p: &Value) -> CmdResult { let path = save_path(s, p)?; + if s.downloads_files() { + return download(s, "project.save", path, false); + } write(s, path) } /// Saves with the destination's name, restoring the current name if writing fails. fn save_as(s: &mut Session, p: &Value) -> CmdResult { let path = PathBuf::from(super::ps(p, "path").ok_or("path is required")?); + if s.downloads_files() { + return download(s, "project.saveAs", path, true); + } let previous_name = path.file_stem().and_then(|x| x.to_str()).map(|stem| std::mem::replace(&mut s.project.name, stem.to_string())); let result = write(s, path); // Only undoable commands get a Session snapshot; restore this view command's name by hand. diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 2a27412a0b..2cfc5e262d 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -636,19 +636,25 @@ fn relationships(input: &impl super::InputSource) -> impl Iterator CmdResult { - let path = ps(p, "path").ok_or("path is required")?; - let i = index(s, p)?; - let bytes = report_file(s, i, template)?; - rustgis_data::io::write_atomic(Path::new(path), &bytes).map_err(|e| format!("{path}: {e}"))?; - Ok(json!({"path": path})) + let command = if template { "report.saveTemplate" } else { "report.save" }; + super::exports::file_command(s, command, p, |s, out| { + let i = index(s, p)?; + Ok(super::exports::Made::new(report_within(s, i, template, out)?, json!({"path": out.path}))) + }) } /// A report file (the report as it is) or template (its design without the data source). pub fn report_file(s: &Session, i: usize, template: bool) -> Result, String> { + report_within(s, i, template, super::exports::Output::UNLIMITED) +} + +/// [`report_file`] for the file `out` describes. +pub(super) fn report_within(s: &Session, i: usize, template: bool, out: super::exports::Output<'_>) -> Result, String> { let r = s.project.reports.get(i).ok_or("no report")?; let r = if template { r.template() } else { r.clone() }; - serde_json::to_vec_pretty(&r).map_err(|e| e.to_string()) + out.json_pretty(&r) } fn open(s: &mut Session, p: &Value) -> CmdResult { diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index b7305e2a8e..c0651320f7 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -16,6 +16,7 @@ use rustgis_map::{Layer, Map, Rgba}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use super::exports::{Output, Parts}; use super::ps; use crate::{CmdResult, CommandSpec as C, Session}; @@ -206,7 +207,13 @@ pub fn commands() -> Vec { /// The shared item bytes of a kind: its name, bytes and source. Rasters drawn into it without /// their cast shadows are said (see [`super::share::saying_shadows`]). pub fn share_bytes(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec, String), String> { - let (name, bytes, source, notes) = share_output(s, kind, p)?; + share_bytes_within(s, kind, p, Output::UNLIMITED) +} + +/// [`share_bytes`] for the file `out` describes: a downloaded one is stopped as it passes its +/// room. +fn share_bytes_within(s: &mut Session, kind: &str, p: &Value, out: Output<'_>) -> Result<(String, Vec, String), String> { + let (name, bytes, source, notes) = share_output(s, kind, p, out)?; for note in notes { s.say(note); } @@ -218,6 +225,7 @@ pub(crate) fn share_output( s: &mut Session, kind: &str, p: &Value, + out: Output<'_>, ) -> Result<(String, Vec, String, Vec), String> { let what = match kind { "webMap" => "The web map", @@ -235,7 +243,7 @@ pub(crate) fn share_output( } _ => Vec::new(), }; - let (name, bytes, source) = super::share::saying_shadows(s, what, |s| share_bytes_inner(s, kind, p))?; + let (name, bytes, source) = super::share::saying_shadows(s, what, |s| share_bytes_inner(s, kind, p, out))?; Ok((name, bytes, source, notes)) } @@ -266,45 +274,49 @@ impl Unplaced { } /// Build the saved payload for each share kind; web tools carry capabilities of their steps. -fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value) -> Result<(String, Vec, String), String> { +fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value, out: Output<'_>) -> Result<(String, Vec, String), String> { + // The features read whole so far, which a download's reads are held to together. + let mut held = 0; match kind { "webMap" => { let mut m = map_of(s, p)?; - m.layers.iter_mut().filter(|l| shared_layer("webMap", l)).try_for_each(|l| load_whole(s, l))?; + m.layers.iter_mut().filter(|l| shared_layer("webMap", l)).try_for_each(|l| load_whole(s, l, out, &mut held))?; let mut unplaced = Unplaced::default(); - let html = web_map_html(&m, &m.name, &mut unplaced)?; + let html = out.file(|w| write_web_map(w, &m, &m.name, &mut unplaced))?; unplaced.say(s, "The web map"); - Ok((m.name.clone(), html.into_bytes(), m.name)) + Ok((m.name.clone(), html, m.name)) } "webLayer" => { let mut l = layer_of(s, p)?; - load_whole(s, &mut l)?; + load_whole(s, &mut l, out, &mut held)?; let mut unplaced = Unplaced::default(); - let zip = web_layer_zip(s, &l, &mut unplaced)?; + let zip = web_layer_zip(s, &l, &mut unplaced, out)?; unplaced.say(s, "The web layer"); Ok((l.name.clone(), zip, l.name.clone())) } "webStyle" => { let l = layer_of(s, p)?; let style = web_style(&l); - Ok((l.name.clone(), serde_json::to_vec_pretty(&style).map_err(|e| e.to_string())?, l.name.clone())) + Ok((l.name.clone(), out.json_pretty(&style)?, l.name.clone())) } "locator" => { let l = layer_of(s, p)?; let fields: Option> = p.get("fields").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()); let mut unplaced = Unplaced::default(); - let loc = locator(&l, fields.as_deref(), &mut unplaced)?; + let loc = locator(&l, fields.as_deref(), &mut unplaced, out)?; unplaced.say(s, "The locator"); - Ok((l.name.clone(), serde_json::to_vec(&loc).map_err(|e| e.to_string())?, l.name.clone())) + Ok((l.name.clone(), out.json(&loc)?, l.name.clone())) } "geodataService" => { let mut m = map_of(s, p)?; - m.layers.iter_mut().filter(|l| shared_layer("geodataService", l)).try_for_each(|l| load_whole(s, l))?; + m.layers.iter_mut().filter(|l| shared_layer("geodataService", l)).try_for_each(|l| load_whole(s, l, out, &mut held))?; let mut layers: Vec<&Dataset> = m.layers.iter().filter(|l| shared_layer("geodataService", l)).map(|l| &l.dataset).collect(); layers.extend(s.project.tables.iter().map(|t| &t.dataset)); let mut unplaced = Unplaced::default(); - let zip = ogc_zip(&m.name, &layers, &[], &mut unplaced)?; + let mut parts = out.parts(); + ogc_entries(&mut parts, &m.name, &layers, &mut unplaced)?; + let zip = parts.zip()?; let name = m.name.clone(); drop(layers); unplaced.say(s, "The geodata service"); @@ -314,24 +326,21 @@ fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value) -> Result<(String, let i = shared_model(s, p)?; let m = s.project.models.get_mut(i).ok_or("make a model first (ModelBuilder)")?; let name = m.name.clone(); - let (bytes, report) = crate::durable::output(m, None, |m| { - let tool = crate::model::to_web_tool_file(&m.name, &m.steps); - serde_json::to_vec_pretty(&tool).map_err(|e| e.to_string()) - })?; + let (bytes, report) = crate::durable::output(m, None, |m| out.json_pretty(&crate::model::to_web_tool_file(&m.name, &m.steps)))?; crate::durable::notify(s, &report); Ok((name.clone(), bytes, name)) } "webScene" => { let mut m = map_of(s, p)?; - m.layers.iter_mut().filter(|l| shared_layer("webScene", l)).try_for_each(|l| load_whole(s, l))?; - let scene = gltf(&m, s.view_size)?; + m.layers.iter_mut().filter(|l| shared_layer("webScene", l)).try_for_each(|l| load_whole(s, l, out, &mut held))?; + let scene = gltf(&m, s.view_size, out)?; for note in scene.notes() { s.say(note); } Ok((m.name.clone(), scene.bytes, m.name.clone())) } "linkChart" => { - let (item, note) = link_chart_item(s, p)?; + let (item, note) = link_chart_item(s, p, out)?; if let Some(note) = note { s.notify(note, false); } @@ -341,16 +350,21 @@ fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value) -> Result<(String, } } -/// A link chart's shared item, and what its limits leave out when they do (#1947), for whoever -/// shares it to say: `share` says it last, after "Shared …", so the status bar keeps it. -fn link_chart_item(s: &Session, p: &Value) -> Result<((String, Vec, String), Option), String> { +/// A link chart's shared item for the file `out` describes (a downloaded one is stopped as it +/// passes its room), and what its limits leave out when they do (#1947), for whoever shares it to +/// say: `share` says it last, after "Shared …", so the status bar keeps it. +fn link_chart_item(s: &Session, p: &Value, out: Output<'_>) -> Result<((String, Vec, String), Option), String> { let rel = ps(p, "relationship").map(str::to_string); - let (html, left) = link_chart(s, rel.as_deref())?; + let mut left = None; + let html = out.file(|page| { + left = link_chart(s, rel.as_deref(), page)?; + Ok(()) + })?; // Every relationship is recorded with an empty source (a relationship may be called // "Relationships"). let name = rel.clone().unwrap_or_else(|| "Relationships".into()); let note = left.map(|left| format!("{name}: {left}")); - Ok(((name, html.into_bytes(), rel.unwrap_or_default()), note)) + Ok(((name, html, rel.unwrap_or_default()), note)) } /// A map to share, its layer groups folded into their layers (the shared formats have none). @@ -362,9 +376,12 @@ 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. -fn load_whole(s: &mut Session, l: &mut Layer) -> Result<(), String> { +/// For a download, 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) = l.load_all_counted()?; + let (ds, unread) = if out.downloads() { 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); } @@ -389,6 +406,10 @@ fn target(input: &impl super::InputSource, p: &Value, name: &str, ext: &str) -> if let Some(path) = ps(p, "path") { return Ok(path.to_string()); } + // A data store is a folder, which the browser can't write to. + if s.downloads_files() { + return Err("the web app has no data stores; pass a path, and the file downloads under the name it ends in".into()); + } let store = match ps(p, "store") { Some(n) => s.project.data_stores.iter().find(|d| d.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no data store '{n}'"))?, None => s.project.data_stores.first().ok_or("pass a path, or register a data store (Publish › Manage › Data Stores)")?, @@ -397,9 +418,15 @@ fn target(input: &impl super::InputSource, p: &Value, name: &str, ext: &str) -> Ok(PathBuf::from(&store.path).join(format!("{}.{ext}", safe(name))).display().to_string()) } +/// Writes a share of `kind` to its path or data store and records the item the Manage commands +/// update; where files are downloaded, downloads it instead ([`download_share`]). fn share(s: &mut Session, p: &Value, kind: &str) -> CmdResult { + if s.downloads_files() { + return download_share(s, p, kind); + } let written = s.notice_mark(); - let ((name, bytes, source), chart_note) = if kind == "linkChart" { link_chart_item(s, p)? } else { (share_bytes(s, kind, p)?, None) }; + let ((name, bytes, source), chart_note) = + if kind == "linkChart" { link_chart_item(s, p, Output::UNLIMITED)? } else { (share_bytes(s, kind, p)?, None) }; let ext = KINDS.iter().find(|k| k.0 == kind).map_or("bin", |k| k.1); let path = target(s, p, &name, ext)?; // A share of another kind (or an uploaded file) at that path isn't replaced. @@ -447,12 +474,46 @@ fn share(s: &mut Session, p: &Value, kind: &str) -> CmdResult { Ok(json!({"item": id, "path": path, "bytes": bytes.len()})) } +/// [`share`] where files are downloaded. No shared item is recorded: the Manage commands +/// update an item's file in place, and a download can't be. +fn download_share(s: &mut Session, p: &Value, kind: &str) -> CmdResult { + // Refused without a path before anything is made. + target(s, p, "", "")?; + super::exports::download_command(s, &format!("share.{kind}"), p, |s, out| { + let path = out.path; + let ((name, bytes, _), chart_note) = + if kind == "linkChart" { link_chart_item(s, p, out)? } else { (share_bytes_within(s, kind, p, out)?, None) }; + note_label_classes(s, kind, p); + note_export(s, kind, p, path); + if let Some(note) = chart_note { + s.notify(note, false); + } + let answer = json!({"path": path, "bytes": bytes.len()}); + let done = format!( + "Shared {name} as the download {path}; it isn't listed under Jobs, as the web app can't update a downloaded file (share it again to replace it)" + ); + Ok(super::exports::Made { done: Some(done), ..super::exports::Made::new(bytes, answer) }) + }) +} + /// Re-shares an item in place, from its source or a new one. fn update_item(s: &mut Session, p: &Value, kind: &str, new_source: Option<&str>) -> CmdResult { + refuse_update(s, kind)?; let q = update_params(s, p, kind, new_source)?; share(s, &q, kind) } +/// Refuses, where files are downloaded, updating a shared item of `kind`: its file stays where +/// it was written, which the browser can't write to. +fn refuse_update(s: &Session, kind: &str) -> Result<(), String> { + if !s.downloads_files() { + return Ok(()); + } + Err(format!("the web app can't update a shared file in place; run share.{kind} with a path, which downloads it again")) +} + +/// `share.dataStore`: registers or removes a folder shares are written to, or lists them. +/// Registering is refused where files are downloaded. fn data_store(s: &mut Session, p: &Value) -> CmdResult { if let Some(n) = ps(p, "remove") { let before = s.project.data_stores.len(); @@ -461,6 +522,11 @@ fn data_store(s: &mut Session, p: &Value) -> CmdResult { return Err(format!("no data store '{n}'")); } } else if let Some(path) = ps(p, "path") { + if s.downloads_files() { + return Err(format!( + "{path}: the web app can't write to a folder, so it keeps no data stores; share with a path, and the file downloads under the name it ends in" + )); + } if !Path::new(path).is_dir() { return Err(format!("{path} isn't a folder")); } @@ -483,7 +549,12 @@ fn data_store(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"stores": s.project.data_stores})) } +/// `share.upload`: copies a file into a data store, never over a file there. Refused where files +/// are downloaded. fn upload(s: &mut Session, p: &Value) -> CmdResult { + if s.downloads_files() { + return Err("the web app can't copy files into a folder; upload files to a data store in the desktop app".into()); + } let src = ps(p, "path").ok_or("path is required")?; let file = Path::new(src).file_name().map(|n| n.to_string_lossy().into_owned()).ok_or("path must name a file")?; let store = match ps(p, "store") { @@ -543,6 +614,19 @@ fn script_json(v: &Value) -> String { serde_json::to_string(v).unwrap_or_default().replace(") -> std::io::Result<()> { + page.write_all(b"[")?; + for (i, value) in values.enumerate() { + if i > 0 { + page.write_all(b",")?; + } + page.write_all(script_json(&value).as_bytes())?; + } + page.write_all(b"]") +} + fn css(c: Rgba) -> String { format!("rgba({},{},{},{:.3})", c.r(), c.g(), c.b(), f64::from(c.a()) / 255.0) } @@ -550,10 +634,14 @@ fn css(c: Rgba) -> String { /// A layer's visible features as GeoJSON, each with its drawn style: in longitude/latitude, /// whatever system the layer holds its coordinates in. One with a place that can't be given there /// is left out, counted in `unplaced`. -fn styled_features(l: &Layer, budget: &mut usize, unplaced: &mut Unplaced) -> Result, String> { +fn styled_features( + l: &Layer, + budget: &mut usize, + unplaced: &mut Unplaced, + mut each: impl FnMut(Value) -> Result<(), String>, +) -> Result<(), String> { let rows = l.visible_rows(); let opacity = 1.0 - f64::from(l.transparency.clamp(0.0, 100.0)) / 100.0; - let mut out = Vec::new(); // Its symbol by expression (no map scale: the page zooms on its own). let styler = l.styler(None); let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; @@ -572,23 +660,37 @@ fn styled_features(l: &Layer, budget: &mut usize, unplaced: &mut Unplaced) -> Re let sym = styler.symbol(row); let props: serde_json::Map = l.dataset.fields.iter().enumerate().map(|(i, f)| (f.name.clone(), json!(l.dataset.value(row, i).to_string()))).collect(); - out.push(json!({ + each(json!({ "type": "Feature", "geometry": rustgis_data::io::geometry_to_geojson(&g), "properties": props, "style": {"fill": css(sym.fill), "stroke": css(sym.stroke), "width": sym.stroke_width, "size": sym.size, "opacity": opacity}, - })); + }))?; *budget -= 1; } - Ok(out) + Ok(()) } /// A self-contained web map page: the map's layers (rasters as images) drawn on a canvas in Web -/// Mercator, with pan, zoom, a layer list and pop-ups. No libraries or server. -fn web_map_html(m: &Map, title: &str, unplaced: &mut Unplaced) -> Result { +/// Mercator, with pan, zoom, a layer list and pop-ups. No libraries or server. Its layers are +/// written to `page` as they are made, so a page held to a limit stops there. +fn write_web_map(page: &mut dyn std::io::Write, m: &Map, title: &str, unplaced: &mut Unplaced) -> Result<(), String> { + let failed = |e: std::io::Error| e.to_string(); let mut budget = MAX_FEATURES; let mut pictures = 0usize; - let mut layers = Vec::new(); + let mut separator = ""; + write!( + page, + r#"{title} + +

{title}

"#, - title = html_escape(title), - layers = script_json(&Value::Array(layers)), lon = if c.x.is_finite() { c.x } else { 0.0 }, lat = if c.y.is_finite() { c.y } else { 0.0 }, res = if m.camera.res.is_finite() && m.camera.res > 0.0 { m.camera.res } else { 40_000.0 }, bg = bg - )) + ) + .map_err(failed) } /// Says, when a shared web map, web layer or OGC API Features item has layers that lost Z or M @@ -886,9 +991,8 @@ fn zoom_range(l: &Layer) -> (Option, Option) { } /// Static OGC API – Features collections (landing page, conformance, collections and their -/// items), plus extra files. -fn ogc_zip(title: &str, layers: &[&Dataset], extra: &[(String, Vec)], unplaced: &mut Unplaced) -> Result, String> { - let mut entries: Vec<(String, Vec)> = Vec::new(); +/// items), added to the archive's `parts`. +fn ogc_entries(parts: &mut Parts<'_>, title: &str, layers: &[&Dataset], unplaced: &mut Unplaced) -> Result<(), String> { let mut cols = Vec::new(); let mut used: HashMap = HashMap::new(); let mut taken = std::collections::HashSet::new(); @@ -911,31 +1015,34 @@ fn ogc_zip(title: &str, layers: &[&Dataset], extra: &[(String, Vec)], unplac col["extent"] = json!({"spatial": {"bbox": [[e.min_x, e.min_y, e.max_x, e.max_y]], "crs": "http://www.opengis.net/def/crs/OGC/1.3/CRS84"}}); } - entries.push((format!("collections/{id}.json"), serde_json::to_vec_pretty(&col).map_err(|e| e.to_string())?)); + parts.push(format!("collections/{id}.json"), serde_json::to_vec_pretty(&col).map_err(|e| e.to_string())?)?; // GeoJSON is longitude/latitude, whatever system the layer holds its coordinates in; a // feature with a place that can't be given there is written without its geometry. let (lonlat, lost) = ds.in_lonlat_leaving_out()?; unplaced.add(&ds.name, lost); - let mut fc = rustgis_data::io::to_geojson(&lonlat); - fc["numberReturned"] = json!(ds.features.len()); - entries.push((format!("collections/{id}/items.json"), serde_json::to_vec(&fc).map_err(|e| e.to_string())?)); + parts.make(format!("collections/{id}/items.json"), |w| { + rustgis_data::io::write_geojson_items(&lonlat, w).map_err(|e| e.to_string()) + })?; cols.push(col); } let landing = json!({"title": title, "links": [ {"href": "conformance.json", "rel": "conformance"}, {"href": "collections.json", "rel": "data"}]}); let conformance = json!({"conformsTo": ["http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/core", "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/geojson"]}); - entries.push(("index.json".into(), serde_json::to_vec_pretty(&landing).map_err(|e| e.to_string())?)); - entries.push(("conformance.json".into(), serde_json::to_vec_pretty(&conformance).map_err(|e| e.to_string())?)); - entries.push(("collections.json".into(), serde_json::to_vec_pretty(&json!({"collections": cols})).map_err(|e| e.to_string())?)); - entries.extend(extra.iter().cloned()); - rustgis_data::zip::write(&entries) + parts.push("index.json".into(), serde_json::to_vec_pretty(&landing).map_err(|e| e.to_string())?)?; + parts.push("conformance.json".into(), serde_json::to_vec_pretty(&conformance).map_err(|e| e.to_string())?)?; + parts.push("collections.json".into(), serde_json::to_vec_pretty(&json!({"collections": cols})).map_err(|e| e.to_string())?) } /// A web layer: the layer as an OGC API Features collection, its style, and a viewer page. -fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced) -> Result, String> { - let style = serde_json::to_vec_pretty(&web_style(l)).map_err(|e| e.to_string())?; +fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced, out: Output<'_>) -> Result, String> { + let mut parts = out.parts(); + ogc_entries(&mut parts, &l.name, &[&l.dataset], unplaced)?; + parts.make("style.json".into(), |w| serde_json::to_writer_pretty(w, &web_style(l)).map_err(|e| e.to_string()))?; + let src = safe(&l.name); // The same features as the collection's items, counted there. - let geojson = serde_json::to_vec(&rustgis_data::io::to_geojson(&l.dataset.in_lonlat_leaving_out()?.0)).map_err(|e| e.to_string())?; + parts.make(format!("{src}.geojson"), |w| { + rustgis_data::io::write_geojson(&l.dataset.in_lonlat_leaving_out()?.0, w).map_err(|e| e.to_string()) + })?; let mut m = s.map().clone(); m.layers = vec![l.clone()]; let e = l.extent(); @@ -947,15 +1054,9 @@ fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced) -> Result, } -fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced) -> Result { +fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, out: Output<'_>) -> Result { let ds = &l.dataset; let fis: Vec = match fields { Some(fs) => { @@ -980,6 +1081,8 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced) -> Res } let lonlat = ds.lonlat_conversion()?; let mut entries = Vec::new(); + // The entries' text so far, less than the file they make comes to. + let mut held = 0usize; for (row, ft) in ds.features.iter().enumerate().take(MAX_FEATURES) { let Some(g) = &ft.geometry else { continue }; let e = g.extent(); @@ -1003,7 +1106,10 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced) -> Res v => v.to_string(), }; if !t.trim().is_empty() { - entries.push((t.trim().chars().take(500).collect(), c.x, c.y)); + let entry: String = t.trim().chars().take(500).collect(); + held = held.saturating_add(entry.len()); + out.check(held)?; + entries.push((entry, c.x, c.y)); } } } @@ -1120,7 +1226,11 @@ impl SceneBytes { /// from: its bearing and pitch, as far off as MapLibre's camera would be. Also the number of /// polygon caps that are fans (the triangulator gave up, or fell back to one), and counted /// explanations of features or parts left out. -fn gltf(m: &Map, view: (f64, f64)) -> Result { +fn gltf(m: &Map, view: (f64, f64), out: Output<'_>) -> Result { + // A downloaded scene's geometry is written in base64, a third larger: held to what fits. + let most = MAX_SCENE_BYTES.min(out.most() / 4 * 3); + let too_large = + || if most < MAX_SCENE_BYTES { out.refusal() } else { "the scene would be too large; share fewer features".to_string() }; let c = m.center_lonlat(); let origin = rustgis_geom::lonlat_to_merc(c); let k = c.y.to_radians().cos().abs().max(0.01); @@ -1197,8 +1307,8 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result { budget -= 1; // The geometry built so far, with the buffer already written, stays under the cap // (checked as it grows, so a few huge polygons can't run away first). - if buffer.len() + built > MAX_SCENE_BYTES { - return Err("the scene would be too large; share fewer features".into()); + if buffer.len() + built > most { + return Err(too_large()); } let sym = styler.symbol(row); // A layer without an extrusion stands flat on the ground; the base and the height @@ -1254,8 +1364,8 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result { // checked before it is built, so a fan over a huge ring can't run away. let walls = if h > 0.0 { flat.len() * (4 * 12 + 6 * 4) } else { 0 }; let grown = size(&tri, &lines, &key).saturating_sub(last.map_or(0, |(_, before)| before)); - if buffer.len() + built + grown + cap * 12 + triangles * 12 + walls > MAX_SCENE_BYTES { - return Err("the scene would be too large; share fewer features".into()); + if buffer.len() + built + grown + cap * 12 + triangles * 12 + walls > most { + return Err(too_large()); } // The fallback fan follows the ring, which may run either way: it is wound // counter-clockwise (in x, z) like the triangulator's answer, so it faces up too. @@ -1373,8 +1483,8 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result { meshes.push(json!({"name": l.name, "primitives": primitives})); nodes.push(json!({"name": l.name, "mesh": meshes.len() - 1})); } - if buffer.len() > MAX_SCENE_BYTES { - return Err("the scene would be too large; share fewer features".into()); + if buffer.len() > most { + return Err(too_large()); } } if nodes.is_empty() { @@ -1403,7 +1513,7 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result { "extras": {"origin": [c.x, c.y], "units": "metres east, up and south of origin (longitude, latitude)", "bearing": at.bearing, "pitch": at.pitch}, }); - scene.bytes = serde_json::to_vec(&doc).map_err(|e| e.to_string())?; + scene.bytes = out.json(&doc)?; Ok(scene) } @@ -1434,17 +1544,45 @@ fn viewpoint(m: &Map, at: &rustgis_map::Camera, view: (f64, f64)) -> (Value, Val (camera, node) } +/// A link chart's node: a feature's layer and row, and the relationship it came into the chart +/// by. +type ChartNode<'a> = (&'a Layer, usize, usize); + +/// A feature's node, made while the chart has room for one. `index` holds the nodes by map, layer +/// id and row. +fn chart_node<'a>( + index: &mut HashMap<(usize, u32, usize), usize>, + nodes: &mut Vec>, + mi: usize, + l: &'a Layer, + row: usize, + gi: usize, +) -> Option { + if let Some(&i) = index.get(&(mi, l.id, row)) { + return Some(i); + } + if nodes.len() >= MAX_NODES { + return None; + } + nodes.push((l, row, gi)); + index.insert((mi, l.id, row), nodes.len() - 1); + Some(nodes.len() - 1) +} + /// A link chart: the features joined by the map's relationships, as a node-link diagram (a /// self-contained page with a force layout; drag nodes, hover for names). -/// The page, and what the chart's limits leave out of it when they do: said by whoever shares -/// it, and on the page (#1947). -fn link_chart(s: &Session, rel: Option<&str>) -> Result<(String, Option), String> { +/// The page is written to `page` as it is made, a feature or a link at a time. Gives what the +/// chart's limits leave out of it when they do: said by whoever shares it, and on the page +/// (#1947). +fn link_chart(s: &Session, rel: Option<&str>, page: &mut dyn std::io::Write) -> Result, String> { let rels = link_relationships(s, rel)?; let find = |name: &str| link_layer(s, name).and_then(|(m, l)| s.project.maps.iter().position(|p| std::ptr::eq(p, m)).map(|i| (i, l))); - let mut nodes: Vec = Vec::new(); + // Each node's layer, row and relationship; its name is read as the page is written. + let mut nodes: Vec = Vec::new(); // Nodes by map, layer id and row (same-named layers in different maps stay apart). let mut index: HashMap<(usize, u32, usize), usize> = HashMap::new(); - let mut links: Vec = Vec::new(); + // Each link's two nodes and its relationship's name. + let mut links: Vec<(usize, usize, &str)> = Vec::new(); let label = |l: &Layer, row: usize| -> String { let ds = &l.dataset; let fi = ds @@ -1454,18 +1592,6 @@ fn link_chart(s: &Session, rel: Option<&str>) -> Result<(String, Option) .or_else(|| ds.fields.iter().position(|f| !f.ty.is_numeric())); fi.map(|i| ds.value(row, i).to_string()).unwrap_or_else(|| format!("{} {}", l.name, row + 1)) }; - // A feature's node, made while the chart has room for one. - let node = |index: &mut HashMap<(usize, u32, usize), usize>, nodes: &mut Vec, mi: usize, l: &Layer, row: usize, gi: usize| { - if let Some(&i) = index.get(&(mi, l.id, row)) { - return Some(i); - } - if nodes.len() >= MAX_NODES { - return None; - } - nodes.push(json!({"name": label(l, row), "layer": l.name, "group": gi})); - index.insert((mi, l.id, row), nodes.len() - 1); - Some(nodes.len() - 1) - }; // What the chart would show without its limits, to say what they leave out: each related // feature once, and each relation. let mut related: HashSet<(usize, u32, usize)> = HashSet::new(); @@ -1543,14 +1669,15 @@ fn link_chart(s: &Session, rel: Option<&str>) -> Result<(String, Option) } continue; } - let (Some(from), Some(to)) = - (a.or_else(|| node(&mut index, &mut nodes, om, o, orow, gi)), node(&mut index, &mut nodes, dm, d, drow, gi)) - else { + let (Some(from), Some(to)) = ( + a.or_else(|| chart_node(&mut index, &mut nodes, om, o, orow, gi)), + chart_node(&mut index, &mut nodes, dm, d, drow, gi), + ) else { i += 1; continue; }; a = Some(from); - links.push(json!({"source": from, "target": to, "relationship": r.name})); + links.push((from, to, r.name.as_str())); drawn_here += 1; i += 1; } @@ -1564,7 +1691,7 @@ fn link_chart(s: &Session, rel: Option<&str>) -> Result<(String, Option) let title = rel.unwrap_or("Relationships"); let mut legend = String::new(); let layers: Vec = { - let mut v: Vec = nodes.iter().filter_map(|n| n["layer"].as_str().map(str::to_string)).collect(); + let mut v: Vec = nodes.iter().map(|(l, ..)| l.name.clone()).collect(); v.sort(); v.dedup(); v @@ -1576,12 +1703,26 @@ fn link_chart(s: &Session, rel: Option<&str>) -> Result<(String, Option) if let Some(left) = &left { let _ = write!(legend, "
Shows {}.", html_escape(left)); } - let html = format!( + let failed = |e: std::io::Error| e.to_string(); + write!( + page, r#"{title}
{title}
{legend}
"#, - title = html_escape(title), - legend = legend, - nodes = script_json(&Value::Array(nodes)), - links = script_json(&Value::Array(links)), layers = script_json(&json!(layers)), - ); + ) + .map_err(failed)?; let said = left.map(|left| { format!( "the link chart shows {left}; a link chart takes at most {MAX_NODES} features, {MAX_LINKS} links and {MAX_FEATURE_LINKS} links from one feature in each relationship" ) }); - Ok((html, said)) + Ok(said) } /// Resolves saved/default and literal locator paths without reading their contents. @@ -1685,6 +1823,8 @@ fn update_links_inputs(input: &super::InputContext<'_>, p: &Value) -> Result) -> Result { + // Before the item is looked for, so the browser's refusal is the one said. + refuse_update(&input.input_context(), kind)?; let q = update_params(input, p, kind, new_source)?; let mut inputs = share_kind_inputs(input, &q, kind)?; inputs.state = json!({"source":inputs.state,"effective":q}); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 0042b1c805..95a62b5a95 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1367,24 +1367,31 @@ fn save_model(s: &mut Session, p: &Value) -> CmdResult { /// A model as a `*.model.json` file: written to `path`, or its text returned. fn export_model(s: &mut Session, p: &Value) -> CmdResult { - let written = s.notice_mark(); + if ps(p, "path").is_some() { + return super::exports::file_command(s, "model.export", p, |s, out| { + let (name, text) = model_file(s, p, out)?; + // What the graph passed left out is said once the file is out, and not at all of one + // that couldn't be written. + let (_, left_out) = s.holding_notices(|s| note_passed_graph(s, p)); + let left_out = left_out.into_iter().map(|n| rustgis_data::loss::Note { loss: n.loss(), text: n.text, tally: None }); + let answer = json!({"model": name, "path": out.path}); + Ok(super::exports::Made { notes: left_out.collect(), ..super::exports::Made::new(text, answer) }) + }); + } + let (name, text) = model_file(s, p, super::exports::Output::UNLIMITED)?; + let text = String::from_utf8(text).map_err(|e| e.to_string())?; + let file: String = name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect(); + note_passed_graph(s, p); + Ok(json!({"model": name, "fileName": format!("{file}.model.json"), "text": text})) +} + +/// The model `p` names, and its `*.model.json` file for `out`, with what writing it leaves out +/// said. +fn model_file(s: &mut Session, p: &Value, out: super::exports::Output<'_>) -> Result<(String, Vec), String> { let (name, g, _) = model_graph(s, p)?; - let (text, report) = - crate::durable::output_owned(g, |g| serde_json::to_string_pretty(&crate::model::to_file(&name, g)).map_err(|e| e.to_string()))?; + let (text, report) = crate::durable::output_owned(g, |g| out.json_pretty(&crate::model::to_file(&name, g)))?; crate::durable::notify(s, &report); - let file: String = name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect(); - match ps(p, "path") { - Some(path) => { - rustgis_data::io::write_atomic(std::path::Path::new(path), text.as_bytes()).map_err(|e| format!("{path}: {e}"))?; - note_passed_graph(s, p); - s.retain_written_notices(written); - Ok(json!({"model": name, "path": path})) - } - None => { - note_passed_graph(s, p); - Ok(json!({"model": name, "fileName": format!("{file}.model.json"), "text": text})) - } - } + Ok((name, text)) } /// Runs a model saved as steps (no graph) in order, putting each step's output layer name in place diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 3f28a62ead..527519d673 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -167,6 +167,11 @@ pub fn commands() -> Vec { .params(r#"{"index"?: number (the last one when omitted), "all"?: bool}"#), C::new("animation.export", "Export Animation", "View › Animation", |s, p| { let written = s.notice_mark(); + // As the Export Animation button says: its frames are drawn on the one thread the + // browser has. + if s.downloads_files() { + return Err("exporting animations needs the desktop app".into()); + } let path = ps(p, "path").ok_or("path is required (a .zip of PNG frames)")?.to_string(); let bytes = animation_zip(s, p)?; rustgis_data::io::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 65f0fe9178..0d2a08a02f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -941,6 +941,8 @@ pub struct Session { /// Notices given in this session, including ones no longer kept (see [`Session::notices_since`]), /// less those a failed command withdrew. notices_given: u64, + /// While a download's file is made, the notices that wait with it ([`Session::holding_notices`]). + held_notices: 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)>, @@ -1535,6 +1537,7 @@ impl Session { bundled_roots_said: false, diagnostics: rustgis_data::diagnostics::History::default(), notices_given: 0, + held_notices: None, losses_given: Vec::new(), beyond_said: None, crs_notes_said: Vec::new(), @@ -1844,8 +1847,8 @@ impl Session { } /// Whether the files commands make reach the user as downloads: the browser has no filesystem - /// to write a path in, so a tool's file output and an export queue their bytes for the front - /// end ([`Session::take_gp_files`]). + /// to write a path in, so a tool's file output and a command's file (an export, a save, a + /// package, a share) queue their bytes for the front end ([`Session::take_gp_files`]). pub(crate) fn downloads_files(&self) -> bool { #[cfg(test)] if self.queue_gp_files { @@ -1893,20 +1896,21 @@ impl Session { self.waiting_downloads().filter_map(|f| f.bytes.as_ref()).map(|bytes| bytes.capacity()).sum() } - /// Whether pending download `id` is an export's: no geoprocessing run records it. + /// Whether pending download `id` is a command's file, as an export's is: no geoprocessing run + /// records it. pub fn is_export_file(&self, id: u64) -> bool { self.file_outputs.iter().any(|file| file.id == id && file.is_export()) } - /// Says which queued downloads among `files` are dropped, and `why`: the exports in one - /// notice (the desktop would have written their files by now), the tools' file outputs in + /// Says which queued downloads among `files` are dropped, and `why`: the commands' files in one + /// notice (the desktop would have written them by now), the tools' file outputs in /// another (a run is recorded only once its file is delivered, so these go unrecorded). fn say_dropped_downloads<'a>(&mut self, files: impl IntoIterator, why: &str) { let (exports, tools): (Vec<_>, Vec<_>) = files.into_iter().partition(|file| file.is_export()); let names = |files: Vec<&cmd::gp::PendingFile>| files.iter().map(|file| file.file_name.clone()).collect::>(); let (exports, tools) = (names(exports), names(tools)); if !exports.is_empty() { - self.notify(format!("{} export(s) not downloaded, {why}: {}", exports.len(), listed(&exports)), true); + self.notify(format!("{} file(s) not downloaded, {why}: {}", exports.len(), listed(&exports)), true); } if !tools.is_empty() { self.notify( @@ -3768,6 +3772,18 @@ impl Session { self.publish_notice(text, severity, self.diagnostic_source, None, false, None); } + /// Runs `f`, keeping aside what it says instead of saying it: the caller says each later + /// ([`Session::relay_notice`]), or never. For a file whose notices wait for its download. + pub(crate) fn holding_notices(&mut self, f: impl FnOnce(&mut Self) -> T) -> (T, Vec) { + let outer = self.held_notices.replace(Vec::new()); + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))); + let held = std::mem::replace(&mut self.held_notices, outer).unwrap_or_default(); + match ran { + Ok(result) => (result, held), + Err(panic) => std::panic::resume_unwind(panic), + } + } + /// Lands a worker's notice under the admitted command, preserving the notice's metadata. pub(crate) fn relay_notice(&mut self, notice: Notice) { self.publish_notice( @@ -3793,22 +3809,19 @@ impl Session { if severity == rustgis_data::diagnostics::Severity::Error && self.rerun_said.iter().any(|said| said == text.as_str()) { return; } + let error = severity == rustgis_data::diagnostics::Severity::Error; + if let Some(held) = &mut self.held_notices { + // Every one: the queue cuts what it keeps when they are relayed, after it has counted them. + held.push(Notice { text: text.into_string(), error, localized, severity, written, loss }); + return; + } let record = self.diagnostics.push_redacted(severity, source.unwrap_or("Application"), &text, loss, self.run.clone()); // A bug's failure keeps its details (the panic's message and place) under it, for a report, // scrubbed as a message is, logins in use included. - if severity == rustgis_data::diagnostics::Severity::Error - && let Some(incident) = rustgis_data::incident::named(text.as_str()) - { + if error && let Some(incident) = rustgis_data::incident::named(text.as_str()) { self.diagnostics.detail(record, Self::redacted(&incident.details()).as_str()); } - self.notices.push(Notice { - text: text.into_string(), - error: severity == rustgis_data::diagnostics::Severity::Error, - localized, - severity, - written, - loss, - }); + self.notices.push(Notice { text: text.into_string(), error, localized, severity, written, loss }); self.notices_given += 1; if let Some(code) = loss { match self.losses_given.iter_mut().find(|(c, _)| *c == code) { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index b6d2cd2f80..0063254f1d 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -15,7 +15,9 @@ mod capabilities; #[path = "project_label_losses.rs"] pub(crate) mod label_losses; pub use capabilities::layout_file_bytes; -pub(crate) use capabilities::{layer_file_bytes, map_file_bytes, model_capabilities, task_capabilities}; +#[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}; /// A map export cannot keep runtime-only download reservations, even in a larger project. pub(crate) fn ensure_map_imports_complete(map: &Map) -> Result<(), String> { @@ -1888,9 +1890,19 @@ impl Project { /// Writes controlled durable fields and relative paths in one guarded transaction. Live /// fields are restored on every return and native unwind; only explicit saves are remembered. pub fn saved_text(&mut self, dir: Option<&Path>) -> Result<(String, crate::durable::Report), String> { + self.saved_with(dir, project_text) + } + + /// [`Self::saved_text`] with the text made by `write`, for a save held to less than a project + /// file may come to, such as a download. + pub(crate) fn saved_with( + &mut self, + dir: Option<&Path>, + write: impl FnOnce(&Project) -> Result, + ) -> Result<(String, crate::durable::Report), String> { self.ensure_imports_complete()?; let unrecorded = self.bound_address_losses(false); - let (text, mut report) = crate::durable::output_remembered(self, dir.and_then(Path::to_str), project_text)?; + let (text, mut report) = crate::durable::output_remembered(self, dir.and_then(Path::to_str), write)?; report.addresses = report.addresses.saturating_add(u32::try_from(unrecorded).unwrap_or(u32::MAX)); Ok((text, report)) } @@ -3056,7 +3068,12 @@ impl Durable for ModelGraph { /// Enforces the opening bound inside the formatter, before any destination is replaced. fn project_text(p: &Project) -> Result { let max = max_bytes(); - json_within(p, max)?.ok_or_else(|| format!("the project is too large to save (maximum {})", limit_said(max))) + json_within(p, max)?.ok_or_else(|| too_large_to_save(max)) +} + +/// Why a project whose text passes `max` bytes isn't saved. +pub(crate) fn too_large_to_save(max: u64) -> String { + format!("the project is too large to save (maximum {})", limit_said(max)) } #[cfg(test)] diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 1440cc949a..14ca001aab 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use super::{FORMAT, ModelGraph, ModelNodeKind, ModelStep, Project}; +use crate::cmd::exports::Output; impl Serialize for Project { fn serialize(&self, serializer: S) -> Result { @@ -1289,20 +1290,31 @@ struct Item<'a, T> { } /// A map file has its own header, independent of the project it came from. +#[cfg(test)] pub(crate) fn map_file_bytes(map: &Map) -> Result, String> { + map_file_within(map, Output::UNLIMITED) +} + +/// The map file of `map`, with its own header, for the file `out` describes. +pub(crate) fn map_file_within(map: &Map, out: Output<'_>) -> Result, String> { let mut requires = map_capabilities([map]); if map.needs_wkt() { requires.push("crs-wkt"); } - serde_json::to_vec(&Item { format: FORMAT, requires, value: map }).map_err(|e| e.to_string()) + out.json(&Item { format: FORMAT, requires, value: map }) } /// 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)); - serde_json::to_vec_pretty(&Item { format: FORMAT, requires, value: layout }).map_err(|e| e.to_string()) + out.json_pretty(&Item { format: FORMAT, requires, value: layout }) } /// What the elements of `layouts` use that an older reader would draw without and save again @@ -1336,12 +1348,19 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static } /// A layer file keeps the same renderer capabilities as the layer saved inside a project. +#[cfg(test)] pub(crate) fn layer_file_bytes(layer: &Layer) -> Result, String> { + layer_file_within(layer, Output::UNLIMITED) +} + +/// The layer file of `layer`, with the same renderer capabilities as the layer saved inside a +/// project, for the file `out` describes. +pub(crate) fn layer_file_within(layer: &Layer, out: Output<'_>) -> Result, String> { let mut requires = layer_capabilities(layer); if layer.needs_wkt() { requires.push("crs-wkt"); } - serde_json::to_vec(&Item { format: FORMAT, requires, value: layer }).map_err(|e| e.to_string()) + out.json(&Item { format: FORMAT, requires, value: layer }) } /// Only executable export options require the capability, not fields in unrelated data. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fc6067c2b8..f094695c24 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -40225,7 +40225,7 @@ fn keys_read_by_commands() -> Vec<(String, std::collections::BTreeSet)> let call = if *m == module { name.as_str() } else { qualified.as_str() }; let key = format!("{m}::{name}"); // A dispatcher by kind: its arms read keys for other commands. - if matches!(key.as_str(), "items::item_bytes" | "items::item_output") { + if matches!(key.as_str(), "items::item_bytes" | "items::item_output" | "items::item_output_within") { continue; } if !seen.contains(&key) && args.iter().any(|a| calls(&body, call, a)) { diff --git a/crates/engine/src/tests/browser_exports.rs b/crates/engine/src/tests/browser_exports.rs index 223a4949cd..7972d8ce58 100644 --- a/crates/engine/src/tests/browser_exports.rs +++ b/crates/engine/src/tests/browser_exports.rs @@ -1,5 +1,6 @@ -//! Exports by command where files are downloaded: the browser has no filesystem to write a path -//! in, so a script's, the Assistant's or a plugin's export is offered as a download instead. +//! Exports, saves, packages and shares by command where files are downloaded: the browser has no +//! filesystem to write a path in, so a script's, the Assistant's or a plugin's file is offered as +//! a download instead, or the command says what to do. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -362,6 +363,7 @@ fn a_browser_export_of_a_large_streamed_layer_is_refused() { for (command, params, file) in [ ("share.exportLayer", json!({"layer": layer}), "z.geojson"), ("data.convert", json!({"layer": layer, "format": "csv"}), "z.csv"), + ("share.webLayer", json!({"layer": layer}), "z.zip"), ] { let read = streamed(&mut s, layer, count, text, chunks); let e = s.run(command, &to(¶ms, file)).unwrap_err(); @@ -383,6 +385,22 @@ fn a_browser_export_of_a_large_streamed_layer_is_refused() { } } +/// A share of several layers read in place holds them to one limit together: two that fit one at +/// a time are refused, naming the second, and nothing waits to be downloaded. +#[test] +fn a_browser_share_of_several_streamed_layers_is_held_to_one_limit() { + let files = Files::new(); + let mut s = session(&files, true); + for layer in ["First", "Second"] { + streamed(&mut s, layer, None, 140 << 20, true); + } + for command in ["share.webMap", "share.geodataService"] { + let e = s.run(command, &json!({"path": "shared.zip"})).unwrap_err(); + assert!(e.contains("with the layers read before it") && e.contains("more than the 256 MiB"), "{command}: {e}"); + assert!(s.take_gp_files().is_empty(), "{command}"); + } +} + /// Every export command that downloads, over the limit (a stand-in of ten bytes): its /// writer stops once the file passes it, nothing waits to be downloaded, and the refusal says /// how to export. A picture's size is bounded by its pixels, so a PNG, an SVG, and the file a @@ -428,7 +446,7 @@ fn a_browser_export_over_the_limit_is_stopped_as_it_is_made() { for (command, params, file, refusal) in cases { s.download_cap = Some(10); let e = s.run(command, &to(¶ms, file)).unwrap_err(); - assert!(e.contains(file) && e.contains(refusal) && e.contains("export less"), "{command} {file}: {e}"); + assert!(e.contains(file) && e.contains(refusal) && e.contains("make a smaller file"), "{command} {file}: {e}"); assert!(e.contains("desktop app"), "{e}"); assert!(s.take_gp_files().is_empty(), "{command} {file}"); s.download_cap = Some(1 << 20); @@ -490,7 +508,7 @@ fn a_failed_commands_export_from_a_project_it_opened_is_said_dropped() { let script = "project.new\nshare.exportMap {\"width\": 64, \"height\": 64, \"path\": \"later.png\"}\nno.suchCommand"; s.run("script.run", &json!({"script": script})).unwrap_err(); let dropped: Vec = said(&s, mark).into_iter().filter(|n| n.contains("not downloaded")).collect(); - assert_eq!(dropped, ["1 export(s) not downloaded, as the command that made them failed: later.png"]); + assert_eq!(dropped, ["1 file(s) not downloaded, as the command that made them failed: later.png"]); let waiting: Vec = s.take_gp_files().into_iter().map(|f| f.1).collect(); assert_eq!(waiting, ["totals.csv"]); } @@ -521,7 +539,7 @@ fn a_browser_download_dropped_before_it_is_offered_is_said() { let expected = |queued: &[&str], why: &str| { let mut notices = Vec::new(); if queued.contains(&export) { - notices.push(format!("1 export(s) not downloaded, {why}: totals.csv")); + notices.push(format!("1 file(s) not downloaded, {why}: totals.csv")); } if queued.contains(&tool) { notices.push(format!( @@ -556,3 +574,421 @@ fn a_browser_download_dropped_before_it_is_offered_is_said() { assert_eq!(dropped(&s, mark), expected(queued, "as another project replaced theirs first"), "{queued:?}"); } } + +/// [`session`] with an item of every kind a command saves, and a field name long enough that a +/// template and a package have something to leave out. +fn items(files: &Files, browser: bool) -> Session { + let mut s = session(files, false); + s.run("layer.addDataBytes", &json!({"fileName": "scene.tif", "data": super::two_class_b64()})).unwrap(); + let square = |class: &str, x: f64| { + json!({"type": "Feature", "properties": {"class": class}, "geometry": {"type": "Polygon", + "coordinates": [[[x, 45.002], [x + 0.013, 45.002], [x + 0.013, 45.035], [x, 45.035], [x, 45.002]]]}}) + }; + let training = json!({"type": "FeatureCollection", "features": [square("water", 10.002), square("field", 10.025)]}); + s.run("layer.addDataText", &json!({"fileName": "training.geojson", "text": training.to_string()})).unwrap(); + for (command, params) in [ + ( + "dl.train", + json!({"layer": "scene", "training": "training", "classField": "class", "bands": [1, 2], "epochs": 3, "model": "cover"}), + ), + ("task.new", json!({"name": "Steps", "steps": [{"title": "Zoom", "command": "map.zoomFull"}]})), + ("bookmark.add", json!({"name": "Home"})), + ("style.new", json!({"layer": "Places", "name": "Dots"})), + ("ramp.add", json!({"name": "Mine", "format": "clr", "text": "0 0 0 0\n1 255 255 255\n"})), + ("gp.run", json!({"tool": "buffer", "params": {"input": "Places", "distance": 100}})), + ("presentation.new", json!({"name": "Slides"})), + ("presentation.mapPage", json!({})), + ("notebook.new", json!({"name": "Notes"})), + ("model.new", json!({"name": "Ring", "steps": [{"tool": "buffer", "params": {"input": "Places", "distance": 5}}]})), + ( + "data.relate", + json!({"name": "Kin", "origin": "training", "originKey": "class", "destination": "training", "destinationKey": "class"}), + ), + ] { + s.run(command, ¶ms).unwrap_or_else(|e| panic!("{command}: {e}")); + } + // One layer in view for the commands that act on the active one. + s.active_layer = s.map().layer_by_name("Places").map(|l| l.id); + s.queue_gp_files = browser; + s +} + +/// The line that says a file is out, which differs between the desktop and a download. +fn says_it_is_out(notice: &str) -> bool { + ["Saved ", "Exported ", "Shared ", "Download offered: "].iter().any(|start| notice.starts_with(start)) +} + +/// The commands that save, package or share a file: command, other parameters, file name, and +/// whether two writes of it give the same bytes. +fn file_cases() -> Vec<(&'static str, Value, &'static str, bool)> { + vec![ + ("map.save", json!({}), "m.rgismap", true), + ("map.package", json!({}), "m.rgismpk", true), + ("map.package", json!({"mobile": true}), "mobile.rgismpk", true), + ("layer.save", json!({"layer": "Places"}), "l.rgislyr", true), + ("style.save", json!({}), "s.rgisstyle", true), + ("ramp.save", json!({}), "r.rgisramp", true), + ("project.saveTemplate", json!({}), "t.rgistemplate", false), + ("project.newTemplate", json!({"name": "Mine"}), "n.rgistemplate", false), + ("project.package", json!({}), "p.rgispkg", false), + ("gp.package", json!({}), "g.rgisgpk", false), + ("task.save", json!({"task": "Steps"}), "k.rgistask", true), + ("bookmark.save", json!({}), "b.rgisbookmarks", true), + ("layout.save", json!({"layout": "Page"}), "l.rgislayout", true), + ("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!({"dpi": 48}), "s.pdf", false), + ("presentation.export", json!({"dpi": 48}), "s.png", true), + ("notebook.save", json!({}), "n.rgisnb", true), + ("notebook.save", json!({}), "n.ipynb", true), + ("model.export", json!({"name": "Ring"}), "ring.model.json", true), + ("dl.package", json!({"model": "cover"}), "c.rgisdlpk", false), + ("imagery.mesh", json!({"layer": "Dem"}), "dem.obj", true), + ("imagery.hostedImagery", json!({"layer": "scene", "maxZoom": 8}), "tiles.zip", false), + ("share.export3d", json!({"layer": "Places"}), "p.obj", true), + ("share.export3d", json!({"layer": "training"}), "t.stl", true), + ("share.webMap", json!({}), "map.html", false), + ("share.webLayer", json!({"layer": "Places"}), "layer.zip", false), + ("share.webStyle", json!({"layer": "Places"}), "style.json", true), + ("share.locator", json!({"layer": "Places"}), "find.rgisloc", true), + ("share.geodataService", json!({}), "data.zip", false), + ("share.webTool", json!({"model": "Ring"}), "tool.rgistool", true), + ("share.webScene", json!({}), "scene.gltf", false), + ("share.linkChart", json!({}), "chart.html", true), + ] +} + +/// Two writes of a file whose ids or times differ hold the same: a zip the same entries, JSON the +/// same members and as many items, and anything else as many bytes. +fn assert_same_shape(a: &[u8], b: &[u8], what: &str) { + fn same(a: &Value, b: &Value) -> bool { + match (a, b) { + (Value::Object(a), Value::Object(b)) => a.len() == b.len() && a.iter().all(|(k, v)| b.get(k).is_some_and(|w| same(v, w))), + (Value::Array(a), Value::Array(b)) => a.len() == b.len() && a.iter().zip(b).all(|(v, w)| same(v, w)), + (a, b) => std::mem::discriminant(a) == std::mem::discriminant(b), + } + } + if b.starts_with(b"PK") { + let (a, b) = (rustgis_data::zip::read(a).unwrap(), rustgis_data::zip::read(b).unwrap()); + let names = |z: &[(String, Vec)]| z.iter().map(|(name, _)| name.clone()).collect::>(); + assert_eq!(names(&a), names(&b), "{what}"); + for ((name, a), (_, b)) in a.iter().zip(&b) { + assert_same_shape(a, b, &format!("{what}: {name}")); + } + } else if let Ok(b) = serde_json::from_slice::(b) { + assert!(same(&serde_json::from_slice(a).unwrap(), &b), "{what}"); + } else { + assert_eq!(a.len(), b.len(), "{what}"); + } +} + +/// What is said while a file is made counts in full however much of it there is: the queue keeps +/// the latest 200 and counts the rest. +#[test] +fn every_notice_held_for_a_download_is_relayed() { + let mut s = Session::new(Project::default()); + let ((), held) = s.holding_notices(|s| (0..250).for_each(|k| s.notify(format!("note {k}"), false))); + let mark = s.notice_mark(); + for notice in held { + s.relay_notice(notice); + } + assert_eq!(s.notice_mark() - mark, 250); +} + +/// Each command that saves, packages or shares a file downloads, under the path's name, the file +/// the desktop writes, and says of it what the desktop says, once the download is taken. +#[test] +fn a_browser_file_command_downloads_the_desktops_file_and_says_the_same() { + let mut lossy = 0; + for (command, params, file, same_bytes) in file_cases() { + let files = Files::new(); + let mut desktop = items(&files, false); + let path = files.path().join(file); + let path = path.to_str().unwrap(); + let mark = desktop.notice_mark(); + desktop.run(command, &to(¶ms, path)).unwrap_or_else(|e| panic!("{command} {file}: {e}")); + let written = std::fs::read(path).unwrap(); + let folder = format!("{}{}", files.path().display(), std::path::MAIN_SEPARATOR); + let mut desktop_said: Vec = + said(&desktop, mark).into_iter().map(|n| n.replace(&folder, "")).filter(|n| !says_it_is_out(n)).collect(); + desktop_said.sort(); + lossy += usize::from(!desktop_said.is_empty()); + + let mut browser = items(&files, true); + std::fs::remove_file(path).unwrap(); + let (mark, steps) = (browser.notice_mark(), browser.undo_depth()); + let pending = browser.run(command, &to(¶ms, file)).unwrap_or_else(|e| panic!("{command} {file}: {e}")); + assert_eq!(said(&browser, mark), Vec::::new(), "{command} {file}: nothing is said before the download"); + let messages: Vec<&str> = pending["messages"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + for note in &desktop_said { + assert!(messages.contains(¬e.as_str()), "{command} {file}: {note} not in {messages:?}"); + } + let (name, bytes, answer) = deliver(&mut browser, &pending, None); + assert_eq!(name, file); + if same_bytes { + assert!(bytes == written, "{command} {file}: {} bytes downloaded, {} written", bytes.len(), written.len()); + } else { + assert_same_shape(&bytes, &written, &format!("{command} {file}")); + } + let (out, mut rest): (Vec<_>, Vec<_>) = said(&browser, mark).into_iter().partition(|n| says_it_is_out(n)); + rest.sort(); + assert_eq!(out.len(), 1, "{command} {file}: {out:?}"); + assert!(out[0].contains(file), "{command} {file}: {out:?}"); + assert_eq!(rest, desktop_said, "{command} {file}"); + let answer = answer.unwrap(); + assert_eq!((&answer["delivered"], &answer["file"]), (&json!(true), &json!(file)), "{answer}"); + assert!(!std::path::Path::new(file).exists(), "{command} {file}: no file is written"); + assert_eq!(browser.undo_depth(), steps, "{command} {file}"); + assert!(browser.project.shared.is_empty(), "{command}: a download isn't a shared item"); + } + // Some of these leave something out, so the comparison above has notices to compare. + assert!(lossy >= 3, "{lossy}"); +} + +/// 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. +#[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(); + cases.extend([ + ("project.save", json!({}), "p.rgis", false), + ("project.saveAs", json!({}), "q.rgis", false), + ("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!(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}")); + let (_, bytes, answer) = deliver(&mut s, &pending, None); + assert!(!bytes.is_empty() && bytes.len() <= 8 << 20, "{command} {file}: {}", bytes.len()); + answer.unwrap(); + } +} + +/// 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. +#[test] +fn a_browser_stl_is_held_to_its_room_by_the_triangles_it_keeps() { + let files = Files::new(); + let mut s = session(&files, true); + // Enough points that their mesh is past what any download's may hold, whatever its room. + let mut many = Dataset::new("Many", GeometryType::Point, vec![]); + for k in 0..30_000 { + many.push(Some(Geometry::Point(rustgis_data::Coord::new(f64::from(k % 300) * 0.1, f64::from(k / 300) * 0.1))), vec![]); + } + s.map_mut().add_dataset(many); + let flat = json!({"layer": "Places", "height": 1e-12, "path": "flat.stl"}); + let cube = json!({"layer": "Places", "path": "cube.stl"}); + let flat_many = json!({"layer": "Many", "height": 1e-12, "path": "many.stl"}); + for (params, bytes) in [(&flat, 284), (&cube, 684), (&flat_many, 84 + 30_000 * 200)] { + s.download_cap = Some(bytes - 1); + let e = s.run("share.export3d", params).unwrap_err(); + assert!(e.contains(".stl: stopped once the file passed"), "{e}"); + assert!(s.take_gp_files().is_empty()); + s.download_cap = Some(bytes); + let pending = s.run("share.export3d", params).unwrap(); + let (_, file, answer) = deliver(&mut s, &pending, None); + assert_eq!(file.len(), bytes); + answer.unwrap(); + } +} + +/// A full queue is refused before a file command makes anything: nothing of the file is said. +#[test] +fn a_browser_file_command_is_refused_before_it_is_made_when_no_more_can_wait() { + let files = Files::new(); + let mut s = items(&files, true); + for i in 0..crate::cmd::exports::MAX_DOWNLOADS { + s.run("style.save", &json!({"path": format!("{i}.rgisstyle")})).unwrap(); + } + let mark = s.notice_mark(); + let e = s.run("project.saveTemplate", &json!({"path": "t.rgistemplate"})).unwrap_err(); + assert!(e.contains("file export queue limit reached"), "{e}"); + assert_eq!(said(&s, mark), [e]); + assert_eq!(s.take_gp_files().len(), crate::cmd::exports::MAX_DOWNLOADS); +} + +/// The session log downloads as CSV or JSON Lines, in the format its name or `format` says. +#[test] +fn a_browser_session_log_downloads_in_its_format() { + let files = Files::new(); + let mut s = session(&files, true); + for (params, file, first) in + [(json!({"path": "out/log.csv"}), "log.csv", "time_utc,"), (json!({"path": "log", "format": "jsonl"}), "log", "{")] + { + let mark = s.notice_mark(); + let pending = s.run("project.exportLog", ¶ms).unwrap(); + assert_eq!(said(&s, mark), Vec::::new()); + let (name, bytes, answer) = deliver(&mut s, &pending, None); + assert_eq!(name, file); + assert!(bytes.starts_with(first.as_bytes()), "{file}: {}", String::from_utf8_lossy(&bytes)); + let entries = answer.unwrap()["entries"].clone(); + let notices = said(&s, mark); + let out = format!("Exported the session log ({entries} entries) to {file}"); + assert!(notices.contains(&out), "{notices:?}"); + assert_eq!(notices.iter().any(|n| n.contains("the folder in")), params["path"] == "out/log.csv", "{notices:?}"); + } + let e = s.run("project.exportLog", &json!({"path": "log.rgis"})).unwrap_err(); + assert!(e.contains("not a .rgis one"), "{e}"); + assert!(s.take_gp_files().is_empty()); +} + +/// Save and Save As download the project. It stays unsaved and has no file; Save As names it +/// after the download once the download is taken. +#[test] +fn a_browser_project_save_downloads_the_project() { + let files = Files::new(); + for (command, path, file, named) in [ + ("project.saveAs", "Atlas.rgis", "Atlas.rgis", "Atlas"), + ("project.saveAs", "/home/me/Atlas", "Atlas.rgis", "Atlas"), + ("project.save", "Copy.rgis", "Copy.rgis", "Untitled"), + ] { + let mut s = session(&files, true); + s.project.name = "Untitled".into(); + s.mark_saved(); + let (mark, steps) = (s.notice_mark(), s.undo_depth()); + let pending = s.run(command, &json!({"path": path})).unwrap(); + assert_eq!((s.project.name.as_str(), said(&s, mark)), ("Untitled", Vec::new()), "{command}"); + let (name, bytes, answer) = deliver(&mut s, &pending, None); + assert_eq!(name, file); + let saved = Project::from_json(std::str::from_utf8(&bytes).unwrap()).unwrap(); + assert_eq!(saved.name, named, "{command}"); + assert_eq!(s.project.name, named, "{command}"); + assert_eq!(answer.unwrap()["path"], file); + let notices = said(&s, mark); + let offered = format!("Download offered: {file}. The browser doesn't say whether it saved the file."); + assert!(notices.contains(&offered), "{notices:?}"); + assert!(!notices.iter().any(|n| n.starts_with("Saved ") || n.contains("first 200")), "{notices:?}"); + // A rename leaves it unsaved; a download under its own name changes nothing. + assert_eq!(s.dirty(), named != "Untitled", "{command}"); + assert_eq!((s.path.is_none(), s.undo_depth()), (true, steps), "{command}"); + } + // Not taken, or renamed meanwhile: the name stays. + let mut s = session(&files, true); + s.project.name = "Untitled".into(); + let pending = s.run("project.saveAs", &json!({"path": "Atlas.rgis"})).unwrap(); + let mark = s.notice_mark(); + deliver(&mut s, &pending, Some("download blocked")).2.unwrap(); + assert_eq!((s.project.name.as_str(), said(&s, mark)), ("Untitled", vec!["download blocked".to_string()])); + let pending = s.run("project.saveAs", &json!({"path": "Atlas.rgis"})).unwrap(); + s.run("project.rename", &json!({"name": "Later"})).unwrap(); + deliver(&mut s, &pending, None).2.unwrap(); + assert_eq!(s.project.name, "Later"); + // A name longer than a project's is cut, and that is said. + let long = "n".repeat(201); + let pending = s.run("project.saveAs", &json!({"path": format!("{long}.rgis")})).unwrap(); + let mark = s.notice_mark(); + deliver(&mut s, &pending, None).2.unwrap(); + assert_eq!(s.project.name, "n".repeat(200)); + assert!(said(&s, mark).iter().any(|n| n.contains("201 characters") && n.contains("first 200"))); + // Refused as the desktop refuses it. + let e = s.run("project.saveAs", &json!({"path": "atlas.geojson"})).unwrap_err(); + assert!(e.contains("not a .geojson one"), "{e}"); + assert!(s.take_gp_files().is_empty()); +} + +/// A file command that fails, and a download not taken, say only why. +#[test] +fn a_browser_file_not_made_or_not_taken_says_only_why() { + let files = Files::new(); + let mut s = items(&files, true); + let e = s.run("map.save", &json!({"path": "m.rgismap", "map": "nowhere"})).unwrap_err(); + assert!(e.contains("nowhere"), "{e}"); + assert!(s.take_gp_files().is_empty()); + let pending = s.run("project.saveTemplate", &json!({"path": "t.rgistemplate"})).unwrap(); + let mark = s.notice_mark(); + let (_, _, answer) = deliver(&mut s, &pending, Some("download blocked")); + assert_eq!(answer.unwrap()["delivered"], false); + assert_eq!(said(&s, mark), ["download blocked"]); + // Dropped with a script that fails afterwards, and said. + let mark = s.notice_mark(); + let script = "map.save {\"path\": \"m.rgismap\"}\nno.suchCommand"; + s.run("script.run", &json!({"script": script})).unwrap_err(); + let notices = said(&s, mark); + assert!(notices.iter().any(|n| n == "1 file(s) not downloaded, as the command that made them failed: m.rgismap"), "{notices:?}"); + assert!(s.take_gp_files().is_empty()); +} + +/// A model exported from a graph that couldn't be read whole says so once its download is +/// taken, and a whole graph's export doesn't. +#[test] +fn a_browser_model_export_says_what_its_graph_left_out() { + let files = Files::new(); + let mut s = session(&files, true); + for (nodes, left_out) in [(json!([]), false), (json!(["not a node"]), true)] { + let mark = s.notice_mark(); + let params = json!({"graph": {"nodes": nodes, "edges": []}, "path": "m.model.json"}); + let pending = s.run("model.export", ¶ms).unwrap(); + assert_eq!(said(&s, mark), Vec::::new()); + assert_eq!(pending["messages"].to_string().contains("1 node(s) left out"), left_out, "{pending}"); + deliver(&mut s, &pending, None).2.unwrap(); + let notices = said(&s, mark); + assert_eq!(notices.iter().filter(|n| n.contains("1 node(s) left out")).count(), usize::from(left_out), "{notices:?}"); + } +} + +/// What needs a file to stay where it is, or a folder, is refused with what to do instead, before +/// anything is made. +#[test] +fn what_a_download_cant_stand_in_for_is_refused() { + let files = Files::new(); + let mut s = items(&files, true); + // A shared item a project opened in the browser lists. + for (id, kind) in ["webMap", "webLayer", "webScene", "linkChart"].into_iter().enumerate() { + s.project.shared.push(crate::cmd::sharing::SharedItem { + id: id as u32 + 1, + kind: kind.into(), + name: "Old".into(), + source: "Places".into(), + path: "/srv/old".into(), + created: 0.0, + updated: 0.0, + bytes: 1, + this_session: false, + }); + } + let (layers, layouts, shared) = (s.map().layers.len(), s.project.layouts.len(), s.project.shared.clone()); + let path = |command: &str| format!("the web app can't update a shared file in place; run {command} with a path"); + for (command, params, why) in [ + ("share.saveWebMap", json!({}), path("share.webMap")), + ("share.replaceWebLayer", json!({}), path("share.webLayer")), + ("share.saveWebScene", json!({}), path("share.webScene")), + ("share.saveWebLinkChart", json!({}), path("share.linkChart")), + ("share.webMap", json!({}), "pass a path".into()), + ("share.webStyle", json!({"layer": "Places"}), "pass a path".into()), + ("share.dataStore", json!({"path": "/srv/shares"}), "can't write to a folder".into()), + ("share.upload", json!({"path": "a.csv"}), "desktop app".into()), + ("animation.export", json!({"path": "a.zip"}), "exporting animations needs the desktop app".into()), + ("raster.project", json!({"layer": "Dem", "crs": "EPSG:3857", "path": "p.tif"}), "leave out path".into()), + ("raster.rasterize", json!({"layer": "training", "cellSize": 0.01, "path": "r.tif"}), "leave out path".into()), + ("raster.mosaic", json!({"inputs": ["Dem", "Dem"], "path": "m.tif"}), "leave out path".into()), + ( + "raster.georeference", + json!({"layer": "Dem", "transform": "similarity", "points": [[0, 0, 0, 1], [1, 1, 1, 0]], "path": "g.tif"}), + "leave out path".into(), + ), + ("layout.publication", json!({"coverage": "c.png"}), "leave out coverage".into()), + ] { + let e = s.run(command, ¶ms).unwrap_err(); + assert!(e.contains(&why), "{command}: {e}"); + assert!(s.take_gp_files().is_empty(), "{command}"); + } + assert_eq!((s.map().layers.len(), s.project.layouts.len()), (layers, layouts)); + assert_eq!(s.project.shared, shared); + // What the refusals leave to do still works: a result kept in the project, a store removed. + s.run("raster.mosaic", &json!({"inputs": ["Dem", "Dem"]})).unwrap(); + s.run("share.dataStore", &json!({})).unwrap(); +} diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md index 8fa08cf50f..f0cbaa2e26 100644 --- a/docs/user-guide/sharing.md +++ b/docs/user-guide/sharing.md @@ -84,24 +84,51 @@ the formats above that can hold it: for a table without geometry, CSV, GeoJSON, (no GeoPackage in the web app, which downloads the file). Scripts and the command line use `share.exportTable`. -The browser can't write to a folder, so in the web app an export command with a `path` (from the -Script pane, the Assistant or a plugin) downloads the file under the name the path ends in, once -the commands finish: `share.exportLayer`, `share.exportTable`, `share.exportMap`, -`share.exportRaster` (a raster layer), `layout.export`, `report.export` and `data.convert`. A -folder in the path isn't used, and a `.shp` path downloads a `.zip` of the Shapefile's files; a -notice says each. At most 8 files, 256 MiB in all, can wait to be downloaded (a geoprocessing -tool's file output waits the same way), and those of a script that then fails, or of a project -replaced before they are offered, are dropped with a notice. A tool output dropped this way leaves -its run out of the geoprocessing history. An export is refused once its file passes what is left of -the 256 MiB, as it is made where the format allows, and for a Shapefile's `.zip` or a KMZ counting -its files before they are zipped: export a selection of features, a smaller size or fewer pages, -or use the desktop app. -`share.exportLayer` and `data.convert` read a layer read in place whole for such a download, up to -256 MiB of features; past that, select the features you need and export a layer made from them with -**Make Layer From Selected Features**, or use the desktop app. They don't read a layer added by its -web address this way: download the file and add it, or use the desktop app. -GeoPackage and FlatGeobuf, a tile layer as a raster, an orbit, a block and publishing to a source -need the desktop app; for a field package, use **Package for the Field** on the ribbon. +The browser can't write to a folder, so in the web app a command given a `path` (from the Script +pane, the Assistant or a plugin) downloads the file under the name the path ends in, once the +commands finish: + +- exports: `share.exportLayer`, `share.exportTable`, `share.exportMap`, `share.exportRaster` (a + raster layer), `share.export3d`, `layout.export`, `report.export`, `presentation.export`, + `data.convert`, `model.export`, `project.exportLog`, `imagery.mesh` and + `imagery.hostedImagery`; +- saves and packages: `project.save`, `project.saveAs`, `project.saveTemplate`, + `project.newTemplate`, `project.package`, `map.save`, `map.package`, `layer.save`, + `style.save`, `ramp.save`, `task.save`, `bookmark.save`, `layout.save`, `report.save`, + `report.saveTemplate`, `presentation.save`, `notebook.save`, `gp.package` and `dl.package`; +- shares: `share.webMap` and the other **Share As** commands. + +A folder in the path isn't used, and a `.shp` path downloads a `.zip` of the Shapefile's files; a +notice says each. What a command says of its file, losses included, is said once the download is +taken. At most 8 files, 256 MiB in all, can wait to be downloaded (a geoprocessing tool's file +output waits the same way), and those of a script that then fails, or of a project replaced before +they are offered, are dropped with a notice. A tool output dropped this way leaves its run out of +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. + +`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 +features (a share's layers together); past that, select the features you need and make a layer +from them with **Make Layer From Selected Features**, or use the desktop app. They don't read a +layer added by its web address this way: download the file and add it, or use the desktop app. + +A downloaded file can't be written again, so: + +- `project.save` and `project.saveAs` don't mark the project saved, as the browser doesn't say + whether it saved the file; `project.saveAs` names the project after the file once the download + is taken, and a project it renames is unsaved. +- A download isn't listed under **Jobs**, and the **Manage** commands that update a shared file + (`share.saveWebMap`, `share.replaceWebLayer`, `share.saveWebScene`, + `share.saveWebLinkChart`) are refused: share it again instead. A share needs a `path`, as there + are no data stores (`share.dataStore`) or uploads (`share.upload`). +- `raster.project`, `raster.rasterize`, `raster.mosaic` and `raster.georeference` refuse a + `path`, which the new layer would read: leave it out, then export the layer. + +GeoPackage and FlatGeobuf, a tile layer as a raster, an orbit, a block, animations, the time +slider's steps, `layout.publication`'s `coverage` image and publishing to a source need the +desktop app; for a field package, use **Package for the Field** on the ribbon. To export the largest rows of a Summary Statistics result, give `share.exportTable` an optional `sort` list and `limit`. Each sort key names a stored field; `descending` defaults to `false`. @@ -166,8 +193,10 @@ Packages and project item files are described under [Project items](data.md#proj ## Sharing as open formats **Publish › Share As** writes open-format files to a chosen file on desktop, or downloads them -in the browser. The Share As commands accept a `path`; without one they use the first -**data store** (a folder added with **Add Data Store…** in the Shared Items pane). +in the browser. The Share As commands accept a `path`. On the desktop, one run without a `path` +writes to the first **data store** (a folder added with **Add Data Store…** in the Shared Items +pane), or the one `store` names. The browser has no data stores: a Share As command needs a +`path` there and is refused without one. - **Web Map** (`share.webMap`): an HTML page of visible layers (rasters as embedded images), pan and zoom, a layer list and pop-ups. It uses a flat Mercator view, not the project's