Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/data/src/loss.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,12 @@ loss_codes! {
"Curves, circles, rotated boxes or edges that follow the Earth's curve were read, drawn or written as straight segments.",
"Keep the source file where exact curves matter: RustGIS draws curves as straight segments."
),
ApproximatedResolution => (
"approximated.resolution",
Approximated,
"A page was drawn at a lower resolution than asked, because a page holds at most 12,000 pixels a side and 60 million pixels in all (25 million in the browser).",
"Export a smaller page to keep the resolution asked. When the notice gives 36 dpi or more, you can also ask for that dpi; a lower request is raised to 36 dpi, so the notice comes back."
),
AssumedNullMarker => (
"assumed.null-marker",
Assumed,
Expand Down
17 changes: 16 additions & 1 deletion crates/engine/src/cmd/layout/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ fn layout_bytes_for(
/// millimetres from the page's top left), drawn at that `dpi` rather than cut out of the whole
/// page: what the assistant's `view_map` shows of a layout. It says what exporting the page says
/// of it: texts cut off, named fonts still being read, frames drawn without their cast shadows,
/// pictures drawn as a grey box, charts' notices.
/// pictures drawn as a grey box, charts' notices, and a whole page drawn at a lower dpi than asked.
pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]>) -> Result<Vec<u8>, String> {
let img = layout_page(s, li, dpi, region, |layout, maps, info| match region {
Some(r) => rustgis_render::layout::render_region(layout, maps, dpi, info, r),
Expand Down Expand Up @@ -145,6 +145,10 @@ pub(super) fn layout_page(
for note in rustgis_render::layout::profiles_notice(&profiles, 1) {
s.warn(note);
}
// A region has a budget of its own: only the whole page is said.
if region.is_none() {
say_page_scale(s, rustgis_render::layout::page_scale_notice(&layout, dpi, "PNG"));
}
Ok(img)
}

Expand Down Expand Up @@ -380,6 +384,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner(
s.warn(note);
}
pictured_notices(s, &frames_pictured, &pages_pictured);
say_page_scale(s, rustgis_render::layout::page_scale_notice(&saved, dpi, if pdf { "PDF" } else { "PNG" }));
georeference_notices(s, &left_out, &by_corners, pages.len());
if !pdf {
return png.ok_or_else(|| "nothing to draw".to_string());
Expand All @@ -390,6 +395,14 @@ pub(in crate::cmd::layout) fn layout_bytes_inner(
Ok(bytes)
}

/// Says that a page past the renderer's budget is drawn at a lower dpi than asked (#3463), as the
/// approximation it is: once, whatever the pages of a series.
fn say_page_scale(s: &mut Session, note: Option<String>) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the one notice for layout exports, but its twins that draw layout pages still cut them without saying so: presentation.export's draw_page (crates/engine/src/cmd/presentation.rs:478) calls layout::render directly, and the report's flowing pages cap their scale at MAX_PIXELS silently (crates/render/src/report.rs:374-376). The PR lists these as "not in this PR", but AGENTS.md says existing silent losses are bugs, and this loss code exists precisely for this case. Either route them through the same check in this PR, or file a follow-up and link it here.

Category: bug

if let Some(note) = note {
s.notify_loss(rustgis_data::loss::LossCode::ApproximatedResolution, note.into());
}
}

/// Says which faces a PDF set in outlines though its text was to be in fonts (#1815), with why:
/// their text is drawings, not text, in a vector editor. One notice, the faces counted.
pub(crate) fn outlined_notice(s: &mut Session, outlined: &[rustgis_render::pdf::Outlined]) {
Expand Down Expand Up @@ -609,6 +622,7 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd
let layout = s.project.layouts.get(li).ok_or("no layout")?;
let clipped = rustgis_render::layout::clipped_text(layout, &s.project.maps, dpi, &info);
let note = rustgis_render::layout::clipped_text_notice(layout, &clipped);
let scale = rustgis_render::layout::page_scale_notice(layout, dpi, "SVG");
let gaps = rustgis_render::layout::sections_not_drawn(layout, &s.project.maps).into_iter().map(|g| (g, 1)).collect();
let grey = rustgis_render::layout::pictures_not_drawn(layout);
let profiles: ProfileNotes = rustgis_render::layout::profiles_not_drawn(layout, &s.project.maps).into_iter().map(|n| (n, 1)).collect();
Expand Down Expand Up @@ -648,5 +662,6 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd
s.warn(note);
}
pictured_notices(s, &pictured, &[]);
say_page_scale(s, scale);
Ok(text)
}
2 changes: 2 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ mod layout_chart_notices;

#[path = "tests/layout_credits.rs"]
mod layout_credits;
#[path = "tests/layout_page_scale.rs"]
mod layout_page_scale;
#[path = "tests/map_credits.rs"]
mod map_credits;

Expand Down
113 changes: 113 additions & 0 deletions crates/engine/src/tests/layout_page_scale.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
//! A layout export past the page's pixel limit says the dpi it is drawn at (#3463).

use super::layout_credits::Dir;
use super::*;
use rustgis_data::loss::LossCode;

/// The world with a blank layout "Strip", 5000 mm by 20 mm: at 150 dpi it would be 29,528 pixels
/// wide, past the 12,000 a side a page holds, but only 12,000 by 118 pixels once drawn.
fn strip() -> Session {
let mut s = world();
s.run("layout.new", &json!({"name": "Strip", "template": "blank", "width": 5000, "height": 20})).unwrap();
s
}

/// What exporting the layout to a file of `ext` at `dpi` says of its resolution, with each
/// notice's loss code, and the file's bytes.
fn exported(s: &mut Session, dir: &Dir, ext: &str, dpi: f64) -> (Vec<(String, Option<LossCode>)>, Vec<u8>) {
let path = dir.0.join(format!("page.{ext}"));
let mark = s.notice_mark();
s.run("layout.export", &json!({"path": path, "dpi": dpi})).unwrap();
let said = s.notices_since(mark).iter().filter(|n| n.text.contains("dpi asked")).map(|n| (n.text.clone(), n.loss())).collect();
(said, std::fs::read(path).unwrap())
}

/// A PNG's width and height from its header.
fn png_size(bytes: &[u8]) -> (u32, u32) {
let side = |at: usize| u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap());
(side(16), side(20))
}

#[test]
fn a_layout_export_past_the_pixel_limit_says_the_dpi_it_is_drawn_at() {
let dir = Dir::new("scale-past");
let mut s = strip();
let limits = "a page holds at most 12000 pixels a side and";
let (said, png) = exported(&mut s, &dir, "png", 150.0);
let (w, h) = png_size(&png);
// What it says of the size is the file's.
let text = format!("{w} × {h} pixels");
assert_eq!(said.len(), 1, "{said:?}");
assert!(said[0].0.starts_with("The PNG is drawn at 60 dpi, not the 150 dpi asked: "), "{said:?}");
assert!(said[0].0.contains(limits) && said[0].0.ends_with(&text), "{said:?}");
assert_eq!(said[0].1, Some(LossCode::ApproximatedResolution));
for ext in ["pdf", "svg"] {
let (said, _) = exported(&mut s, &dir, ext, 150.0);
assert_eq!(said.len(), 1, "{ext}: {said:?}");
let kind = ext.to_ascii_uppercase();
let start = format!("The {kind}'s pictures and the detail of its vectors are drawn at 60 dpi, not the 150 dpi asked: ");
assert!(said[0].0.starts_with(&start) && said[0].0.contains(limits), "{ext}: {said:?}");
assert_eq!(said[0].1, Some(LossCode::ApproximatedResolution), "{ext}");
}
}

#[test]
fn a_layout_export_inside_the_pixel_limit_says_nothing() {
let dir = Dir::new("scale-inside");
let mut s = strip();
// 5000 mm at 60 dpi is 11,811 pixels.
for ext in ["png", "pdf", "svg"] {
assert_eq!(exported(&mut s, &dir, ext, 60.0).0, [], "{ext}");
}
let mut a4 = world();
a4.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap();
for ext in ["png", "pdf", "svg"] {
assert_eq!(exported(&mut a4, &dir, ext, 150.0).0, [], "{ext}");
}
}

#[test]
fn the_assistants_picture_of_a_layout_says_it_for_the_whole_page_only() {
let mut s = strip();
let mark = s.notice_mark();
crate::cmd::layout::layout_png(&mut s, 0, 150.0, None).unwrap();
let said = s.notices_since(mark).iter().filter(|n| n.text.contains("dpi asked")).count();
assert_eq!(said, 1);
// A region has a budget of its own.
let mark = s.notice_mark();
crate::cmd::layout::layout_png(&mut s, 0, 150.0, Some([0.0, 0.0, 100.0, 20.0])).unwrap();
assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("dpi asked")));
}

#[test]
fn a_hostile_dpi_says_it_at_most_once() {
let dir = Dir::new("scale-hostile");
let mut s = strip();
for dpi in [json!("1e400"), json!("x"), json!(-1), json!(1e300)] {
let mark = s.notice_mark();
let _ = s.run("layout.export", &json!({"path": dir.0.join("page.png"), "dpi": dpi}));
let said = s.notices_since(mark).iter().filter(|n| n.text.contains("dpi asked")).count();
assert!(said <= 1, "{dpi}: {said}");
}
}

/// The browser's Export Layout (a download, drawn on a copy of the project) says it with its code,
/// as the desktop's does, and says nothing for a page inside the limit.
#[test]
fn a_browsers_layout_download_says_it() {
let mut s = strip();
s.queue_gp_files = true;
for (dpi, said) in [(150.0, 1), (60.0, 0)] {
for name in ["page.png", "page.pdf", "page.svg"] {
let mark = s.notice_mark();
let pending = s.run("layout.export", &json!({"path": name, "dpi": dpi})).unwrap();
// What drawing it said is said as the browser takes the file.
let files = s.take_gp_files();
assert_eq!(files.len(), 1, "{name}: {pending}");
let _ = s.acknowledge_gp_file(files[0].0, None);
let notes: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("dpi asked")).collect();
assert_eq!(notes.len(), said, "{name} at {dpi}: {notes:?}");
assert!(notes.iter().all(|n| n.loss() == Some(LossCode::ApproximatedResolution)), "{name}");
}
}
}
34 changes: 32 additions & 2 deletions crates/render/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,13 +302,39 @@ fn render_drawing_inner(

/// Page pixel dimensions and the shared millimetre scale, capped to the renderer's budget.
pub(crate) fn page_geometry(layout: &Layout, dpi: f64) -> (u32, u32, f64) {
let ppp = (if dpi.is_finite() { dpi } else { 96.0 } / 96.0).clamp(0.25, 8.0);
let k = PT_PER_MM * ppp;
let k = asked_scale(dpi);
let k = k.min((MAX_PIXELS / (layout.width * layout.height).max(1.0)).sqrt());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The height is scaled by the pixel-area limit only, so a page cut by the side limit keeps the taller scale. For the PR's own example (5000 × 20 mm at 150 dpi), k is cut to 2.4 px/mm by the side limit, but h is still 20 × 54.8 = 118 px, so the PNG is 118 px tall while the page is 48 px. The new notice quotes that 118 as the file's size, which makes the mismatch visible. This predates the PR and the PR says so, but the notice now reports it as fact, and the fix is one line. It changes every side-limited drawing, so it can be a follow-up if you prefer, but the PR should not leave it silent.

Suggested change
let k = k.min((MAX_PIXELS / (layout.width * layout.height).max(1.0)).sqrt());
let k = k.min((MAX_PIXELS / (layout.width * layout.height).max(1.0)).sqrt()).min(MAX_SIDE / layout.width.max(layout.height).max(1e-6));

Category: bug

let (w, h) = ((layout.width * k).clamp(1.0, MAX_SIDE), (layout.height * k).clamp(1.0, MAX_SIDE));
(w as u32, h as u32, k.min(w / layout.width).min(h / layout.height))
}

/// The pixels a millimetre `dpi` asks for, as a page is drawn at it before its budget cuts it.
fn asked_scale(dpi: f64) -> f64 {
PT_PER_MM * (if dpi.is_finite() { dpi } else { 96.0 } / 96.0).clamp(0.25, 8.0)
}

/// What a page's budget ([`MAX_SIDE`], `MAX_PIXELS`) does to an export of `format` ("PNG", "PDF" or
/// "SVG") at `dpi` (#3463): `None` when the page is drawn at the resolution asked, else the
/// notice that it is drawn at a lower one, with that dpi. A page that can't be drawn at all is an
/// error where it is drawn, so it has none.
pub fn page_scale_notice(layout: &Layout, dpi: f64, format: &str) -> Option<String> {
let asked = asked_scale(dpi);
let (w, h, k) = page_geometry(layout, dpi);
// Not `k < asked`: the side limits give `k` back an ulp short on every ordinary page.
if !(k.is_finite() && k > 0.0 && k < asked * (1.0 - 1e-6)) {
return None;
}
let dpi_of = |k: f64| k * 96.0 / PT_PER_MM;
// The dpi drawn at is floored, as Capture To Clipboard says it; the one asked is rounded.
let (drawn, wanted) = (dpi_of(k).floor(), dpi_of(asked).round());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two numbers are rounded differently. drawn is floored and wanted is rounded, and the gate only needs k to be a little below asked. So a request of 150.4 dpi that is cut to about 150.2 gives "drawn at 150 dpi, not the 150 dpi asked", which contradicts itself. Consider showing both with one decimal place (or both floored, and worded so the two can't read as equal), and add a test for a non-integer dpi just above a cut.

Category: quality

let limits = format!("a page holds at most {MAX_SIDE:.0} pixels a side and {:.0} million pixels in all", MAX_PIXELS / 1e6);
Some(if format == "PNG" {
format!("The PNG is drawn at {drawn} dpi, not the {wanted} dpi asked: {limits}, so it is {w} × {h} pixels")
} else {
format!("The {format}'s pictures and the detail of its vectors are drawn at {drawn} dpi, not the {wanted} dpi asked: {limits}")
})
}

/// One element on transparency, allocating only its on-page pixel bounds.
/// Outer `None` means rendering failed; inner `None` means the element is off-page.
/// A fatal source error is retained for the composed SVG's revision check and error report.
Expand Down Expand Up @@ -1343,3 +1369,7 @@ mod tests;
#[cfg(test)]
#[path = "layout/extent_tests.rs"]
mod extent_tests;

#[cfg(test)]
#[path = "layout/page_scale_tests.rs"]
mod page_scale_tests;
99 changes: 99 additions & 0 deletions crates/render/src/layout/page_scale_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
//! The notice for a page drawn at a lower dpi than asked (#3463).

use super::*;

/// Pixels a millimetre at `dpi`, as the page is asked for.
fn asked(dpi: f64) -> f64 {
PT_PER_MM * (dpi / 96.0)
}

fn notice(width: f64, height: f64, dpi: f64, format: &str) -> Option<String> {
page_scale_notice(&Layout::new("Page", width, height), dpi, format)
}

#[test]
fn a_page_inside_the_budget_gives_no_notice() {
for (w, h) in [(210.0, 297.0), (297.0, 420.0), (5000.0, 20.0)] {
for dpi in [72.0, 96.0, 150.0, 300.0] {
// 5000 mm at 150 dpi is past the side limit.
if w * asked(dpi) > MAX_SIDE {
continue;
}
for format in ["PNG", "PDF", "SVG"] {
assert_eq!(notice(w, h, dpi, format), None, "{w} x {h} at {dpi} dpi, {format}");
}
}
}
// A dpi that is not finite is drawn at the default, an extreme one clamped: not what this says.
for dpi in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -5.0, 1e300] {
assert_eq!(notice(20.0, 20.0, dpi, "PNG"), None, "{dpi}");
}
}

#[test]
fn a_page_past_the_side_limit_says_the_dpi_it_is_drawn_at() {
let layout = Layout::new("Strip", 5000.0, 20.0);
let (w, h, _) = page_geometry(&layout, 150.0);
let limits = format!("a page holds at most {MAX_SIDE:.0} pixels a side and {:.0} million pixels in all", MAX_PIXELS / 1e6);
assert_eq!(
page_scale_notice(&layout, 150.0, "PNG").unwrap(),
format!("The PNG is drawn at 60 dpi, not the 150 dpi asked: {limits}, so it is {w} × {h} pixels")
);
for format in ["PDF", "SVG"] {
assert_eq!(
page_scale_notice(&layout, 150.0, format).unwrap(),
format!("The {format}'s pictures and the detail of its vectors are drawn at 60 dpi, not the 150 dpi asked: {limits}")
);
}
}

#[test]
fn a_page_past_the_pixel_budget_says_so() {
// 5000 mm square at 600 dpi: the whole-page budget decides, not a side.
let say = notice(5000.0, 5000.0, 600.0, "PNG").unwrap();
let drawn = ((MAX_PIXELS / (5000.0 * 5000.0)).sqrt() * 96.0 / PT_PER_MM).floor();
assert!(say.starts_with(&format!("The PNG is drawn at {drawn} dpi, not the 600 dpi asked: ")), "{say}");
assert!(say.contains(&format!("{:.0} million pixels in all", MAX_PIXELS / 1e6)), "{say}");
}

/// The notice comes exactly when the page is cut, whatever the size and dpi: floating-point noise
/// in the drawn scale is not a cut.
#[test]
fn the_notice_is_given_exactly_when_the_page_is_cut() {
let sizes = [
(148.0, 210.0),
(210.0, 297.0),
(297.0, 420.0),
(594.0, 841.0),
(841.0, 1189.0),
(5000.0, 20.0),
(20.0, 5000.0),
(20.0, 20.0),
(5000.0, 5000.0),
];
for (w, h) in sizes {
for dpi in [24.0, 36.0, 96.0, 150.0, 300.0, 600.0, 768.0] {
let k = asked(dpi);
let (pw, ph) = (w * k, h * k);
let cut = pw > MAX_SIDE || ph > MAX_SIDE || pw * ph > MAX_PIXELS;
// Skip the knife edge, where either answer is right.
let near = |x: f64, limit: f64| (x / limit - 1.0).abs() < 1e-3;
if near(pw, MAX_SIDE) || near(ph, MAX_SIDE) || near(pw * ph, MAX_PIXELS) {
continue;
}
assert_eq!(notice(w, h, dpi, "PNG").is_some(), cut, "{w} x {h} at {dpi} dpi");
}
}
}

#[test]
fn a_page_that_cannot_be_drawn_says_nothing_of_its_dpi() {
for (w, h) in [(0.0, 0.0), (f64::NAN, 100.0), (100.0, f64::NAN), (f64::MAX, f64::MAX), (1e-300, 1e-300), (f64::INFINITY, 5.0)] {
// No panic; an unusable page is an error where it is drawn, not a lower dpi.
let said = notice(w, h, 150.0, "PNG");
let (_, _, k) = page_geometry(&Layout::new("Page", w, h), 150.0);
if !k.is_finite() || k <= 0.0 {
assert_eq!(said, None, "{w} x {h}");
}
}
}
4 changes: 4 additions & 0 deletions docs/user-guide/layouts.md
Original file line number Diff line number Diff line change
Expand Up @@ -1149,6 +1149,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu
page. In the browser and on phones, **Export** opens a menu: pick the resolution (96, 150 or
300 dpi; 150 at first) and then **PDF**, **PNG** or **SVG**, which downloads the layout in that
format. The `ui.exportLayout` command takes the same choices as `"format"` and `"dpi"`.
A page that would pass 12,000 pixels a side, or 60 million pixels in all (25 million in the
browser), is drawn at a lower dpi, and the export says which, with the loss code
[`approximated.resolution`](loss-codes.md#approximated.resolution): a PNG at that dpi, a PDF's or
SVG's pictures and the detail of its vectors.
**Print** opens the PDF in the system viewer on desktop; **Save Layout File** and
**Import Layout** move layouts between projects (`.rgislayout`).
- **Capture To Clipboard** copies an image of the current page at 192 dpi, with any text still being
Expand Down
8 changes: 8 additions & 0 deletions docs/user-guide/loss-codes.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,14 @@ Curves, circles, rotated boxes or edges that follow the Earth's curve were read,

**What to do:** Keep the source file where exact curves matter: RustGIS draws curves as straight segments.

### `approximated.resolution` { #approximated.resolution }

A page was drawn at a lower resolution than asked, because a page holds at most 12,000 pixels a side and 60 million pixels in all (25 million in the browser).

**Where you see it:** exporting a layout (`layout.export`, Export Layout, Print) or viewing one for the Assistant, when its page at the dpi asked would pass those limits (an A2 page at 300 dpi in the browser). A PNG is drawn at the lower dpi; in a PDF or SVG, its pictures and the detail of its vectors are.

**What to do:** Export a smaller page to keep the resolution asked. When the notice gives 36 dpi or more, you can also ask for that dpi; a lower request is raised to 36 dpi, so the notice comes back.

## Assumed

Assumed means RustGIS had to guess something the data did not say, so the result may be wrong if the guess is.
Expand Down
Loading