Repository navigation
fix(web): stop pictures, SVGs and PDFs at the download limit as they are made #3320
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
a5463c3
d46727d
dbbb928
bedcaae
344499c
42dc73c
a91af92
bf625f4
968e552
3ba19ea
79bbfc9
16e68e3
f319c2b
9a69595
2167d4c
59e381c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<W: Write + ?Sized>(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<W: Write + ?Sized>(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<W: Write + ?Sized> Write for ImageData<'_, W> { | ||
| fn write(&mut self, data: &[u8]) -> std::io::Result<usize> { | ||
| 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<u8>, tried: &mut Vec<u8>) { | ||
| 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::<u32>())) | ||
| .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"); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<T, E: std::fmt::Display>( | ||
| download: Option<(Room, &str)>, | ||
| make: impl FnOnce(&Limit) -> Result<T, E>, | ||
| ) -> Result<T, String> { | ||
| 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(), | ||
| }) | ||
| } | ||
|
Comment on lines
+149
to
+158
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This repeats Suggest one helper with the path prefix in both cases, with Category: quality
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Left for the release quality pass: the exports that call it put the file name on their own errors, so one helper needs that settled in each. |
||
|
|
||
| /// 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<T, E: std::fmt::Display>(self, make: impl FnOnce(&Limit) -> Result<T, E>) -> Result<T, String> { | ||
| 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) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<u8>, 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)); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Twin the change missed: the PR drops the drawing-cost pre-check for Print Map, because
Each of these runs before Category: bug
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Kept on purpose, and as it was on |
||
| } | ||
| let html = format!( | ||
| r#"<!doctype html> | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This row loop has no Cancel look. A 8192 × 8192 picture is 8,192 rows of filtering and compressing (the PR's own timings put a 4096² noise picture at about 2.5 s), and nothing between rows calls
progress::check, so a cancelled download export waits for the whole picture. The download path runs in the background (exports::runs_in_background), so Cancel is supposed to be seen between items of a long loop. The fix is one line;Error::otheris already used incapped.rs:The
encode_pngpath this replaces had the same gap, so this isn't a regression. The new loop is the place to add the look, or the doc comment should say the picture is one long step. Confidence about 60% that the rule applies as written; I did not runcancelling_at_each_check_leaves_nothing_behind.Category: agents-md
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added in the next push: the loop looks at Cancel at each row, and its comment says so. Only a file with a limit comes this way, which is the browser, whose one thread cannot be cancelled while it runs, so it is for a caller that can.