From d26011157658dad985d2129a90d673e04f68fc4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 1 Dec 2026 15:29:36 -0500 Subject: [PATCH 1/8] fix(layout): say when a map frame's tile credits are cut off on export --- crates/engine/src/cmd/layout/export.rs | 33 ++++-- crates/engine/src/cmd/report.rs | 58 ++++++++--- crates/engine/src/tests.rs | 3 + crates/engine/src/tests/layout_credits.rs | 120 ++++++++++++++++++++++ crates/render/src/layout.rs | 12 ++- crates/render/src/layout/credit.rs | 88 ++++++++++++++++ crates/render/src/layout/frame.rs | 38 ++++--- crates/render/src/layout/tests.rs | 112 +++++++++++++++++++- crates/render/src/lib.rs | 8 +- 9 files changed, 423 insertions(+), 49 deletions(-) create mode 100644 crates/engine/src/tests/layout_credits.rs create mode 100644 crates/render/src/layout/credit.rs diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index 8cf303e46d..c99f896675 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -109,9 +109,11 @@ pub(super) fn layout_page( if let Some(r) = region { profiles.retain(|n, _| layout.element(n.element).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); } - let ((img, mut unfitted), mut charts) = rustgis_render::layout::drawn_charts(|| { - rustgis_render::layout::unfitted_legends(|| { - crate::cmd::share::saying_shadows(s, "The layout", |s| draw(&layout, &mut s.project.maps, &info)) + let (((img, mut unfitted), mut charts), mut credits) = rustgis_render::layout::cut_credits(|| { + rustgis_render::layout::drawn_charts(|| { + rustgis_render::layout::unfitted_legends(|| { + crate::cmd::share::saying_shadows(s, "The layout", |s| draw(&layout, &mut s.project.maps, &info)) + }) }) }); let img = img?; @@ -121,6 +123,7 @@ pub(super) fn layout_page( cut.retain(|t| layout.element(t.id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); unfitted.retain(|l| layout.element(l.id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); charts.retain(|(id, _)| layout.element(*id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); + credits.retain(|c| layout.element(c.id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); } if let Some(note) = rustgis_render::layout::clipped_text_notice(&layout, &clipped) { s.warn(note); @@ -132,6 +135,9 @@ pub(super) fn layout_page( for note in chart_notice_lines(&layout, &charts) { s.warn(note); } + if let Some(note) = rustgis_render::layout::credit_notice(&credits) { + s.warn(note); + } if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) { s.warn(note); } @@ -339,8 +345,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( // export says them. // And the legends a fit drew that still don't fit, each once, whatever the page. // And what each chart drew, for its notices. - let (((result, said), unfitted), charts) = - rustgis_render::layout::drawn_charts(|| rustgis_render::layout::unfitted_legends(|| rustgis_render::shadows_said(render_pages))); + let ((((result, said), unfitted), charts), credits) = rustgis_render::layout::cut_credits(|| { + rustgis_render::layout::drawn_charts(|| rustgis_render::layout::unfitted_legends(|| rustgis_render::shadows_said(render_pages))) + }); if result.is_ok() { for w in crate::cmd::share::shadow_warnings("The layout", &said) { s.warn(w); @@ -369,6 +376,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( for note in chart_notice_lines(&saved, &charts) { s.warn(note); } + if let Some(note) = rustgis_render::layout::credit_notice(&credits) { + s.warn(note); + } pictured_notices(s, &frames_pictured, &pages_pictured); georeference_notices(s, &left_out, &by_corners, pages.len()); if !pdf { @@ -602,10 +612,12 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd 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(); - let ((drawn, unfitted), charts) = rustgis_render::layout::drawn_charts(|| { - 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 (((drawn, unfitted), charts), credits) = rustgis_render::layout::cut_credits(|| { + rustgis_render::layout::drawn_charts(|| { + 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) + }) }) }) }); @@ -627,6 +639,9 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd for note in chart_notes { s.warn(note); } + if let Some(note) = rustgis_render::layout::credit_notice(&credits) { + s.warn(note); + } pictured_notices(s, &pictured, &[]); Ok(text) } diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 3aa1315bad..d2c0446f64 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1331,7 +1331,7 @@ fn report_pages_bytes( let (mut frames_pictured, mut pages_pictured) = (Vec::new(), Vec::new()); // The legends its layouts' pages drew under a fit still cut, and the charts they drew, by // layout ([`keep_drawn`]). - let (mut unfitted, mut charts) = (Vec::new(), Vec::new()); + let (mut unfitted, mut charts, mut credits) = (Vec::new(), Vec::new(), Vec::new()); // The texts cut off on its layouts' pages, by layout and element. let mut clipped = ClippedTexts::new(); // The tables its layouts' pages cut, by layout. @@ -1356,14 +1356,16 @@ fn report_pages_bytes( } } if !pdf { - let (drawn, listed, shown) = + let (drawn, listed) = listing(|| rustgis_render::report::draw_page(doc, pages, k, dpi, &s.project.layouts, &mut s.project.maps)); let (img, ..) = drawn?; keep_tables(s, &mut tables, page_layout, dpi); - keep_drawn(&mut unfitted, page_layout, listed); - keep_drawn(&mut charts, page_layout, shown); + keep_drawn(&mut unfitted, page_layout, listed.legends); + keep_drawn(&mut charts, page_layout, listed.charts); + keep_drawn(&mut credits, page_layout, listed.credits); say_report_unfitted(s, &unfitted); say_report_charts(s, &charts); + say_report_credits(s, &credits); say_report_clipped(s, &clipped); say_report_tables(s, tables); say_sections_not_drawn(s, pages, 1); @@ -1371,20 +1373,21 @@ fn report_pages_bytes( 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)); + let (drawn, listed) = listing(|| rustgis_render::report::pdf_page(doc, pages, k, dpi, &s.project.layouts, &mut s.project.maps)); let (page, pictured) = drawn?; keep_tables(s, &mut tables, page_layout, dpi); - keep_drawn(&mut unfitted, page_layout, listed); - keep_drawn(&mut charts, page_layout, shown); + keep_drawn(&mut unfitted, page_layout, listed.legends); + keep_drawn(&mut charts, page_layout, listed.charts); + keep_drawn(&mut credits, page_layout, listed.credits); if page.overflowed() { // Too large for vectors all the same: the page as one picture. pages_pictured.push(k + 1); - let (drawn, listed, shown) = + let (drawn, listed) = listing(|| rustgis_render::report::draw_page(doc, pages, k, dpi, &s.project.layouts, &mut s.project.maps)); let (img, w, h) = drawn?; - keep_drawn(&mut unfitted, page_layout, listed); - keep_drawn(&mut charts, page_layout, shown); + keep_drawn(&mut unfitted, page_layout, listed.legends); + keep_drawn(&mut charts, page_layout, listed.charts); + keep_drawn(&mut credits, page_layout, listed.credits); out.push(rustgis_render::pdf::Page::new(&img, w, h)); } else { frames_pictured.extend(pictured); @@ -1403,6 +1406,7 @@ fn report_pages_bytes( } say_report_unfitted(s, &unfitted); say_report_charts(s, &charts); + say_report_credits(s, &credits); say_report_clipped(s, &clipped); super::layout::pictured_notices(s, &frames_pictured, &pages_pictured); say_report_tables(s, tables); @@ -1504,11 +1508,19 @@ fn say_report_pictures(s: &mut Session, pages: &[rustgis_render::report::Page], super::layout::say_pictures_not_drawn(s, &gaps, "The report: "); } -/// Runs `f`, and returns its result with the legends it drew under a fit still cut and the charts -/// it drew. -fn listing(f: impl FnOnce() -> T) -> (T, Vec, Vec) { - let ((drawn, legends), charts) = rustgis_render::layout::drawn_charts(|| rustgis_render::layout::unfitted_legends(f)); - (drawn, legends, charts) +/// What a page drew that its report says: legends under a fit still cut, charts, and map frames +/// whose tile credits are cut off. +struct Listed { + legends: Vec, + charts: Vec, + credits: Vec, +} + +/// Runs `f`, and returns its result with what it drew that its report says. +fn listing(f: impl FnOnce() -> T) -> (T, Listed) { + let (((drawn, legends), charts), credits) = + rustgis_render::layout::cut_credits(|| rustgis_render::layout::drawn_charts(|| rustgis_render::layout::unfitted_legends(f))); + (drawn, Listed { legends, charts, credits }) } /// Keeps what a page that draws the layout `layout` (by its index) `listed`, a legend cut under @@ -1543,6 +1555,20 @@ fn say_report_charts(s: &mut Session, kept: &[(usize, rustgis_render::layout::Dr } } +/// Says the map frames whose tile credits [`keep_drawn`] kept as cut off, each named with its +/// layout, as a layout's export says its own: one notice however many layouts have one. +fn say_report_credits(s: &mut Session, kept: &[(usize, rustgis_render::layout::CutCredit)]) { + let found: Vec<_> = kept + .iter() + .filter_map(|(li, c)| { + Some(rustgis_render::layout::CutCredit { layout: Some(s.project.layouts.get(*li)?.name.clone()), ..c.clone() }) + }) + .collect(); + if let Some(note) = rustgis_render::layout::credit_notice(&found) { + s.warn(format!("The report: {note}")); + } +} + /// The texts cut off on a report's layout pages: each layout's (by its index) elements, by id. type ClippedTexts = std::collections::BTreeMap>; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0c47c64466..fc255f610c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -146,6 +146,9 @@ mod layout_panel_cut; #[path = "tests/layout_chart_notices.rs"] mod layout_chart_notices; +#[path = "tests/layout_credits.rs"] +mod layout_credits; + #[path = "tests/layout_publication_parts.rs"] mod layout_publication_parts; diff --git a/crates/engine/src/tests/layout_credits.rs b/crates/engine/src/tests/layout_credits.rs new file mode 100644 index 0000000000..afd35840e7 --- /dev/null +++ b/crates/engine/src/tests/layout_credits.rs @@ -0,0 +1,120 @@ +//! A map frame whose tile credits don't fit in it says so on export (#3474). + +use super::*; + +const CREDIT: &str = "© A tile provider whose credit is longer than a small map frame holds"; +const ADVICE: &str = "its tile credits don't fit in it, so their ends are cut off; make it larger, or show fewer tile layers in it"; + +/// A temporary directory of this thread's, removed however the test ends. +struct Dir(std::path::PathBuf); + +impl Dir { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("rustgis-3474-{tag}-{}-{:?}", std::process::id(), std::thread::current().id())); + std::fs::create_dir_all(&dir).unwrap(); + Dir(dir) + } +} + +impl Drop for Dir { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } +} + +/// The world with a one-tile MBTiles layer crediting `CREDIT`, and a blank layout "Credits". +fn credited(dir: &Dir) -> Session { + let path = dir.0.join("tiles.mbtiles"); + let mut tile = tiny_skia::Pixmap::new(256, 256).unwrap(); + tile.fill(tiny_skia::Color::from_rgba8(200, 220, 240, 255)); + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute_batch( + "CREATE TABLE metadata (name text, value text); CREATE TABLE tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob); + INSERT INTO metadata VALUES ('name', 'Blue'), ('format', 'png'), ('minzoom', '0'), ('maxzoom', '0');", + ) + .unwrap(); + db.execute("INSERT INTO metadata VALUES ('attribution', ?1)", [CREDIT]).unwrap(); + db.execute("INSERT INTO tiles VALUES (0, 0, 0, ?1)", [tile.encode_png().unwrap()]).unwrap(); + drop(db); + let mut s = world(); + s.run("layer.addData", &json!({"path": path})).unwrap(); + s.run("layout.new", &json!({"name": "Credits", "template": "blank"})).unwrap(); + s +} + +/// Adds a map frame `w` mm wide, zoomed to everything; its element id. +fn frame(s: &mut Session, x: f64, w: f64) -> u64 { + let id = s.run("layout.addFrame", &json!({"x": x, "y": 20, "w": w, "h": 60})).unwrap()["element"].as_u64().unwrap(); + s.run("layout.frameZoom", &json!({"element": id, "to": "full"})).unwrap(); + id +} + +/// What exporting the layout to a file of `ext` says of its credits. +fn exported(s: &mut Session, dir: &Dir, ext: &str) -> Vec { + let mark = s.notice_mark(); + s.run("layout.export", &json!({"path": dir.0.join(format!("page.{ext}")), "dpi": 36})).unwrap(); + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("tile credits")).collect() +} + +fn named(s: &Session, id: u64) -> String { + let name = &s.project.layouts.last().unwrap().element(id as u32).unwrap().name; + format!("\"{name}\" ({id})") +} + +#[test] +fn a_frame_that_holds_its_credit_says_nothing() { + let dir = Dir::new("whole"); + let mut s = credited(&dir); + frame(&mut s, 10.0, 200.0); + for ext in ["png", "svg", "pdf"] { + assert_eq!(exported(&mut s, &dir, ext), Vec::::new(), "{ext}"); + } +} + +#[test] +fn a_frame_narrower_than_its_credit_says_so_on_every_export() { + let dir = Dir::new("narrow"); + let mut s = credited(&dir); + let id = frame(&mut s, 10.0, 20.0); + for ext in ["png", "svg", "pdf"] { + let said = exported(&mut s, &dir, ext); + assert_eq!(said, [format!("Map frame {}: {ADVICE}", named(&s, id))], "{ext}"); + } +} + +#[test] +fn two_narrow_frames_are_said_in_one_notice() { + let dir = Dir::new("two"); + let mut s = credited(&dir); + let (a, b) = (frame(&mut s, 10.0, 20.0), frame(&mut s, 40.0, 20.0)); + let said = exported(&mut s, &dir, "png"); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("2 map frames don't hold their tile credits"), "{said:?}"); + assert!(said[0].contains(&format!("{}; {}", named(&s, a), named(&s, b))), "{said:?}"); +} + +#[test] +fn a_frame_without_tile_layers_says_nothing() { + let mut s = world(); + s.run("layout.new", &json!({"name": "Plain", "template": "blank"})).unwrap(); + frame(&mut s, 10.0, 20.0); + let dir = Dir::new("plain"); + assert_eq!(exported(&mut s, &dir, "png"), Vec::::new()); +} + +#[test] +fn a_report_names_the_layout_whose_frame_cuts_its_credit() { + let dir = Dir::new("report"); + let mut s = credited(&dir); + let id = frame(&mut s, 10.0, 20.0); + s.run("report.new", &json!({"layer": "Countries", "name": "R"})).unwrap(); + s.run("report.existingTemplate", &json!({"report": "R", "layout": "Credits", "end": true})).unwrap(); + // A PNG is the report's first page, which is not this layout's (it follows the report's own). + for ext in ["pdf"] { + let mark = s.notice_mark(); + s.run("report.export", &json!({"report": "R", "path": dir.0.join(format!("r.{ext}")), "dpi": 36})).unwrap(); + let said: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("tile credits")).collect(); + let name = &s.project.layouts.last().unwrap().element(id as u32).unwrap().name; + assert_eq!(said, [format!("The report: Map frame \"{name}\" ({id}) in \"Credits\": {ADVICE}")], "{ext}"); + } +} diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index c7177a609e..0e928abad8 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -22,6 +22,7 @@ use crate::{View, paint, point_marks, text}; mod chart; mod colorbar; mod coverage; +mod credit; mod dynamic_text; mod frame; mod grid; @@ -39,6 +40,7 @@ mod textbox; pub use chart::*; pub use colorbar::*; pub use coverage::*; +pub use credit::*; pub use dynamic_text::*; pub use frame::*; pub use grid::*; @@ -472,7 +474,9 @@ fn draw_page( sections.iter().filter_map(|s| Some((s, section_ends(map, &cam, (fw, fh), shape, s.line).ok()?))).collect(); let over = FrameOver { grid, sections: §ions, shape: Some(shape) }; let mut failed_source = None; - let Some(mut frame_pm) = frame_canvas(map, &view, pm.is_recording(), &mut pending.frames, over, &mut failed_source, env) + let mut cut_here = false; + let Some(mut frame_pm) = + frame_canvas(map, &view, pm.is_recording(), (&mut pending.frames, &mut cut_here), over, &mut failed_source, env) else { if frame_requires_complete(map, &view) { *source_error = failed_source_error(map, failed_source); @@ -487,13 +491,17 @@ fn draw_page( frame_pm.overflowed() || pm.recorded_cost().saturating_add(frame_pm.recorded_cost()) > crate::vector::max_cost(); if frame_pm.is_recording() && too_large - && let Some(pixels) = frame_canvas(map, &view, false, &mut pending.frames, over, &mut None, env) + && let Some(pixels) = frame_canvas(map, &view, false, (&mut pending.frames, &mut cut_here), over, &mut None, env) { frame_pm = pixels; if let Some(list) = record.as_deref_mut() { list.push((e.id, e.name.clone())); } } + // Its tile credits' ends cut off, for an export to say ([`cut_credits`]). + if cut_here { + credit_cut(e.id, &e.name); + } // The extent indicators, in order, a later one over an earlier one. let mut numbers = Vec::new(); for (n, i) in e.kind.extent_indicators().into_iter().enumerate() { diff --git a/crates/render/src/layout/credit.rs b/crates/render/src/layout/credit.rs new file mode 100644 index 0000000000..68abceec03 --- /dev/null +++ b/crates/render/src/layout/credit.rs @@ -0,0 +1,88 @@ +//! The map frames whose tile credits don't fit in them (#3474). + +use super::*; + +/// A map frame a page drew whose tile credits don't fit in it ([`cut_credits`]): its element's id +/// and name, and in a report its layout's name. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CutCredit { + pub id: u32, + pub name: String, + /// Its layout's name, said with it: set by a report, whose pages draw several. + pub layout: Option, +} + +thread_local! { + /// While [`cut_credits`] runs on this thread: the frames drawn whose credits were cut, each + /// once. + static CUT: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Ends the list [`cut_credits`] opened when dropped, even by a panic. +struct CutList(bool); + +impl Drop for CutList { + fn drop(&mut self) { + if self.0 { + CUT.set(None); + } + } +} + +/// `f`, and the map frames the pages it drew on this thread drew with their tile credits cut off +/// (the credit is wider than the frame, or than every row of its shape), each once, in the order +/// first drawn: what an export says of them. The credits are known only as the frame is drawn, so +/// this costs nothing besides the drawing. A call inside another lists nothing and leaves its +/// frames to the outer one. +pub fn cut_credits(f: impl FnOnce() -> T) -> (T, Vec) { + let opened = CUT.with_borrow_mut(|c| { + let none = c.is_none(); + if none { + *c = Some(Vec::new()); + } + none + }); + let _list = CutList(opened); + let out = f(); + let listed = if opened { CUT.with_borrow_mut(Option::take).unwrap_or_default() } else { Vec::new() }; + (out, listed) +} + +/// Lists the frame `id` named `name` as drawn with its credits cut, while [`cut_credits`] runs. +pub(super) fn credit_cut(id: u32, name: &str) { + CUT.with_borrow_mut(|c| { + if let Some(listed) = c + && !listed.iter().any(|l| l.id == id) + { + listed.push(CutCredit { id, name: name.to_string(), layout: None }); + } + }); +} + +/// A frame as a notice names it: by name and id, and in a report by its layout. +fn named(c: &CutCredit) -> String { + let layout = c.layout.as_ref().map(|l| format!(" in \"{}\"", notice_cut(l))).unwrap_or_default(); + format!("\"{}\" ({}){layout}", notice_cut(&c.name), c.id) +} + +/// What to say of the frames [`cut_credits`] found: one notice, each frame by name and id (the +/// first ten, and how many more). `None` when there are none. +pub fn credit_notice(found: &[CutCredit]) -> Option { + match found { + [] => None, + [c] => Some(format!( + "Map frame {}: its tile credits don't fit in it, so their ends are cut off; make it larger, or show fewer tile layers in it", + named(c) + )), + _ => { + let mut each = found.iter().take(10).map(named).collect::>().join("; "); + if found.len() > 10 { + each.push_str(&format!("; and {} more", found.len() - 10)); + } + Some(format!( + "{} map frames don't hold their tile credits, so their ends are cut off: {each}; make them larger, or show fewer tile layers in them", + found.len() + )) + } + } +} diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs index 9984999954..0b6dc32c2d 100644 --- a/crates/render/src/layout/frame.rs +++ b/crates/render/src/layout/frame.rs @@ -10,7 +10,8 @@ pub fn frame_map(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp let mut failed_source = None; let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; let over = FrameOver::default(); - let result = frame_canvas(map, &view, false, &mut false, over, &mut failed_source, &Env::default()).map(Canvas::into_pixmap); + let result = + frame_canvas(map, &view, false, (&mut false, &mut false), over, &mut failed_source, &Env::default()).map(Canvas::into_pixmap); revisions.finish(map, failed_source, result, "could not draw the map frame") } @@ -29,12 +30,13 @@ pub(super) struct FrameOver<'a> { /// frame can be kept as vectors (flat, north up, without view effects), else its pixels; with /// what goes `over` it drawn on it under the attribution. /// `pending` is set when some of its tiles, or a read of its streamed layers or rasters, were -/// still on their way (in the browser, which doesn't wait for them). +/// still on their way (in the browser, which doesn't wait for them); `cut` when its tile credits +/// don't fit in it ([`finish_frame`]). pub(super) fn frame_canvas( map: &mut Map, view: &View, record: bool, - pending: &mut bool, + (pending, cut): (&mut bool, &mut bool), over: FrameOver, failed_source: &mut Option, env: &Env, @@ -45,7 +47,9 @@ pub(super) fn frame_canvas( let img = img?; *pending |= img.tiles_pending || img.data_pending || shadows; let grid = over.grid.map(|(g, comma)| (&*map, view, g, comma)); - Some(finish_frame(img, view.pixels_per_point, grid, over.sections, over.shape)) + let (canvas, cut_here) = finish_frame(img, view.pixels_per_point, grid, over.sections, over.shape); + *cut |= cut_here; + Some(canvas) } /// [`frame_map`] without waiting for tiles still on their way, for a preview drawn while the @@ -58,20 +62,20 @@ pub fn frame_map_preview(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: /// Map preview during a layout pan, using the same expression context as its page. pub fn frame_map_preview_with(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: f64, ppp: f64, env: &Env) -> Option { let view = View { width: w, height: h, pixels_per_point: ppp, camera, sky: false }; - crate::render_cpu(map, &view, false, false, &mut None, env).map(|img| finish_frame(img, ppp, None, &[], None).into_pixmap()) + crate::render_cpu(map, &view, false, false, &mut None, env).map(|img| finish_frame(img, ppp, None, &[], None).0.into_pixmap()) } /// A rendered frame map with its labels, its `grid` (drawn on `map` in `view`, with a decimal /// comma or not), its section lines and its attribution drawn on it: on its recording when it was /// recorded, else on its pixels. The attribution keeps clear of the grid's labels and the sections' -/// names. +/// names. Also whether the attribution doesn't fit in the frame, so that its ends are cut off. pub(super) fn finish_frame( img: crate::Rendered, ppp: f64, grid: Option<(&Map, &View, &Grid, bool)>, sections: &[(&Section, SectionEnds)], shape: Option<&FrameShape>, -) -> Canvas { +) -> (Canvas, bool) { let crate::Rendered { pixmap, recorded, labels, unplaced, label_layers, attribution, .. } = img; let mut pm = recorded.unwrap_or_else(|| Canvas::from_pixmap(pixmap)); crate::draw_labels(&mut pm, (&unplaced, &labels, &label_layers), ppp as f32); @@ -83,12 +87,12 @@ pub(super) fn finish_frame( kept_clear.extend(draw_sections(&mut pm, sections, ppp)); pm.layer(None); let (w, h) = (pm.width() as f32 / ppp as f32, pm.height() as f32 / ppp as f32); - let inset = crate::attribution_text(&attribution).map_or((0.0, 0.0), |(_, tw)| match shape { + let (inset, cut) = crate::attribution_text(&attribution).map_or(((0.0, 0.0), false), |(_, tw)| match shape { Some(s) if !matches!(s, FrameShape::Rectangle) => attribution_in_shape((w, h), tw, s, &kept_clear), - _ => attribution_inset((w, h), tw, &kept_clear), + _ => (attribution_inset((w, h), tw, &kept_clear), tw > w), }); crate::draw_attribution(&mut pm, &attribution, ppp as f32, inset); - pm + (pm, cut) } /// How far further in (up from the bottom, in from the right, in points) the attribution `tw` @@ -145,15 +149,16 @@ pub(super) fn attribution_mask_scale((w, h): (f32, f32)) -> f32 { /// every one of the `labels`, against the right end of its room there. One that no row holds so /// is centred on the widest room clear of them (of rows with none, on the widest inside the /// shape), the lowest of those as wide; on a shape lower than the credit everywhere, which has -/// no such row, it lies across the shape's middle. -pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]) -> (f32, f32) { +/// no such row, it lies across the shape's middle. Also whether it is cut off: no room of the +/// shape, clear of the labels or not, is as long as it. +pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]) -> ((f32, f32), bool) { let size = crate::ATTRIBUTION_SIZE; // The shape at a cell a point (fewer on a huge frame), cut as the frame's drawing is // ([`shape_path`]). let scale = attribution_mask_scale((w, h)); let (cols, rows) = ((w * scale).ceil().max(1.0) as u32, (h * scale).ceil().max(1.0) as u32); - let Some(mut mask) = Mask::new(cols, rows) else { return (0.0, 0.0) }; - let Some(path) = Rect::from_xywh(0.0, 0.0, w, h).and_then(|r| shape_path(shape, r)) else { return (0.0, 0.0) }; + let Some(mut mask) = Mask::new(cols, rows) else { return ((0.0, 0.0), false) }; + let Some(path) = Rect::from_xywh(0.0, 0.0, w, h).and_then(|r| shape_path(shape, r)) else { return ((0.0, 0.0), false) }; mask.fill_path(&path, FillRule::Winding, true, Transform::from_scale(scale, scale)); // The rows the credit takes, its halo included, and the gaps at its right and from a label. let band = ((size * 1.6 * scale).ceil() as u32).min(rows); @@ -207,7 +212,10 @@ pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameSha None => (widest.1 / scale, widest.2), }; let cy = (foot - band as f32 / 2.0) / scale; - (h - size * 0.9 - cy, w - cx - tw.min(w) / 2.0 - margin) + // Cut off when no row holds it, and the room it is centred on is shorter than it. + let room_there = widest.0.0.max(widest.0.1) as f32; + let cut = lowest.is_none() && room_there < tw * scale; + ((h - size * 0.9 - cy, w - cx - tw.min(w) / 2.0 - margin), cut) } pub(super) fn shape_path(shape: &FrameShape, r: Rect) -> Option { diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index fa5dd0a6e7..ebfaa3be2b 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6264,7 +6264,7 @@ fn a_frames_attribution_keeps_clear_of_its_grid_labels() { recorded: None, label_layers: Vec::new(), }; - let framed = finish_frame(img, ppp, Some((&map, &view, &all, false)), &[], None); + let framed = finish_frame(img, ppp, Some((&map, &view, &all, false)), &[], None).0; let (a, b) = (labels_pm.pixmap(), framed.pixmap()); assert_ne!(a.data(), b.data(), "the credit is drawn"); for (_, [x0, y0, x1, y1]) in &labels { @@ -6295,7 +6295,7 @@ fn credit_pixels((w, h): (f32, f32), credit: &str, shape: &FrameShape) -> Vec<(u recorded: None, label_layers: Vec::new(), }; - let framed = finish_frame(img, f64::from(ppp), None, &[], Some(shape)); + let framed = finish_frame(img, f64::from(ppp), None, &[], Some(shape)).0; let pm = framed.pixmap(); let mut mask = Mask::new(pm.width(), pm.height()).unwrap(); let path = shape_path(shape, Rect::from_xywh(0.0, 0.0, w * ppp, h * ppp).unwrap()).unwrap(); @@ -6338,7 +6338,7 @@ fn a_shaped_frames_attribution_stays_inside_its_shape() { fn a_shaped_frames_attribution_takes_the_lowest_row_that_holds_it() { let size = crate::ATTRIBUTION_SIZE; let place = |(w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]| { - let (bottom, right) = attribution_in_shape((w, h), tw, shape, labels); + let ((bottom, right), _) = attribution_in_shape((w, h), tw, shape, labels); (crate::attribution_center(w, tw, right), h - bottom - size * 0.9) }; let (_, circle) = place((142.0, 142.0), 100.0, &FrameShape::Circle, &[]); @@ -6392,7 +6392,7 @@ fn a_huge_shaped_frames_attribution_is_placed_within_the_cell_budget() { assert!((side * scale).ceil().powi(2) <= 1.01 * ATTRIBUTION_MASK_CELLS, "{scale}"); assert_eq!(attribution_mask_scale((227.0, 227.0)), 1.0, "a point a cell on an ordinary frame"); let (tw, size) = (175.0, crate::ATTRIBUTION_SIZE); - let (bottom, right) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &[]); + let ((bottom, right), _) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &[]); let (cx, cy) = (crate::attribution_center(side, tw, right), side - bottom - size * 0.9); let r = side / 2.0; for (dx, dy) in [(-0.5, -0.8), (0.5, -0.8), (-0.5, 0.8), (0.5, 0.8)] { @@ -6402,6 +6402,110 @@ fn a_huge_shaped_frames_attribution_is_placed_within_the_cell_budget() { assert!(cy > side * 0.95, "near the circle's foot: {cy}"); } +/// Whether finishing a `w` × `h` point frame in `shape` (a rectangle for none) says its `credit` +/// is cut off (#3474). +fn credit_is_cut((w, h): (f32, f32), credit: &[String], shape: Option<&FrameShape>) -> bool { + let ppp = 2.0f32; + let mut pm = Pixmap::new((w * ppp) as u32, (h * ppp) as u32).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let img = crate::Rendered { + pixmap: pm, + labels: Vec::new(), + unplaced: Vec::new(), + attribution: credit.to_vec(), + tiles_pending: false, + data_pending: false, + tile_errors: Vec::new(), + absent: Vec::new(), + partial: Vec::new(), + pending_in_place: Vec::new(), + recorded: None, + label_layers: Vec::new(), + }; + finish_frame(img, f64::from(ppp), None, &[], shape).1 +} + +/// A frame says its credit is cut off exactly when no place in it holds all of it (#3474): a +/// rectangle narrower than the credit, a shape with no row as wide; never one that holds it, nor +/// one with no credit. +#[test] +fn a_frame_says_when_its_attribution_is_cut_off() { + let one = vec!["© OpenStreetMap contributors".to_string()]; + let tw = crate::attribution_text(&one).unwrap().1; + let two = vec![one[0].clone(), "Instituto Brasileiro de Geografia e Estatística".to_string()]; + // A rectangle: wider than the frame is cut; as wide as it, or with the margin to spare, is not. + assert!(credit_is_cut((tw - 10.0, 100.0), &one, None)); + assert!(credit_is_cut((tw - 1.0, 100.0), &one, None)); + assert!(!credit_is_cut((tw.ceil(), 100.0), &one, None)); + assert!(!credit_is_cut((tw + 2.0, 100.0), &one, None)); + assert!(!credit_is_cut((tw + 50.0, 100.0), &one, Some(&FrameShape::Rectangle))); + // Two credits side by side in a frame that holds one. + assert!(credit_is_cut((tw + 50.0, 100.0), &two, None)); + // No credit, nothing to cut. + assert!(!credit_is_cut((20.0, 20.0), &[], None)); + // A shape: a circle that holds it on its widest rows, and one too small for any. + assert!(!credit_is_cut((227.0, 227.0), &one, Some(&FrameShape::Circle))); + assert!(credit_is_cut((60.0, 60.0), &one, Some(&FrameShape::Circle))); + assert!(credit_is_cut((227.0, 227.0), &two, Some(&FrameShape::Circle))); + // A shape lower than the credit everywhere. + assert!(credit_is_cut((300.0, 4.0), &one, Some(&FrameShape::Ellipse))); + // A triangle pointing down: the credit sits up the map, where it fits. + let down = FrameShape::Polygon(vec![(0.0, 0.0), (1.0, 0.0), (0.5, 1.0)]); + assert!(!credit_is_cut((227.0, 227.0), &one, Some(&down))); +} + +/// A credit that fits the frame within its right margin is drawn whole, nudged into the margin, +/// where it was cut by the margin's width (#3474); one wider than the frame is centred on it. +#[test] +fn a_credit_within_a_margin_of_the_frames_width_is_drawn_whole() { + let half = |tw: f32| tw / 2.0; + for (w, tw) in [(100.0, 98.0), (100.0, 96.0), (100.0, 100.0), (100.0, 60.0)] { + let centre = crate::attribution_center(w, tw, 0.0); + assert!(centre - half(tw) >= -1e-3 && centre + half(tw) <= w + 1e-3, "w {w}, tw {tw}: centred at {centre}"); + } + // With room, it keeps its margin. + assert!((crate::attribution_center(100.0, 60.0, 0.0) - (100.0 - 4.0 - 30.0)).abs() < 1e-3); + // Wider than the frame: centred, running past both edges alike. + assert!((crate::attribution_center(100.0, 140.0, 0.0) - 50.0).abs() < 1e-3); +} + +/// `cut_credits` lists each frame once, in the order first drawn; a call inside another lists +/// nothing and leaves its frames to the outer one; nothing is kept outside one. +#[test] +fn cut_credits_lists_each_frame_once() { + credit_cut(9, "Outside"); + let ((), found) = cut_credits(|| { + credit_cut(3, "North"); + credit_cut(5, "South"); + credit_cut(3, "North"); + let ((), inner) = cut_credits(|| credit_cut(7, "East")); + assert!(inner.is_empty()); + }); + let ids: Vec<_> = found.iter().map(|c| c.id).collect(); + assert_eq!(ids, [3, 5, 7]); + let ((), after) = cut_credits(|| ()); + assert!(after.is_empty(), "{after:?}"); +} + +/// What an export says of the frames whose credits are cut: one notice, each named, the first ten +/// and how many more (#3474). +#[test] +fn the_notice_names_the_frames_whose_credits_are_cut() { + let frame = |id: u32, layout: Option<&str>| CutCredit { id, name: format!("Map {id}"), layout: layout.map(str::to_string) }; + assert_eq!(credit_notice(&[]), None); + assert_eq!( + credit_notice(&[frame(3, None)]).unwrap(), + "Map frame \"Map 3\" (3): its tile credits don't fit in it, so their ends are cut off; make it larger, or show fewer tile layers in it" + ); + let two = credit_notice(&[frame(3, Some("Atlas")), frame(4, Some("Atlas"))]).unwrap(); + assert!(two.starts_with("2 map frames don't hold their tile credits"), "{two}"); + assert!(two.contains("\"Map 3\" (3) in \"Atlas\"; \"Map 4\" (4) in \"Atlas\""), "{two}"); + let many: Vec<_> = (1..=12).map(|i| frame(i, None)).collect(); + let note = credit_notice(&many).unwrap(); + assert!(note.starts_with("12 map frames") && note.contains("\"Map 10\" (10); and 2 more"), "{note}"); + assert!(!note.contains("(11)"), "{note}"); +} + /// The credit stays in the corner with nothing under it, goes up above a bottom label and left /// of a right one (above it, when going left would take it out of the frame), and pays no heed /// to the top and left labels. diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index edc8d646ec..4e81411bf1 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -9665,10 +9665,12 @@ pub(crate) fn attribution_text(attribution: &[String]) -> Option<(String, f32)> } /// Where [`draw_attribution`] centres a credit `tw` points wide across a canvas `w` points wide, -/// `right` points further in from its right edge: one wider than the canvas is centred as if it -/// were the canvas's width, so it runs past both edges. +/// `right` points further in from its right edge: one that fits the canvas but not with its margin +/// goes into the margin rather than past the left edge; one wider than the canvas is centred on +/// it, so it runs past both edges. pub(crate) fn attribution_center(w: f32, tw: f32, right: f32) -> f32 { - w - right - tw.min(w) / 2.0 - ATTRIBUTION_MARGIN + let half = tw.min(w) / 2.0; + (w - right - half - ATTRIBUTION_MARGIN).max(half) } /// The tile layers' credits, small, in the bottom-right corner: `inset` points further in (up From 6fdd13a31605373861f7c40414e56b158215d383 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 1 Dec 2026 15:52:34 -0500 Subject: [PATCH 2/8] fix(layout): count a shape's credit as cut only when no row holds it --- crates/engine/src/cmd/report.rs | 4 +--- crates/engine/src/tests/layout_credits.rs | 14 ++++++-------- crates/render/src/layout/frame.rs | 14 +++++++++----- crates/render/src/layout/tests.rs | 17 +++++++++++++++++ 4 files changed, 33 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index d2c0446f64..2271d4b5fa 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1560,9 +1560,7 @@ fn say_report_charts(s: &mut Session, kept: &[(usize, rustgis_render::layout::Dr fn say_report_credits(s: &mut Session, kept: &[(usize, rustgis_render::layout::CutCredit)]) { let found: Vec<_> = kept .iter() - .filter_map(|(li, c)| { - Some(rustgis_render::layout::CutCredit { layout: Some(s.project.layouts.get(*li)?.name.clone()), ..c.clone() }) - }) + .map(|(li, c)| rustgis_render::layout::CutCredit { layout: s.project.layouts.get(*li).map(|l| l.name.clone()), ..c.clone() }) .collect(); if let Some(note) = rustgis_render::layout::credit_notice(&found) { s.warn(format!("The report: {note}")); diff --git a/crates/engine/src/tests/layout_credits.rs b/crates/engine/src/tests/layout_credits.rs index afd35840e7..680c1e08b2 100644 --- a/crates/engine/src/tests/layout_credits.rs +++ b/crates/engine/src/tests/layout_credits.rs @@ -109,12 +109,10 @@ fn a_report_names_the_layout_whose_frame_cuts_its_credit() { let id = frame(&mut s, 10.0, 20.0); s.run("report.new", &json!({"layer": "Countries", "name": "R"})).unwrap(); s.run("report.existingTemplate", &json!({"report": "R", "layout": "Credits", "end": true})).unwrap(); - // A PNG is the report's first page, which is not this layout's (it follows the report's own). - for ext in ["pdf"] { - let mark = s.notice_mark(); - s.run("report.export", &json!({"report": "R", "path": dir.0.join(format!("r.{ext}")), "dpi": 36})).unwrap(); - let said: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("tile credits")).collect(); - let name = &s.project.layouts.last().unwrap().element(id as u32).unwrap().name; - assert_eq!(said, [format!("The report: Map frame \"{name}\" ({id}) in \"Credits\": {ADVICE}")], "{ext}"); - } + // A PDF: a PNG is the report's first page, which is not this layout's (it follows the report's own). + let mark = s.notice_mark(); + s.run("report.export", &json!({"report": "R", "path": dir.0.join("r.pdf"), "dpi": 36})).unwrap(); + let said: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("tile credits")).collect(); + let name = &s.project.layouts.last().unwrap().element(id as u32).unwrap().name; + assert_eq!(said, [format!("The report: Map frame \"{name}\" ({id}) in \"Credits\": {ADVICE}")]); } diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs index 0b6dc32c2d..0fdbde1f05 100644 --- a/crates/render/src/layout/frame.rs +++ b/crates/render/src/layout/frame.rs @@ -149,8 +149,8 @@ pub(super) fn attribution_mask_scale((w, h): (f32, f32)) -> f32 { /// every one of the `labels`, against the right end of its room there. One that no row holds so /// is centred on the widest room clear of them (of rows with none, on the widest inside the /// shape), the lowest of those as wide; on a shape lower than the credit everywhere, which has -/// no such row, it lies across the shape's middle. Also whether it is cut off: no room of the -/// shape, clear of the labels or not, is as long as it. +/// no such row, it lies across the shape's middle. Also whether it is cut off: no row of the shape, +/// clear of the labels or not, is as long as it. pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]) -> ((f32, f32), bool) { let size = crate::ATTRIBUTION_SIZE; // The shape at a cell a point (fewer on a huge frame), cut as the frame's drawing is @@ -172,6 +172,9 @@ pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameSha let middle = path.bounds(); let across = ((middle.left() + middle.right()) / 2.0 * scale, (middle.top() + middle.bottom()) / 2.0 * scale + band as f32 / 2.0); let (mut lowest, mut widest) = (None, ((0u32, 0u32), across.0, across.1)); + // The longest run of columns inside the shape, labels or not, on any row the credit's height + // fits: if it is shorter than the credit, no place in the shape holds it. + let mut longest = 0u32; for (y, line) in mask.data().chunks_exact(cols as usize).enumerate() { for (n, &a) in inside.iter_mut().zip(line) { // Wholly inside: a cell half covered would let the credit past the edge by half a cell. @@ -194,6 +197,7 @@ pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameSha let full = n >= band; let x = x as f32; run = if full { run + 1 } else { 0 }; + longest = longest.max(run); free = if full && !in_row.iter().any(|b| x < b[2] && b[0] < x + 1.0) { free + 1 } else { 0 }; let found = (free, if free == 0 { run } else { 0 }); if run > 0 && (found > widest.0 || (found == widest.0 && foot > widest.2)) { @@ -212,9 +216,9 @@ pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameSha None => (widest.1 / scale, widest.2), }; let cy = (foot - band as f32 / 2.0) / scale; - // Cut off when no row holds it, and the room it is centred on is shorter than it. - let room_there = widest.0.0.max(widest.0.1) as f32; - let cut = lowest.is_none() && room_there < tw * scale; + // Cut off when no row of the shape is as long as it (a label over the rows that are only + // overlaps it, which isn't cutting it). + let cut = (longest as f32) < tw * scale; ((h - size * 0.9 - cy, w - cx - tw.min(w) / 2.0 - margin), cut) } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index ebfaa3be2b..3ec79e116d 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6454,6 +6454,23 @@ fn a_frame_says_when_its_attribution_is_cut_off() { assert!(!credit_is_cut((227.0, 227.0), &one, Some(&down))); } +/// A label over the rows of a shape that hold the credit leaves the credit over it, not cut off: +/// only a shape with no row as long as the credit cuts it (#3474). +#[test] +fn a_label_over_the_rows_that_hold_the_credit_isnt_a_cut() { + let one = vec!["© OpenStreetMap contributors".to_string()]; + let tw = crate::attribution_text(&one).unwrap().1; + // A circle just wide enough for the credit across its middle rows only. + let side = (tw + 12.0).ceil(); + let band = [(Edge::Bottom, [0.0, side * 0.3, side, side * 0.7])]; + let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &band); + assert!(!cut, "the middle rows hold it, under the label"); + let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &[]); + assert!(!cut); + let (_, cut) = attribution_in_shape((tw - 10.0, tw - 10.0), tw, &FrameShape::Circle, &band); + assert!(cut, "no row holds it"); +} + /// A credit that fits the frame within its right margin is drawn whole, nudged into the margin, /// where it was cut by the margin's width (#3474); one wider than the frame is centred on it. #[test] From cb07128d638c1d0afa08053fc447a67cbd06acdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 1 Dec 2026 16:18:09 -0500 Subject: [PATCH 3/8] fix(layout): decide a shape's cut credit from where the credit is placed --- crates/render/src/layout/frame.rs | 16 +++++++--------- crates/render/src/layout/tests.rs | 25 ++++++++++++++++++------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs index 0fdbde1f05..4955251dbd 100644 --- a/crates/render/src/layout/frame.rs +++ b/crates/render/src/layout/frame.rs @@ -149,8 +149,8 @@ pub(super) fn attribution_mask_scale((w, h): (f32, f32)) -> f32 { /// every one of the `labels`, against the right end of its room there. One that no row holds so /// is centred on the widest room clear of them (of rows with none, on the widest inside the /// shape), the lowest of those as wide; on a shape lower than the credit everywhere, which has -/// no such row, it lies across the shape's middle. Also whether it is cut off: no row of the shape, -/// clear of the labels or not, is as long as it. +/// no such row, it lies across the shape's middle. Also whether it is cut off: the room it is +/// centred on is shorter than it. pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]) -> ((f32, f32), bool) { let size = crate::ATTRIBUTION_SIZE; // The shape at a cell a point (fewer on a huge frame), cut as the frame's drawing is @@ -172,9 +172,6 @@ pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameSha let middle = path.bounds(); let across = ((middle.left() + middle.right()) / 2.0 * scale, (middle.top() + middle.bottom()) / 2.0 * scale + band as f32 / 2.0); let (mut lowest, mut widest) = (None, ((0u32, 0u32), across.0, across.1)); - // The longest run of columns inside the shape, labels or not, on any row the credit's height - // fits: if it is shorter than the credit, no place in the shape holds it. - let mut longest = 0u32; for (y, line) in mask.data().chunks_exact(cols as usize).enumerate() { for (n, &a) in inside.iter_mut().zip(line) { // Wholly inside: a cell half covered would let the credit past the edge by half a cell. @@ -197,7 +194,6 @@ pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameSha let full = n >= band; let x = x as f32; run = if full { run + 1 } else { 0 }; - longest = longest.max(run); free = if full && !in_row.iter().any(|b| x < b[2] && b[0] < x + 1.0) { free + 1 } else { 0 }; let found = (free, if free == 0 { run } else { 0 }); if run > 0 && (found > widest.0 || (found == widest.0 && foot > widest.2)) { @@ -216,9 +212,11 @@ pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameSha None => (widest.1 / scale, widest.2), }; let cy = (foot - band as f32 / 2.0) / scale; - // Cut off when no row of the shape is as long as it (a label over the rows that are only - // overlaps it, which isn't cutting it). - let cut = (longest as f32) < tw * scale; + // Cut off when the room it is centred on, where it is placed (the widest clear of the labels + // when no row holds it so), is shorter than it: a verdict of the placement itself, so the two + // can't disagree. + let room_there = widest.0.0.max(widest.0.1) as f32; + let cut = lowest.is_none() && room_there < tw * scale; ((h - size * 0.9 - cy, w - cx - tw.min(w) / 2.0 - margin), cut) } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 3ec79e116d..b9f43b619d 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6454,20 +6454,31 @@ fn a_frame_says_when_its_attribution_is_cut_off() { assert!(!credit_is_cut((227.0, 227.0), &one, Some(&down))); } -/// A label over the rows of a shape that hold the credit leaves the credit over it, not cut off: -/// only a shape with no row as long as the credit cuts it (#3474). +/// The verdict is the placement's: a credit is said cut when the room it is centred on is shorter +/// than it, however long a run under a label is (#3474). A label across the middle of a circle +/// leaves it clear segments shorter than the credit on its widest rows, so it overhangs the shape; +/// a label that leaves a clear segment as long as the credit doesn't cut it. #[test] -fn a_label_over_the_rows_that_hold_the_credit_isnt_a_cut() { +fn a_credit_centred_on_a_room_shorter_than_it_is_said_cut() { let one = vec!["© OpenStreetMap contributors".to_string()]; let tw = crate::attribution_text(&one).unwrap().1; // A circle just wide enough for the credit across its middle rows only. let side = (tw + 12.0).ceil(); - let band = [(Edge::Bottom, [0.0, side * 0.3, side, side * 0.7])]; - let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &band); - assert!(!cut, "the middle rows hold it, under the label"); + // A label across its middle: the rows that hold the credit are under it. + let across = [(Edge::Bottom, [0.0, side * 0.3, side, side * 0.7])]; + let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &across); + assert!(cut, "clear of the label, no room holds it"); + // A label over the middle's right part only: the left part is clear but shorter than the credit. + let part = [(Edge::Right, [side * 0.45, side * 0.3, side, side * 0.7])]; + let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &part); + assert!(cut, "the clear room left of the label is shorter than the credit"); + // No label, or one off the rows that hold it: whole. let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &[]); assert!(!cut); - let (_, cut) = attribution_in_shape((tw - 10.0, tw - 10.0), tw, &FrameShape::Circle, &band); + let high = [(Edge::Right, [0.0, 0.0, side, side * 0.1])]; + let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &high); + assert!(!cut, "a label above the credit's rows doesn't move it"); + let (_, cut) = attribution_in_shape((tw - 10.0, tw - 10.0), tw, &FrameShape::Circle, &[]); assert!(cut, "no row holds it"); } From 3dae5a5e4814f5ef36341cb4a107fa13f6172cc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 1 Dec 2026 16:35:03 -0500 Subject: [PATCH 4/8] fix(layout): say cut credits on a presentation export, and don't count a cell short as a cut --- crates/engine/src/cmd/presentation.rs | 8 +++++++- crates/engine/src/tests/layout_credits.rs | 24 +++++++++++++++++++++++ crates/render/src/layout/frame.rs | 5 ++++- crates/render/src/layout/tests.rs | 16 +++++++++++++++ 4 files changed, 51 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index 17ee75bbd5..784e3aa154 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -530,8 +530,14 @@ fn export_within(s: &mut Session, i: usize, format: &str, dpi: f64, out: super:: })) }; let before = revision(s); - let result = super::share::saying_shadows(s, "The presentation", |s| export_bytes_inner(s, i, format, dpi, out)); + // The frames whose tile credits the pages cut off, for the notice a layout's export says. + let (result, credits) = rustgis_render::layout::cut_credits(|| { + super::share::saying_shadows(s, "The presentation", |s| export_bytes_inner(s, i, format, dpi, out)) + }); let (bytes, pages) = before.finish_revision(revision(s), Some(result), "could not draw the presentation")??; + if let Some(note) = rustgis_render::layout::credit_notice(&credits) { + s.warn(note); + } // With what a PDF or a slideshow holds around its pages. out.check(bytes.len())?; Ok((bytes, pages)) diff --git a/crates/engine/src/tests/layout_credits.rs b/crates/engine/src/tests/layout_credits.rs index 680c1e08b2..6ccc6a3219 100644 --- a/crates/engine/src/tests/layout_credits.rs +++ b/crates/engine/src/tests/layout_credits.rs @@ -116,3 +116,27 @@ fn a_report_names_the_layout_whose_frame_cuts_its_credit() { let name = &s.project.layouts.last().unwrap().element(id as u32).unwrap().name; assert_eq!(said, [format!("The report: Map frame \"{name}\" ({id}) in \"Credits\": {ADVICE}")]); } + +#[test] +fn a_presentation_slide_narrower_than_its_credit_says_so() { + let dir = Dir::new("slides"); + let mut s = credited(&dir); + s.run("presentation.new", &json!({"name": "Slides"})).unwrap(); + s.run("presentation.mapPage", &json!({"title": "Map"})).unwrap(); + let exported = |s: &mut Session, ext: &str| { + let mark = s.notice_mark(); + s.run("presentation.export", &json!({"path": dir.0.join(format!("slides.{ext}")), "dpi": 36})).unwrap(); + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("tile credits")).collect::>() + }; + // A slide of the usual size holds the credit. + assert_eq!(exported(&mut s, "pdf"), Vec::::new()); + // One 60 mm wide doesn't. + s.project.presentations[0].width = 60.0; + // A PNG is the first page, the title page `presentation.new` starts with: no map on it. + assert_eq!(exported(&mut s, "png"), Vec::::new()); + for ext in ["pdf", "html"] { + let said = exported(&mut s, ext); + assert_eq!(said.len(), 1, "{ext}: {said:?}"); + assert!(said[0].starts_with("Map frame \"Map\" (") && said[0].ends_with(ADVICE), "{ext}: {said:?}"); + } +} diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs index 4955251dbd..688f153331 100644 --- a/crates/render/src/layout/frame.rs +++ b/crates/render/src/layout/frame.rs @@ -215,8 +215,11 @@ pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameSha // Cut off when the room it is centred on, where it is placed (the widest clear of the labels // when no row holds it so), is shorter than it: a verdict of the placement itself, so the two // can't disagree. + // The mask counts only the cells wholly inside the shape, so a room is up to a cell short at + // each end, and more points a cell on a frame searched at a coarser scale: two cells of + // slack, not to say cut a credit that fits. let room_there = widest.0.0.max(widest.0.1) as f32; - let cut = lowest.is_none() && room_there < tw * scale; + let cut = lowest.is_none() && room_there + 2.0 < tw * scale; ((h - size * 0.9 - cy, w - cx - tw.min(w) / 2.0 - margin), cut) } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index b9f43b619d..902eaf4f21 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6482,6 +6482,22 @@ fn a_credit_centred_on_a_room_shorter_than_it_is_said_cut() { assert!(cut, "no row holds it"); } +/// A shape that holds the credit by a fraction of a point isn't said to cut it: the search counts +/// only the cells wholly inside the shape (#3474). +#[test] +fn a_shape_that_barely_holds_the_credit_isnt_a_cut() { + let one = vec!["© OpenStreetMap contributors".to_string()]; + let tw = crate::attribution_text(&one).unwrap().1; + let square = FrameShape::Polygon(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]); + for extra in [0.2, 0.5, 0.9, 1.5] { + let side = tw + extra; + let (_, cut) = attribution_in_shape((side, side), tw, &square, &[]); + assert!(!cut, "{side} points hold {tw}"); + } + let (_, cut) = attribution_in_shape((tw - 6.0, tw - 6.0), tw, &square, &[]); + assert!(cut, "narrower than the credit"); +} + /// A credit that fits the frame within its right margin is drawn whole, nudged into the margin, /// where it was cut by the margin's width (#3474); one wider than the frame is centred on it. #[test] From fd0a02012b21e5266550b0b48ddd5f9f800dc715 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 1 Dec 2026 17:45:07 -0500 Subject: [PATCH 5/8] fix(layout): judge a shape's cut credit on the credit as drawn --- crates/render/src/layout/frame.rs | 49 +++++++++----- crates/render/src/layout/tests.rs | 104 +++++++++++++++++++----------- 2 files changed, 99 insertions(+), 54 deletions(-) diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs index 688f153331..346406a553 100644 --- a/crates/render/src/layout/frame.rs +++ b/crates/render/src/layout/frame.rs @@ -87,14 +87,39 @@ pub(super) fn finish_frame( kept_clear.extend(draw_sections(&mut pm, sections, ppp)); pm.layer(None); let (w, h) = (pm.width() as f32 / ppp as f32, pm.height() as f32 / ppp as f32); - let (inset, cut) = crate::attribution_text(&attribution).map_or(((0.0, 0.0), false), |(_, tw)| match shape { + let tw = crate::attribution_text(&attribution).map(|(_, tw)| tw); + let inset = tw.map_or((0.0, 0.0), |tw| match shape { Some(s) if !matches!(s, FrameShape::Rectangle) => attribution_in_shape((w, h), tw, s, &kept_clear), - _ => (attribution_inset((w, h), tw, &kept_clear), tw > w), + _ => attribution_inset((w, h), tw, &kept_clear), }); crate::draw_attribution(&mut pm, &attribution, ppp as f32, inset); + let cut = tw.is_some_and(|tw| credit_leaves_frame((w, h), tw, inset, shape, ppp as f32)); (pm, cut) } +/// Whether the credit `tw` points wide that [`crate::draw_attribution`] writes `inset` further in +/// (up, in) on a frame `w` × `h` points reaches outside the frame's `shape`, so that its ends are +/// cut off. Judged on the credit as drawn, not on the search that placed it: at the frame's own +/// pixels, a pixel of the credit's box counting as inside the shape when its centre is, so it errs +/// by half a pixel at most either way, the resolution the credit is drawn at. A rectangle's credit +/// is cut when it is wider than the frame; `attribution_center` keeps it inside otherwise. +pub(super) fn credit_leaves_frame((w, h): (f32, f32), tw: f32, (bottom, right): (f32, f32), shape: Option<&FrameShape>, ppp: f32) -> bool { + if tw > w { + return true; + } + let Some(shape) = shape.filter(|s| !matches!(s, FrameShape::Rectangle)) else { return false }; + let size = crate::ATTRIBUTION_SIZE; + // The box [`attribution_inset`] keeps clear of the labels: the credit's width, its height with + // its halo. + let (x0, y0) = (crate::attribution_center(w, tw, right) - tw / 2.0, h - bottom - size * 0.9 - size * 0.8); + let (cols, rows) = ((tw * ppp).floor().max(1.0) as u32, (size * 1.6 * ppp).floor().max(1.0) as u32); + let (Some(mut mask), Some(path)) = (Mask::new(cols, rows), Rect::from_xywh(0.0, 0.0, w, h).and_then(|r| shape_path(shape, r))) else { + return false; + }; + mask.fill_path(&path, FillRule::Winding, false, Transform::from_translate(-x0, -y0).post_scale(ppp, ppp)); + mask.data().contains(&0) +} + /// How far further in (up from the bottom, in from the right, in points) the attribution `tw` /// points wide goes on a frame `w` × `h` points, so it covers none of the grid's bottom and right /// `labels` (each one's edge, and its box in points: left, top, right, bottom). It goes above a @@ -149,16 +174,16 @@ pub(super) fn attribution_mask_scale((w, h): (f32, f32)) -> f32 { /// every one of the `labels`, against the right end of its room there. One that no row holds so /// is centred on the widest room clear of them (of rows with none, on the widest inside the /// shape), the lowest of those as wide; on a shape lower than the credit everywhere, which has -/// no such row, it lies across the shape's middle. Also whether it is cut off: the room it is -/// centred on is shorter than it. -pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]) -> ((f32, f32), bool) { +/// no such row, it lies across the shape's middle (see [`credit_leaves_frame`] for whether that +/// leaves it cut off). +pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]) -> (f32, f32) { let size = crate::ATTRIBUTION_SIZE; // The shape at a cell a point (fewer on a huge frame), cut as the frame's drawing is // ([`shape_path`]). let scale = attribution_mask_scale((w, h)); let (cols, rows) = ((w * scale).ceil().max(1.0) as u32, (h * scale).ceil().max(1.0) as u32); - let Some(mut mask) = Mask::new(cols, rows) else { return ((0.0, 0.0), false) }; - let Some(path) = Rect::from_xywh(0.0, 0.0, w, h).and_then(|r| shape_path(shape, r)) else { return ((0.0, 0.0), false) }; + let Some(mut mask) = Mask::new(cols, rows) else { return (0.0, 0.0) }; + let Some(path) = Rect::from_xywh(0.0, 0.0, w, h).and_then(|r| shape_path(shape, r)) else { return (0.0, 0.0) }; mask.fill_path(&path, FillRule::Winding, true, Transform::from_scale(scale, scale)); // The rows the credit takes, its halo included, and the gaps at its right and from a label. let band = ((size * 1.6 * scale).ceil() as u32).min(rows); @@ -212,15 +237,7 @@ pub(super) fn attribution_in_shape((w, h): (f32, f32), tw: f32, shape: &FrameSha None => (widest.1 / scale, widest.2), }; let cy = (foot - band as f32 / 2.0) / scale; - // Cut off when the room it is centred on, where it is placed (the widest clear of the labels - // when no row holds it so), is shorter than it: a verdict of the placement itself, so the two - // can't disagree. - // The mask counts only the cells wholly inside the shape, so a room is up to a cell short at - // each end, and more points a cell on a frame searched at a coarser scale: two cells of - // slack, not to say cut a credit that fits. - let room_there = widest.0.0.max(widest.0.1) as f32; - let cut = lowest.is_none() && room_there + 2.0 < tw * scale; - ((h - size * 0.9 - cy, w - cx - tw.min(w) / 2.0 - margin), cut) + (h - size * 0.9 - cy, w - cx - tw.min(w) / 2.0 - margin) } pub(super) fn shape_path(shape: &FrameShape, r: Rect) -> Option { diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 902eaf4f21..2c14a1a41d 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6338,7 +6338,7 @@ fn a_shaped_frames_attribution_stays_inside_its_shape() { fn a_shaped_frames_attribution_takes_the_lowest_row_that_holds_it() { let size = crate::ATTRIBUTION_SIZE; let place = |(w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]| { - let ((bottom, right), _) = attribution_in_shape((w, h), tw, shape, labels); + let (bottom, right) = attribution_in_shape((w, h), tw, shape, labels); (crate::attribution_center(w, tw, right), h - bottom - size * 0.9) }; let (_, circle) = place((142.0, 142.0), 100.0, &FrameShape::Circle, &[]); @@ -6392,7 +6392,7 @@ fn a_huge_shaped_frames_attribution_is_placed_within_the_cell_budget() { assert!((side * scale).ceil().powi(2) <= 1.01 * ATTRIBUTION_MASK_CELLS, "{scale}"); assert_eq!(attribution_mask_scale((227.0, 227.0)), 1.0, "a point a cell on an ordinary frame"); let (tw, size) = (175.0, crate::ATTRIBUTION_SIZE); - let ((bottom, right), _) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &[]); + let (bottom, right) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &[]); let (cx, cy) = (crate::attribution_center(side, tw, right), side - bottom - size * 0.9); let r = side / 2.0; for (dx, dy) in [(-0.5, -0.8), (0.5, -0.8), (-0.5, 0.8), (0.5, 0.8)] { @@ -6454,48 +6454,76 @@ fn a_frame_says_when_its_attribution_is_cut_off() { assert!(!credit_is_cut((227.0, 227.0), &one, Some(&down))); } -/// The verdict is the placement's: a credit is said cut when the room it is centred on is shorter -/// than it, however long a run under a label is (#3474). A label across the middle of a circle -/// leaves it clear segments shorter than the credit on its widest rows, so it overhangs the shape; -/// a label that leaves a clear segment as long as the credit doesn't cut it. +/// Whether the credit of `tw` points placed on a `w` × `h` point frame of `shape` with `labels` +/// (as [`attribution_in_shape`] places it) is cut off, at 2 pixels a point (#3474). +fn placed_credit_is_cut((w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]) -> bool { + let inset = attribution_in_shape((w, h), tw, shape, labels); + credit_leaves_frame((w, h), tw, inset, Some(shape), 2.0) +} + +/// The verdict is on the credit as drawn: cut when its box leaves the shape, however the search +/// that placed it counted its cells, and the same with labels as without (#3474). #[test] -fn a_credit_centred_on_a_room_shorter_than_it_is_said_cut() { +fn a_credit_is_said_cut_when_its_box_leaves_the_shape() { let one = vec!["© OpenStreetMap contributors".to_string()]; let tw = crate::attribution_text(&one).unwrap().1; - // A circle just wide enough for the credit across its middle rows only. - let side = (tw + 12.0).ceil(); - // A label across its middle: the rows that hold the credit are under it. - let across = [(Edge::Bottom, [0.0, side * 0.3, side, side * 0.7])]; - let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &across); - assert!(cut, "clear of the label, no room holds it"); - // A label over the middle's right part only: the left part is clear but shorter than the credit. - let part = [(Edge::Right, [side * 0.45, side * 0.3, side, side * 0.7])]; - let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &part); - assert!(cut, "the clear room left of the label is shorter than the credit"); - // No label, or one off the rows that hold it: whole. - let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &[]); - assert!(!cut); - let high = [(Edge::Right, [0.0, 0.0, side, side * 0.1])]; - let (_, cut) = attribution_in_shape((side, side), tw, &FrameShape::Circle, &high); - assert!(!cut, "a label above the credit's rows doesn't move it"); - let (_, cut) = attribution_in_shape((tw - 10.0, tw - 10.0), tw, &FrameShape::Circle, &[]); - assert!(cut, "no row holds it"); -} - -/// A shape that holds the credit by a fraction of a point isn't said to cut it: the search counts -/// only the cells wholly inside the shape (#3474). -#[test] -fn a_shape_that_barely_holds_the_credit_isnt_a_cut() { + let square = FrameShape::Polygon(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]); + // A square a fraction wider than the credit holds it; one narrower doesn't, however little. + for extra in [0.2, 0.5, 0.9, 1.5, 4.0] { + assert!(!placed_credit_is_cut((tw + extra, tw + extra), tw, &square, &[]), "{extra} wider"); + } + for short in [0.3, 1.0, 2.5] { + assert!(placed_credit_is_cut((tw - short, tw - short), tw, &square, &[]), "{short} narrower"); + } + // On a tall frame, searched at a coarser scale, the same. + assert!(attribution_mask_scale((tw + 0.5, 100_000.0)) < 1.0); + assert!(!placed_credit_is_cut((tw + 0.5, 100_000.0), tw, &square, &[])); + assert!(placed_credit_is_cut((tw - 0.3, 100_000.0), tw, &square, &[])); + // A label over every row, to the right: the credit goes left of it, whole inside the square, + // not cut (as on a rectangle). + let side = 300.0; + let over = [(Edge::Right, [100.0, 0.0, side, side])]; + assert!(!placed_credit_is_cut((side, side), tw, &square, &over)); + // A label across a circle's middle leaves the credit clear rooms shorter than itself: it is + // centred on one and overhangs the circle. + let round = (tw + 12.0).ceil(); + let across = [(Edge::Bottom, [0.0, round * 0.3, round, round * 0.7])]; + assert!(placed_credit_is_cut((round, round), tw, &FrameShape::Circle, &across)); + let part = [(Edge::Right, [round * 0.45, round * 0.3, round, round * 0.7])]; + assert!(placed_credit_is_cut((round, round), tw, &FrameShape::Circle, &part)); + // No label, or one above the credit's rows: whole. + assert!(!placed_credit_is_cut((round, round), tw, &FrameShape::Circle, &[])); + let high = [(Edge::Right, [0.0, 0.0, round, round * 0.1])]; + assert!(!placed_credit_is_cut((round, round), tw, &FrameShape::Circle, &high)); + assert!(placed_credit_is_cut((tw - 10.0, tw - 10.0), tw, &FrameShape::Circle, &[])); +} + +/// On a trapezoid (narrower at its foot, its edges slanted off the cell grid) the verdict is the +/// credit's box against the shape's edges, wherever the room is. +#[test] +fn a_slanted_shapes_verdict_is_the_boxs_against_its_edges() { let one = vec!["© OpenStreetMap contributors".to_string()]; let tw = crate::attribution_text(&one).unwrap().1; - let square = FrameShape::Polygon(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]); - for extra in [0.2, 0.5, 0.9, 1.5] { - let side = tw + extra; - let (_, cut) = attribution_in_shape((side, side), tw, &square, &[]); - assert!(!cut, "{side} points hold {tw}"); + let trapezoid = FrameShape::Polygon(vec![(0.0, 0.0), (1.0, 0.0), (0.8, 1.0), (0.2, 1.0)]); + let (mut cut, mut whole) = (0, 0); + for i in 0..120 { + let w = tw + 1.0 + f32::from(i as u8) * 0.5; + let h = 150.0; + let (bottom, right) = attribution_in_shape((w, h), tw, &trapezoid, &[]); + let (x0, x1) = (crate::attribution_center(w, tw, right) - tw / 2.0, crate::attribution_center(w, tw, right) + tw / 2.0); + let foot = h - bottom - crate::ATTRIBUTION_SIZE * 0.9 + crate::ATTRIBUTION_SIZE * 0.8; + // The edges at the box's foot, the narrowest row it spans. + let (left, rightmost) = (0.2 * w * foot / h, w - 0.2 * w * foot / h); + let margin = (x0 - left).min(rightmost - x1); + // Within a pixel of an edge the answer may go either way. + if margin.abs() < 0.6 { + continue; + } + let said = placed_credit_is_cut((w, h), tw, &trapezoid, &[]); + assert_eq!(said, margin < 0.0, "w {w}: box {x0}..{x1} against {left}..{rightmost}"); + if said { cut += 1 } else { whole += 1 } } - let (_, cut) = attribution_in_shape((tw - 6.0, tw - 6.0), tw, &square, &[]); - assert!(cut, "narrower than the credit"); + assert!(cut > 0 && whole > 0, "the sweep sees both: {cut} cut, {whole} whole"); } /// A credit that fits the frame within its right margin is drawn whole, nudged into the margin, From 2f870365e5de29ba2a7712e491d8a589466ca19d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 1 Dec 2026 18:04:10 -0500 Subject: [PATCH 6/8] fix(layout): sample the credit's box by points, not by the frame's pixels --- crates/render/src/layout/frame.rs | 25 ++++++++++++++++--------- crates/render/src/layout/tests.rs | 18 +++++++++++++----- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs index 346406a553..edda863396 100644 --- a/crates/render/src/layout/frame.rs +++ b/crates/render/src/layout/frame.rs @@ -93,17 +93,23 @@ pub(super) fn finish_frame( _ => attribution_inset((w, h), tw, &kept_clear), }); crate::draw_attribution(&mut pm, &attribution, ppp as f32, inset); - let cut = tw.is_some_and(|tw| credit_leaves_frame((w, h), tw, inset, shape, ppp as f32)); + let cut = tw.is_some_and(|tw| credit_leaves_frame((w, h), tw, inset, shape)); (pm, cut) } +/// Samples across the credit's box, per point of it, that [`credit_leaves_frame`] tests against the +/// shape: its width and height are sampled by rows and columns of this many to the point, whatever +/// the pixels the frame is drawn at, so an overhang is seen from a quarter of a point. +const CREDIT_SAMPLES: f32 = 4.0; + /// Whether the credit `tw` points wide that [`crate::draw_attribution`] writes `inset` further in /// (up, in) on a frame `w` × `h` points reaches outside the frame's `shape`, so that its ends are -/// cut off. Judged on the credit as drawn, not on the search that placed it: at the frame's own -/// pixels, a pixel of the credit's box counting as inside the shape when its centre is, so it errs -/// by half a pixel at most either way, the resolution the credit is drawn at. A rectangle's credit -/// is cut when it is wider than the frame; `attribution_center` keeps it inside otherwise. -pub(super) fn credit_leaves_frame((w, h): (f32, f32), tw: f32, (bottom, right): (f32, f32), shape: Option<&FrameShape>, ppp: f32) -> bool { +/// cut off. Judged on the credit as drawn, not on the search that placed it: its box is sampled +/// ([`CREDIT_SAMPLES`] to the point, the samples spread evenly over the box so the last one is half +/// a sample from its end) and any sample outside the shape cuts it, so an overhang over an eighth of +/// a point goes unsaid at most, at any resolution. A rectangle's credit is cut when it is wider +/// than the frame; `attribution_center` keeps it inside otherwise. +pub(super) fn credit_leaves_frame((w, h): (f32, f32), tw: f32, (bottom, right): (f32, f32), shape: Option<&FrameShape>) -> bool { if tw > w { return true; } @@ -111,12 +117,13 @@ pub(super) fn credit_leaves_frame((w, h): (f32, f32), tw: f32, (bottom, right): let size = crate::ATTRIBUTION_SIZE; // The box [`attribution_inset`] keeps clear of the labels: the credit's width, its height with // its halo. - let (x0, y0) = (crate::attribution_center(w, tw, right) - tw / 2.0, h - bottom - size * 0.9 - size * 0.8); - let (cols, rows) = ((tw * ppp).floor().max(1.0) as u32, (size * 1.6 * ppp).floor().max(1.0) as u32); + let (x0, y0, box_h) = (crate::attribution_center(w, tw, right) - tw / 2.0, h - bottom - size * 0.9 - size * 0.8, size * 1.6); + let (cols, rows) = ((tw * CREDIT_SAMPLES).ceil().max(1.0) as u32, (box_h * CREDIT_SAMPLES).ceil().max(1.0) as u32); let (Some(mut mask), Some(path)) = (Mask::new(cols, rows), Rect::from_xywh(0.0, 0.0, w, h).and_then(|r| shape_path(shape, r))) else { return false; }; - mask.fill_path(&path, FillRule::Winding, false, Transform::from_translate(-x0, -y0).post_scale(ppp, ppp)); + let to_samples = Transform::from_translate(-x0, -y0).post_scale(cols as f32 / tw, rows as f32 / box_h); + mask.fill_path(&path, FillRule::Winding, false, to_samples); mask.data().contains(&0) } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 2c14a1a41d..5c73c474da 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6458,7 +6458,7 @@ fn a_frame_says_when_its_attribution_is_cut_off() { /// (as [`attribution_in_shape`] places it) is cut off, at 2 pixels a point (#3474). fn placed_credit_is_cut((w, h): (f32, f32), tw: f32, shape: &FrameShape, labels: &[(Edge, [f32; 4])]) -> bool { let inset = attribution_in_shape((w, h), tw, shape, labels); - credit_leaves_frame((w, h), tw, inset, Some(shape), 2.0) + credit_leaves_frame((w, h), tw, inset, Some(shape)) } /// The verdict is on the credit as drawn: cut when its box leaves the shape, however the search @@ -6475,6 +6475,14 @@ fn a_credit_is_said_cut_when_its_box_leaves_the_shape() { for short in [0.3, 1.0, 2.5] { assert!(placed_credit_is_cut((tw - short, tw - short), tw, &square, &[]), "{short} narrower"); } + // An edge a fraction of a point inside the credit's end is seen, at any output resolution + // (the box is sampled by points, not by the frame's pixels): a shape whose left edge is 1 pt in + // from a frame 0.4 pt wider than the credit overhangs it by 0.6 pt. + let w = tw + 0.4; + let inset = FrameShape::Polygon(vec![(f64::from(1.0 / w), 0.0), (1.0, 0.0), (1.0, 1.0), (f64::from(1.0 / w), 1.0)]); + assert!(placed_credit_is_cut((w, w), tw, &inset, &[]), "0.6 pt over"); + let roomy = FrameShape::Polygon(vec![(f64::from(0.2 / (tw + 4.0)), 0.0), (1.0, 0.0), (1.0, 1.0), (f64::from(0.2 / (tw + 4.0)), 1.0)]); + assert!(!placed_credit_is_cut((tw + 4.0, tw + 4.0), tw, &roomy, &[]), "3.8 pt of room"); // On a tall frame, searched at a coarser scale, the same. assert!(attribution_mask_scale((tw + 0.5, 100_000.0)) < 1.0); assert!(!placed_credit_is_cut((tw + 0.5, 100_000.0), tw, &square, &[])); @@ -6506,8 +6514,8 @@ fn a_slanted_shapes_verdict_is_the_boxs_against_its_edges() { let tw = crate::attribution_text(&one).unwrap().1; let trapezoid = FrameShape::Polygon(vec![(0.0, 0.0), (1.0, 0.0), (0.8, 1.0), (0.2, 1.0)]); let (mut cut, mut whole) = (0, 0); - for i in 0..120 { - let w = tw + 1.0 + f32::from(i as u8) * 0.5; + for i in 0..400 { + let w = tw + 1.0 + i as f32 * 0.15; let h = 150.0; let (bottom, right) = attribution_in_shape((w, h), tw, &trapezoid, &[]); let (x0, x1) = (crate::attribution_center(w, tw, right) - tw / 2.0, crate::attribution_center(w, tw, right) + tw / 2.0); @@ -6515,8 +6523,8 @@ fn a_slanted_shapes_verdict_is_the_boxs_against_its_edges() { // The edges at the box's foot, the narrowest row it spans. let (left, rightmost) = (0.2 * w * foot / h, w - 0.2 * w * foot / h); let margin = (x0 - left).min(rightmost - x1); - // Within a pixel of an edge the answer may go either way. - if margin.abs() < 0.6 { + // Within a sample (a quarter of a point) of an edge the answer may go either way. + if margin.abs() < 0.3 { continue; } let said = placed_credit_is_cut((w, h), tw, &trapezoid, &[]); From 3a5b0b4732be2a2e20b01f1215f77c943e00ce2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 1 Dec 2026 20:31:50 -0500 Subject: [PATCH 7/8] fix(layout): keep one cut credit per frame of each layout, and name the pages of a presentation --- crates/engine/src/cmd/layout/export.rs | 6 ++--- crates/engine/src/cmd/presentation.rs | 5 ++-- crates/engine/src/cmd/report.rs | 7 ++---- crates/engine/src/tests/layout_credits.rs | 9 ++++++- crates/render/src/layout.rs | 2 +- crates/render/src/layout/credit.rs | 29 +++++++++++++---------- crates/render/src/layout/tests.rs | 22 +++++++++-------- 7 files changed, 45 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index c99f896675..aaab9e8d20 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -135,7 +135,7 @@ pub(super) fn layout_page( for note in chart_notice_lines(&layout, &charts) { s.warn(note); } - if let Some(note) = rustgis_render::layout::credit_notice(&credits) { + if let Some(note) = rustgis_render::layout::credit_notice(&credits, false) { s.warn(note); } if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) { @@ -376,7 +376,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( for note in chart_notice_lines(&saved, &charts) { s.warn(note); } - if let Some(note) = rustgis_render::layout::credit_notice(&credits) { + if let Some(note) = rustgis_render::layout::credit_notice(&credits, false) { s.warn(note); } pictured_notices(s, &frames_pictured, &pages_pictured); @@ -639,7 +639,7 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd for note in chart_notes { s.warn(note); } - if let Some(note) = rustgis_render::layout::credit_notice(&credits) { + if let Some(note) = rustgis_render::layout::credit_notice(&credits, false) { s.warn(note); } pictured_notices(s, &pictured, &[]); diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index 784e3aa154..579460f96f 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -535,8 +535,9 @@ fn export_within(s: &mut Session, i: usize, format: &str, dpi: f64, out: super:: super::share::saying_shadows(s, "The presentation", |s| export_bytes_inner(s, i, format, dpi, out)) }); let (bytes, pages) = before.finish_revision(revision(s), Some(result), "could not draw the presentation")??; - if let Some(note) = rustgis_render::layout::credit_notice(&credits) { - s.warn(note); + // Each page is a layout of its own, its elements numbered from 1: named by their pages. + if let Some(note) = rustgis_render::layout::credit_notice(&credits, true) { + s.warn(format!("The presentation: {note}")); } // With what a PDF or a slideshow holds around its pages. out.check(bytes.len())?; diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 2271d4b5fa..b9018b9f6e 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1558,11 +1558,8 @@ fn say_report_charts(s: &mut Session, kept: &[(usize, rustgis_render::layout::Dr /// Says the map frames whose tile credits [`keep_drawn`] kept as cut off, each named with its /// layout, as a layout's export says its own: one notice however many layouts have one. fn say_report_credits(s: &mut Session, kept: &[(usize, rustgis_render::layout::CutCredit)]) { - let found: Vec<_> = kept - .iter() - .map(|(li, c)| rustgis_render::layout::CutCredit { layout: s.project.layouts.get(*li).map(|l| l.name.clone()), ..c.clone() }) - .collect(); - if let Some(note) = rustgis_render::layout::credit_notice(&found) { + let found: Vec<_> = kept.iter().map(|(_, c)| c.clone()).collect(); + if let Some(note) = rustgis_render::layout::credit_notice(&found, true) { s.warn(format!("The report: {note}")); } } diff --git a/crates/engine/src/tests/layout_credits.rs b/crates/engine/src/tests/layout_credits.rs index 6ccc6a3219..ea07c80012 100644 --- a/crates/engine/src/tests/layout_credits.rs +++ b/crates/engine/src/tests/layout_credits.rs @@ -137,6 +137,13 @@ fn a_presentation_slide_narrower_than_its_credit_says_so() { for ext in ["pdf", "html"] { let said = exported(&mut s, ext); assert_eq!(said.len(), 1, "{ext}: {said:?}"); - assert!(said[0].starts_with("Map frame \"Map\" (") && said[0].ends_with(ADVICE), "{ext}: {said:?}"); + assert!(said[0].starts_with("The presentation: Map frame \"Map\" (") && said[0].ends_with(ADVICE), "{ext}: {said:?}"); + assert!(said[0].contains(" in \"Map\""), "{ext}: named by its page: {said:?}"); } + // Two map pages: each slide is a layout of its own, its frame numbered like the other's, and + // both are said. + s.run("presentation.mapPage", &json!({"title": "Second"})).unwrap(); + let said = exported(&mut s, "pdf"); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("2 map frames") && said[0].contains(" in \"Map\"") && said[0].contains(" in \"Second\""), "{said:?}"); } diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 0e928abad8..bb97930fe6 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -500,7 +500,7 @@ fn draw_page( } // Its tile credits' ends cut off, for an export to say ([`cut_credits`]). if cut_here { - credit_cut(e.id, &e.name); + credit_cut(e.id, &e.name, &layout.name); } // The extent indicators, in order, a later one over an earlier one. let mut numbers = Vec::new(); diff --git a/crates/render/src/layout/credit.rs b/crates/render/src/layout/credit.rs index 68abceec03..b48ccaed2f 100644 --- a/crates/render/src/layout/credit.rs +++ b/crates/render/src/layout/credit.rs @@ -3,12 +3,13 @@ use super::*; /// A map frame a page drew whose tile credits don't fit in it ([`cut_credits`]): its element's id -/// and name, and in a report its layout's name. +/// and name, and the name of the layout it is in (a report or a presentation draws several, whose +/// elements number from 1 each). #[derive(Clone, Debug, PartialEq, Eq)] pub struct CutCredit { pub id: u32, pub name: String, - /// Its layout's name, said with it: set by a report, whose pages draw several. + /// Its layout's name. pub layout: Option, } @@ -48,34 +49,36 @@ pub fn cut_credits(f: impl FnOnce() -> T) -> (T, Vec) { (out, listed) } -/// Lists the frame `id` named `name` as drawn with its credits cut, while [`cut_credits`] runs. -pub(super) fn credit_cut(id: u32, name: &str) { +/// Lists the frame `id` named `name` of the layout `layout` as drawn with its credits cut, while +/// [`cut_credits`] runs: once for each element of each layout. +pub(super) fn credit_cut(id: u32, name: &str, layout: &str) { CUT.with_borrow_mut(|c| { if let Some(listed) = c - && !listed.iter().any(|l| l.id == id) + && !listed.iter().any(|l| l.id == id && l.layout.as_deref() == Some(layout)) { - listed.push(CutCredit { id, name: name.to_string(), layout: None }); + listed.push(CutCredit { id, name: name.to_string(), layout: Some(layout.to_string()) }); } }); } -/// A frame as a notice names it: by name and id, and in a report by its layout. -fn named(c: &CutCredit) -> String { - let layout = c.layout.as_ref().map(|l| format!(" in \"{}\"", notice_cut(l))).unwrap_or_default(); +/// A frame as a notice names it: by name and id, and by its layout when `with_layout`. +fn named(c: &CutCredit, with_layout: bool) -> String { + let layout = c.layout.as_ref().filter(|_| with_layout).map(|l| format!(" in \"{}\"", notice_cut(l))).unwrap_or_default(); format!("\"{}\" ({}){layout}", notice_cut(&c.name), c.id) } /// What to say of the frames [`cut_credits`] found: one notice, each frame by name and id (the -/// first ten, and how many more). `None` when there are none. -pub fn credit_notice(found: &[CutCredit]) -> Option { +/// first ten, and how many more), with its layout when `with_layouts`, as a report or a +/// presentation says them: their layouts' elements number alike. `None` when there are none. +pub fn credit_notice(found: &[CutCredit], with_layouts: bool) -> Option { match found { [] => None, [c] => Some(format!( "Map frame {}: its tile credits don't fit in it, so their ends are cut off; make it larger, or show fewer tile layers in it", - named(c) + named(c, with_layouts) )), _ => { - let mut each = found.iter().take(10).map(named).collect::>().join("; "); + let mut each = found.iter().take(10).map(|c| named(c, with_layouts)).collect::>().join("; "); if found.len() > 10 { each.push_str(&format!("; and {} more", found.len() - 10)); } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 5c73c474da..86316b0a9a 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6553,16 +6553,18 @@ fn a_credit_within_a_margin_of_the_frames_width_is_drawn_whole() { /// nothing and leaves its frames to the outer one; nothing is kept outside one. #[test] fn cut_credits_lists_each_frame_once() { - credit_cut(9, "Outside"); + credit_cut(9, "Outside", "L"); let ((), found) = cut_credits(|| { - credit_cut(3, "North"); - credit_cut(5, "South"); - credit_cut(3, "North"); - let ((), inner) = cut_credits(|| credit_cut(7, "East")); + credit_cut(3, "North", "L"); + credit_cut(5, "South", "L"); + credit_cut(3, "North", "L"); + // The same id in another layout is another frame. + credit_cut(3, "North", "M"); + let ((), inner) = cut_credits(|| credit_cut(7, "East", "L")); assert!(inner.is_empty()); }); let ids: Vec<_> = found.iter().map(|c| c.id).collect(); - assert_eq!(ids, [3, 5, 7]); + assert_eq!(ids, [3, 5, 3, 7]); let ((), after) = cut_credits(|| ()); assert!(after.is_empty(), "{after:?}"); } @@ -6572,16 +6574,16 @@ fn cut_credits_lists_each_frame_once() { #[test] fn the_notice_names_the_frames_whose_credits_are_cut() { let frame = |id: u32, layout: Option<&str>| CutCredit { id, name: format!("Map {id}"), layout: layout.map(str::to_string) }; - assert_eq!(credit_notice(&[]), None); + assert_eq!(credit_notice(&[], false), None); assert_eq!( - credit_notice(&[frame(3, None)]).unwrap(), + credit_notice(&[frame(3, Some("Atlas"))], false).unwrap(), "Map frame \"Map 3\" (3): its tile credits don't fit in it, so their ends are cut off; make it larger, or show fewer tile layers in it" ); - let two = credit_notice(&[frame(3, Some("Atlas")), frame(4, Some("Atlas"))]).unwrap(); + let two = credit_notice(&[frame(3, Some("Atlas")), frame(4, Some("Atlas"))], true).unwrap(); assert!(two.starts_with("2 map frames don't hold their tile credits"), "{two}"); assert!(two.contains("\"Map 3\" (3) in \"Atlas\"; \"Map 4\" (4) in \"Atlas\""), "{two}"); let many: Vec<_> = (1..=12).map(|i| frame(i, None)).collect(); - let note = credit_notice(&many).unwrap(); + let note = credit_notice(&many, false).unwrap(); assert!(note.starts_with("12 map frames") && note.contains("\"Map 10\" (10); and 2 more"), "{note}"); assert!(!note.contains("(11)"), "{note}"); } From 76183e540efa9e7a64b7be5b1e71c89a4cf8a426 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 1 Dec 2026 21:08:37 -0500 Subject: [PATCH 8/8] fix(layout): tell a presentation's slides apart by page, and a credit with no width is never cut --- crates/engine/src/cmd/presentation.rs | 44 ++++++++++++++++++----- crates/engine/src/tests/layout_credits.rs | 13 ++++--- crates/render/src/layout/frame.rs | 4 +++ crates/render/src/layout/tests.rs | 3 +- 4 files changed, 49 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index 579460f96f..10bd2a2b72 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -530,12 +530,10 @@ fn export_within(s: &mut Session, i: usize, format: &str, dpi: f64, out: super:: })) }; let before = revision(s); - // The frames whose tile credits the pages cut off, for the notice a layout's export says. - let (result, credits) = rustgis_render::layout::cut_credits(|| { - super::share::saying_shadows(s, "The presentation", |s| export_bytes_inner(s, i, format, dpi, out)) - }); + // The frames whose tile credits the pages cut off, each named by its page ([`page_credited`]). + let mut credits = Vec::new(); + let result = super::share::saying_shadows(s, "The presentation", |s| export_bytes_inner(s, i, format, dpi, out, &mut credits)); let (bytes, pages) = before.finish_revision(revision(s), Some(result), "could not draw the presentation")??; - // Each page is a layout of its own, its elements numbered from 1: named by their pages. if let Some(note) = rustgis_render::layout::credit_notice(&credits, true) { s.warn(format!("The presentation: {note}")); } @@ -544,12 +542,36 @@ fn export_within(s: &mut Session, i: usize, format: &str, dpi: f64, out: super:: Ok((bytes, pages)) } +/// `f`, drawing page `k` of presentation `i`, and the map frames of it whose tile credits were cut +/// off, added to `kept` named by their page: each page is a layout of its own, its elements +/// numbered from 1 and its name its title, which two pages can share, so only the page's number +/// tells the frames apart. A page drawn twice (a vector page too large, redrawn as a picture) is +/// kept once. +fn page_credited( + s: &mut Session, + i: usize, + k: usize, + kept: &mut Vec, + f: impl FnOnce(&mut Session) -> T, +) -> T { + let title = s.project.presentations.get(i).and_then(|p| p.pages.get(k)).map(|p| p.title.clone()).unwrap_or_default(); + let (out, found) = rustgis_render::layout::cut_credits(|| f(s)); + for mut c in found { + c.layout = Some(format!("{title} (page {})", k + 1)); + if !kept.contains(&c) { + kept.push(c); + } + } + out +} + fn export_bytes_inner( s: &mut Session, i: usize, format: &str, dpi: f64, out: super::exports::Output<'_>, + credits: &mut Vec, ) -> Result<(Vec, usize), String> { // Only the size and name are copied: the pages can hold many megabytes of pictures, so each // is read in place after it's drawn. @@ -559,7 +581,7 @@ fn export_bytes_inner( return Err("the presentation has no pages".into()); } if format == "png" { - let img = draw_page(s, i, 0, dpi)?; + let img = page_credited(s, i, 0, credits, |s| draw_page(s, i, 0, dpi))?; return Ok((out.held_to(|limit| rustgis_render::png::within(&img, limit))?, 1)); } let mut pdf_pages = Vec::new(); @@ -569,18 +591,22 @@ fn export_bytes_inner( let (mut frames_pictured, mut pages_pictured) = (Vec::new(), Vec::new()); for k in 0..n { if format == "pdf" { - let (page, pictured) = pdf_page(s, i, k, dpi, (width, height))?; + let (page, pictured) = page_credited(s, i, k, credits, |s| pdf_page(s, i, k, dpi, (width, height)))?; if page.overflowed() { // Too large for vectors all the same: the page as one picture. pages_pictured.push(k + 1); - pdf_pages.push(rustgis_render::pdf::Page::new(&draw_page(s, i, k, dpi)?, width, height)); + pdf_pages.push(rustgis_render::pdf::Page::new( + &page_credited(s, i, k, credits, |s| draw_page(s, i, k, dpi))?, + width, + height, + )); } else { frames_pictured.extend(pictured); pdf_pages.push(page); } held += pdf_pages.last().map_or(0, rustgis_render::pdf::Page::len); } else { - let img = draw_page(s, i, k, dpi)?; + let img = page_credited(s, i, k, credits, |s| 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 = out.held_to(|limit| rustgis_render::png::base64_within(&img, limit, slides.len()))?; held += png.len(); diff --git a/crates/engine/src/tests/layout_credits.rs b/crates/engine/src/tests/layout_credits.rs index ea07c80012..6059e94647 100644 --- a/crates/engine/src/tests/layout_credits.rs +++ b/crates/engine/src/tests/layout_credits.rs @@ -138,12 +138,15 @@ fn a_presentation_slide_narrower_than_its_credit_says_so() { let said = exported(&mut s, ext); assert_eq!(said.len(), 1, "{ext}: {said:?}"); assert!(said[0].starts_with("The presentation: Map frame \"Map\" (") && said[0].ends_with(ADVICE), "{ext}: {said:?}"); - assert!(said[0].contains(" in \"Map\""), "{ext}: named by its page: {said:?}"); + assert!(said[0].contains(" in \"Map (page 2)\""), "{ext}: named by its page: {said:?}"); } - // Two map pages: each slide is a layout of its own, its frame numbered like the other's, and - // both are said. - s.run("presentation.mapPage", &json!({"title": "Second"})).unwrap(); + // Two map pages, even of one title: each slide is a layout of its own, its frame numbered like + // the other's, and both are said, by their pages. + s.run("presentation.mapPage", &json!({"title": "Map"})).unwrap(); let said = exported(&mut s, "pdf"); assert_eq!(said.len(), 1, "{said:?}"); - assert!(said[0].contains("2 map frames") && said[0].contains(" in \"Map\"") && said[0].contains(" in \"Second\""), "{said:?}"); + assert!( + said[0].contains("2 map frames") && said[0].contains(" in \"Map (page 2)\"") && said[0].contains(" in \"Map (page 3)\""), + "{said:?}" + ); } diff --git a/crates/render/src/layout/frame.rs b/crates/render/src/layout/frame.rs index edda863396..8ca781b009 100644 --- a/crates/render/src/layout/frame.rs +++ b/crates/render/src/layout/frame.rs @@ -110,6 +110,10 @@ const CREDIT_SAMPLES: f32 = 4.0; /// a point goes unsaid at most, at any resolution. A rectangle's credit is cut when it is wider /// than the frame; `attribution_center` keeps it inside otherwise. pub(super) fn credit_leaves_frame((w, h): (f32, f32), tw: f32, (bottom, right): (f32, f32), shape: Option<&FrameShape>) -> bool { + // A credit with no width (empty texts) can't be cut. + if tw <= 0.0 { + return false; + } if tw > w { return true; } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 86316b0a9a..40cda2b53e 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6441,7 +6441,8 @@ fn a_frame_says_when_its_attribution_is_cut_off() { assert!(!credit_is_cut((tw + 50.0, 100.0), &one, Some(&FrameShape::Rectangle))); // Two credits side by side in a frame that holds one. assert!(credit_is_cut((tw + 50.0, 100.0), &two, None)); - // No credit, nothing to cut. + // No credit, or one with no width (empty texts), nothing to cut. + assert!(!credit_is_cut((227.0, 227.0), &[String::new()], Some(&FrameShape::Circle))); assert!(!credit_is_cut((20.0, 20.0), &[], None)); // A shape: a circle that holds it on its widest rows, and one too small for any. assert!(!credit_is_cut((227.0, 227.0), &one, Some(&FrameShape::Circle)));