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