From 594b889390ee6c437a4317a0148396d6d6d7f492 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 04:21:34 -0500 Subject: [PATCH 1/3] fix(layout): say the rows and columns a table's box leaves out --- crates/engine/src/cmd/layout/elements.rs | 15 ++ crates/engine/src/cmd/layout/export.rs | 15 ++ crates/engine/src/cmd/layout/update.rs | 5 + crates/engine/src/cmd/report.rs | 20 +++ crates/engine/src/tests/layout_table.rs | 182 ++++++++++++++++++++++- crates/render/src/layout.rs | 1 + crates/render/src/layout/picture.rs | 2 +- crates/render/src/layout/table.rs | 99 +++++++++++- crates/render/src/layout/tests.rs | 26 ++++ docs/user-guide/layouts.md | 4 +- 10 files changed, 358 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 36890e16a1..487bd63844 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -278,6 +278,20 @@ pub(in crate::cmd::layout) fn held_rows(p: &Value) -> Option { (n != kept).then(|| format!("rows {n} held to {kept} ({least} to {most})")) } +/// Says the rows and columns the box of the table `id` of layout `li` leaves out (#3416), +/// measured as [`super::text::text_fit_loss`] measures a text; nothing of another element. +pub(in crate::cmd::layout) fn say_table_cut(s: &mut Session, li: usize, id: u32) { + let Some(l) = s.project.layouts.get(li) else { return }; + let mut cut = rustgis_render::layout::tables_cut(l, &s.project.maps, 300.0); + cut.retain(|t| t.id == id); + if let Some(note) = rustgis_render::layout::table_cut_notice(&cut) { + s.warn(note); + } +} + +/// What a table is given that changes what its box holds, or shows it. +pub(in crate::cmd::layout) const TABLE_FIT_KEYS: [&str; 8] = ["w", "h", "rows", "fields", "textSize", "header", "layer", "visible"]; + /// Says what [`held_to_limits`] found, in one notice for the command `title`. pub(in crate::cmd::layout) fn say_held(s: &mut Session, title: &str, held: Vec) { if !held.is_empty() { @@ -779,6 +793,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu if kind == "chart" { say_chart_losses(s, i, id); } + say_table_cut(s, i, id); say_text_fit(s, i, id, true); say_text_statistics(s, i, id); if let Some(said) = empty_colorbar { diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index ca729ff4f3..97130e6a7c 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -79,6 +79,10 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> if let Some(r) = region { clipped.retain(|(id, _)| layout.element(*id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); } + let mut cut = rustgis_render::layout::tables_cut(&layout, &s.project.maps, dpi); + if let Some(r) = region { + cut.retain(|t| layout.element(t.id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); + } let mut gaps: SectionGaps = rustgis_render::layout::sections_not_drawn(&layout, &s.project.maps).into_iter().map(|g| (g, 1)).collect(); if let Some(r) = region { gaps.retain(|g, _| layout.element(g.frame).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); @@ -109,6 +113,9 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> s.warn(note); } say_unfitted_legends(s, &unfitted); + if let Some(note) = rustgis_render::layout::table_cut_notice(&cut) { + s.warn(note); + } for note in chart_notice_lines(&layout, &charts) { s.warn(note); } @@ -329,6 +336,10 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( s.warn(note); } say_unfitted_legends(s, &unfitted); + // A table reads its layer whole, so a series' pages leave the same out: said once. + if let Some(note) = rustgis_render::layout::table_cut_notice(&rustgis_render::layout::tables_cut(&saved, &s.project.maps, dpi)) { + s.warn(note); + } for note in chart_notice_lines(&saved, &charts) { s.warn(note); } @@ -563,6 +574,7 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd let note = rustgis_render::layout::clipped_text_notice(layout, &clipped); 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 cut = rustgis_render::layout::table_cut_notice(&rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi)); 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(|| { @@ -581,6 +593,9 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd s.warn(note); } say_unfitted_legends(s, &unfitted); + if let Some(note) = cut { + s.warn(note); + } for note in chart_notes { s.warn(note); } diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 51a06a6ef4..4f8d546f53 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -844,6 +844,8 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { let excluding = matches!(&e.kind, ElementKind::Legend { .. }) && (p.get("exclude").is_some_and(|v| !v.is_null()) || b(p, "allClasses").is_some()); let fit = tells_legend_fit(&e.kind, p); + // `null` included: it gives a text size or the header back. + let table_fit = TABLE_FIT_KEYS.iter().any(|k| p.get(*k).is_some()); if unremembered { s.notify(picture_unremembered(), false); } @@ -859,6 +861,9 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { if excluding { say_raster_keys(s, li, id); } + if table_fit { + say_table_cut(s, li, id); + } // A chart told what to draw, or coloured by classes, says what it leaves out of it. // Given a maximum, it says the bars past it. if !chart_said.is_empty() diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index f364af07bb..3a0a03b636 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1219,6 +1219,7 @@ fn report_pages_bytes( say_report_unfitted(s, &unfitted); say_report_charts(s, &charts); say_report_clipped(s, &clipped); + say_report_tables(s, pages, 1, dpi); say_sections_not_drawn(s, pages, 1); say_report_pictures(s, pages, 1); let png = super::exports::held_to(download, |limit| rustgis_render::png::within(&img, limit))?; @@ -1257,12 +1258,31 @@ fn report_pages_bytes( say_report_charts(s, &charts); say_report_clipped(s, &clipped); super::layout::pictured_notices(s, &frames_pictured, &pages_pictured); + say_report_tables(s, pages, n, dpi); say_sections_not_drawn(s, pages, n); say_report_pictures(s, pages, n); let pdf = super::exports::held_to(download, |limit| rustgis_render::pdf::write_within(&out, &doc.title, limit))?; Ok((pdf, pages.len())) } +/// Says the tables cut by their boxes (#3416) on the layouts of the first `n` of `pages`, drawn +/// at `dpi`, one notice a layout, which it names; a layout on several pages is said once. +fn say_report_tables(s: &mut Session, pages: &[rustgis_render::report::Page], n: usize, dpi: f64) { + let mut seen = Vec::new(); + for page in pages.iter().take(n) { + let rustgis_render::report::Page::Layout(li) = page else { continue }; + if seen.contains(li) { + continue; + } + seen.push(*li); + let Some(layout) = s.project.layouts.get(*li) else { continue }; + let cut = rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi); + let Some(note) = rustgis_render::layout::table_cut_notice(&cut) else { continue }; + let name = crate::project::short_name(&layout.name); + s.warn(format!("The report, layout \"{name}\": {note}")); + } +} + /// Says the section lines (#2863) the layouts of the first `n` of `pages` don't draw, as the /// layout's own export says them: in one notice however many layouts leave one out, each line named /// with its layout, and a layout on several pages counted once. diff --git a/crates/engine/src/tests/layout_table.rs b/crates/engine/src/tests/layout_table.rs index 9b74636bd3..4de870478e 100644 --- a/crates/engine/src/tests/layout_table.rs +++ b/crates/engine/src/tests/layout_table.rs @@ -1,4 +1,4 @@ -//! A layout table's fields, text size and header (#3409). +//! A layout table's fields, text size and header (#3409), and what its box leaves out (#3416). use super::*; @@ -198,3 +198,183 @@ fn undo_redo_and_a_reopened_project_keep_the_options() { let reopened = Project::from_json(&saved.to_string()).unwrap(); assert_eq!(serde_json::to_value(&reopened.layouts).unwrap(), saved["layouts"]); } + +const ADVICE: &str = "make it larger, reduce its text size, or show fewer rows or fields"; + +/// A layout "Tables" over a map with "Parcels" (4 fields, 20 rows) and "Few" (2 fields, 5 rows). +/// At 8 points a column is 23.8 mm wide and a row 4.5 mm high. +fn parcels() -> Session { + use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as Data}; + let mut s = Session::new(sample::world_project()); + for (name, fields, rows) in [("Parcels", 4, 20), ("Few", 2, 5)] { + let fields: Vec = (1..=fields).map(|i| Field::new(format!("f{i}"), FieldType::Integer)).collect(); + let width = fields.len(); + let mut ds = Dataset::new(name, GeometryType::Point, fields); + for n in 0..rows { + ds.push(Some(Geometry::Point(rustgis_data::Coord::new(0.0, 0.0))), vec![Data::Int(n); width]); + } + s.map_mut().add_dataset(ds); + } + s.run("layout.new", &json!({"name": "Tables"})).unwrap(); + s +} + +/// What running `command` with `p` says of tables cut by their boxes. +fn cut_said(s: &mut Session, command: &str, p: Value) -> Vec { + let mark = s.notice_mark(); + s.run(command, &p).unwrap(); + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("box shows") || t.contains("show only part")).collect() +} + +/// Adds a table of Parcels asking 20 rows in a box of `w` by `h` mm, with `extra` keys; its id +/// and what adding it says. +fn added(s: &mut Session, w: f64, h: f64, extra: Value) -> (u64, Vec) { + let mut p = json!({"kind": "table", "layer": "Parcels", "rows": 20, "x": 10, "y": 10, "w": w, "h": h}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + let said = cut_said(s, "layout.addElement", p); + let id = s.project.layouts[0].elements.last().unwrap().id; + (u64::from(id), said) +} + +/// What is said of the one table `id`, which shows `shown`. +fn cut(s: &Session, id: u64, shown: &str) -> String { + let name = &s.project.layouts[0].element(id as u32).unwrap().name; + format!("Table \"{name}\" ({id}): its box shows {shown}; {ADVICE}") +} + +/// What exporting the layout to a file of `ext` says of its tables. +fn table_exported(s: &mut Session, ext: &str) -> Vec { + let dir = std::env::temp_dir().join(format!("rustgis-3416-{}-{:?}", std::process::id(), std::thread::current().id())); + std::fs::create_dir_all(&dir).unwrap(); + let said = cut_said(s, "layout.export", json!({"path": dir.join(format!("page.{ext}")), "dpi": 36})); + std::fs::remove_dir_all(&dir).unwrap(); + said +} + +#[test] +fn a_table_whose_box_holds_what_it_asks_for_says_nothing() { + let mut s = parcels(); + let (id, said) = added(&mut s, 100.0, 100.0, json!({})); + assert!(said.is_empty(), "{said:?}"); + assert!(cut_said(&mut s, "layout.update", json!({"element": id, "textSize": 7})).is_empty()); + assert!(table_exported(&mut s, "png").is_empty()); + // Rows the layer hasn't are not left out. + let (_, said) = added(&mut s, 100.0, 42.0, json!({"layer": "Few"})); + assert!(said.is_empty(), "{said:?}"); +} + +#[test] +fn a_table_added_says_the_rows_and_columns_its_box_leaves_out() { + let mut s = parcels(); + for (w, h, extra, shown) in [ + (100.0, 42.0, json!({}), "8 of 20 rows"), + (60.0, 100.0, json!({}), "2 of 4 columns"), + (60.0, 100.0, json!({"fields": ["f4", "f3", "f2"]}), "2 of 3 columns"), + (60.0, 42.0, json!({}), "8 of 20 rows and 2 of 4 columns"), + (100.0, 42.0, json!({"header": false}), "9 of 20 rows"), + (100.0, 42.0, json!({"textSize": 14}), "4 of 20 rows and 2 of 4 columns"), + (100.0, 3.0, json!({}), "0 of 20 rows"), + ] { + let (id, said) = added(&mut s, w, h, extra.clone()); + assert_eq!(said, [cut(&s, id, shown)], "{w}x{h} {extra}"); + } +} + +#[test] +fn a_change_that_moves_what_fits_says_it_and_another_does_not() { + let mut s = parcels(); + let (id, _) = added(&mut s, 100.0, 100.0, json!({"layer": "Few"})); + let update = |s: &mut Session, mut p: Value| { + p["element"] = json!(id); + cut_said(s, "layout.update", p) + }; + assert_eq!(update(&mut s, json!({"h": 20})), [cut(&s, id, "3 of 5 rows")]); + assert_eq!(update(&mut s, json!({"w": 30})), [cut(&s, id, "3 of 5 rows and 1 of 2 columns")]); + for quiet in [json!({"color": "#112233"}), json!({"name": "Totals"}), json!({"x": 12, "y": 12})] { + assert!(update(&mut s, quiet.clone()).is_empty(), "{quiet}"); + } + assert!(update(&mut s, json!({"w": 100, "h": 100})).is_empty()); + assert_eq!(update(&mut s, json!({"w": 60, "layer": "Parcels"})), [cut(&s, id, "2 of 4 columns")]); + assert_eq!(update(&mut s, json!({"h": 42})), [cut(&s, id, "8 of 20 rows and 2 of 4 columns")]); + assert_eq!(update(&mut s, json!({"rows": 3})), [cut(&s, id, "2 of 4 columns")]); + assert!(update(&mut s, json!({"fields": ["f1"]})).is_empty()); + assert_eq!(update(&mut s, json!({"textSize": 100})).len(), 1); + assert!(update(&mut s, json!({"textSize": 8})).is_empty()); + assert_eq!(update(&mut s, json!({"h": 3, "header": true})), [cut(&s, id, "0 of 3 rows")]); +} + +#[test] +fn a_table_that_draws_nothing_of_its_box_says_nothing() { + let mut s = parcels(); + // Off the page. + let (_, said) = added(&mut s, 60.0, 42.0, json!({"x": 2000})); + assert!(said.is_empty(), "{said:?}"); + // Hidden. + let (id, _) = added(&mut s, 60.0, 42.0, json!({})); + s.run("layout.update", &json!({"element": id, "visible": false})).unwrap(); + assert!(table_exported(&mut s, "png").is_empty()); + // Its layer gone: a placeholder. + s.run("layout.update", &json!({"element": id, "visible": true})).unwrap(); + assert_eq!(table_exported(&mut s, "png").len(), 1); + let layer = s.map().layer_by_name("Parcels").unwrap().id; + s.map_mut().layers.retain(|l| l.id != layer); + assert!(table_exported(&mut s, "png").is_empty()); +} + +#[test] +fn an_export_says_the_tables_cut_in_one_notice() { + let mut s = parcels(); + let (a, _) = added(&mut s, 100.0, 42.0, json!({})); + let one = cut(&s, a, "8 of 20 rows"); + for ext in ["png", "pdf", "svg"] { + assert_eq!(table_exported(&mut s, ext), std::slice::from_ref(&one), "{ext}"); + } + let (b, _) = added(&mut s, 60.0, 100.0, json!({"y": 100})); + let name = |id: u64| s.project.layouts[0].element(id as u32).unwrap().name.clone(); + let both = format!( + "2 tables show only part of what they are asked to: \"{}\" ({a}) 8 of 20 rows; \"{}\" ({b}) 2 of 4 columns; make them larger, reduce their text size, or show fewer rows or fields", + name(a), + name(b) + ); + for ext in ["png", "pdf", "svg"] { + assert_eq!(table_exported(&mut s, ext), std::slice::from_ref(&both), "{ext}"); + } +} + +#[test] +fn a_region_says_the_tables_it_shows_alone() { + let mut s = parcels(); + let (id, _) = added(&mut s, 100.0, 42.0, json!({})); + let one = cut(&s, id, "8 of 20 rows"); + for (region, want) in [([0.0, 0.0, 50.0, 30.0], vec![one]), ([150.0, 150.0, 40.0, 40.0], vec![])] { + let mark = s.notice_mark(); + crate::cmd::layout::layout_png(&mut s, 0, 36.0, Some(region)).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("box shows")).collect(); + assert_eq!(said, want, "{region:?}"); + } +} + +#[test] +fn a_map_series_says_a_cut_table_once() { + let mut s = parcels(); + let (id, _) = added(&mut s, 100.0, 42.0, json!({})); + s.run("layout.series", &json!({"layer": "Few", "nameField": "f1"})).unwrap(); + assert_eq!(table_exported(&mut s, "pdf"), [cut(&s, id, "8 of 20 rows")]); +} + +#[test] +fn a_report_says_the_tables_cut_on_its_layout_pages() { + let mut s = parcels(); + let (id, _) = added(&mut s, 100.0, 42.0, json!({})); + s.run("report.new", &json!({"layer": "Few", "name": "R"})).unwrap(); + for _ in 0..2 { + s.run("report.existingTemplate", &json!({"report": "R", "layout": "Tables", "end": true})).unwrap(); + } + let dir = std::env::temp_dir().join(format!("rustgis-3416r-{}-{:?}", std::process::id(), std::thread::current().id())); + std::fs::create_dir_all(&dir).unwrap(); + let said = cut_said(&mut s, "report.export", json!({"report": "R", "path": dir.join("r.pdf"), "dpi": 36})); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(said, [format!("The report, layout \"Tables\": {}", cut(&s, id, "8 of 20 rows"))]); +} diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index ead02800cc..3b8ac811fd 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -51,6 +51,7 @@ pub use scale_bar::*; pub use section::*; use swatch::*; use table::*; +pub use table::{TableCut, table_cut_notice, tables_cut}; pub use textbox::*; /// Page values for dynamic text. diff --git a/crates/render/src/layout/picture.rs b/crates/render/src/layout/picture.rs index 9257ef4eb7..d003a038ea 100644 --- a/crates/render/src/layout/picture.rs +++ b/crates/render/src/layout/picture.rs @@ -100,7 +100,7 @@ pub fn pictures_not_drawn(layout: &Layout) -> Vec { /// `s` as a notice shows it: its first [`NAME_CHARS`] characters, with "…" after them when it /// has more. -fn notice_cut(s: &str) -> String { +pub(super) fn notice_cut(s: &str) -> String { match s.char_indices().nth(NAME_CHARS) { Some((end, _)) => format!("{}…", s.get(..end).unwrap_or(s)), None => s.to_string(), diff --git a/crates/render/src/layout/table.rs b/crates/render/src/layout/table.rs index 185ea2b773..4ccbfba5f8 100644 --- a/crates/render/src/layout/table.rs +++ b/crates/render/src/layout/table.rs @@ -13,19 +13,103 @@ pub(super) struct TableLook<'a> { pub header: bool, } +/// How much of a table its box holds: the size it draws at and the columns and rows shown. +pub(super) struct TableFit { + pt: f32, + px: f32, + row_h: f32, + col_w: f32, + /// Columns drawn; one even in a layer without fields. + pub cols: usize, + /// Rows drawn under the header. + pub rows: usize, +} + +/// What a table of a layer with `fields` fields and `features` features shows in `r`: what +/// [`table`] draws and [`tables_cut`] counts. +pub(super) fn table_fit(r: Rect, look: TableLook, fields: usize, features: usize, ppp: f32) -> TableFit { + let pt = rustgis_map::layout::layout_text_in_range(look.text_size, TABLE_TEXT_PT) as f32; + let px = pt * 1.33 * ppp; + let row_h = px * 1.6; + // 90 points wide at the default size, and in proportion at another. + let col_w = (90.0 * (pt / TABLE_TEXT_PT as f32) * ppp).min(r.width()); + let cols = ((r.width() / col_w).floor() as usize).clamp(1, asked_columns(look, fields).max(1)); + let head = usize::from(look.header); + let rows = look.rows.min(features).min(((r.height() / row_h) as usize).saturating_sub(head)); + TableFit { pt, px, row_h, col_w, cols, rows } +} + +/// The columns a table is asked to show: its fields, or without any the layer's own. +fn asked_columns(look: TableLook, fields: usize) -> usize { + if look.fields.is_empty() { fields } else { look.fields.len() } +} + +/// A table whose box leaves out rows or columns it is asked to show, each as shown and asked. +#[derive(Debug, Clone, PartialEq)] +pub struct TableCut { + pub id: u32, + pub name: String, + pub rows: (usize, usize), + pub cols: (usize, usize), +} + +/// The tables of `layout` drawn at `dpi` whose boxes don't hold the rows and columns they are +/// asked to show (#3416). A hidden table, one with none of its box on the page and one drawn as a +/// placeholder (no frame, map or layer) show nothing to count. +pub fn tables_cut(layout: &Layout, maps: &[Map], dpi: f64) -> Vec { + let k = page_geometry(layout, dpi).2; + let ppp = (k / PT_PER_MM) as f32; + let cut = layout.elements.iter().filter(|e| e.visible && on_page(layout, e)).filter_map(|e| { + let ElementKind::Table { frame, layer, rows, fields, text_size, header, .. } = &e.kind else { return None }; + let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; + let ds = &maps.get(map_index(maps, map)?)?.layer_by_name(layer)?.dataset; + // At least a pixel each way, as the page draws it. + let r = Rect::from_xywh((e.x * k) as f32, (e.y * k) as f32, ((e.w * k) as f32).max(1.0), ((e.h * k) as f32).max(1.0))?; + let look = TableLook { rows: *rows, fields, text_size: *text_size, header: *header }; + let fit = table_fit(r, look, ds.fields.len(), ds.features.len(), ppp); + let asked = asked_columns(look, ds.fields.len()); + let rows = (fit.rows, (*rows).min(ds.features.len())); + let cols = (fit.cols.min(asked), asked); + (rows.0 < rows.1 || cols.0 < cols.1).then(|| TableCut { id: e.id, name: e.name.clone(), rows, cols }) + }); + cut.collect() +} + +/// One notice for the tables [`tables_cut`] found: each with what it shows of what it is asked +/// to, the first ten by name and id, and how many more. `None` when there are none. +pub fn table_cut_notice(cut: &[TableCut]) -> Option { + let shown = |t: &TableCut| { + let part = |(shown, asked): (usize, usize), what: &str| (shown < asked).then(|| format!("{shown} of {asked} {what}")); + [part(t.rows, "rows"), part(t.cols, "columns")].into_iter().flatten().collect::>().join(" and ") + }; + let named = |t: &TableCut| format!("\"{}\" ({})", notice_cut(&t.name), t.id); + match cut { + [] => None, + [t] => Some(format!( + "Table {}: its box shows {}; make it larger, reduce its text size, or show fewer rows or fields", + named(t), + shown(t) + )), + _ => { + let mut each = cut.iter().take(10).map(|t| format!("{} {}", named(t), shown(t))).collect::>().join("; "); + if cut.len() > 10 { + each.push_str(&format!("; and {} more", cut.len() - 10)); + } + Some(format!( + "{} tables show only part of what they are asked to: {each}; make them larger, reduce their text size, or show fewer rows or fields", + cut.len() + )) + } + } +} + /// The first rows of a table, with as many columns as fit: on white cells in dark grey, or /// with an `ink` (#2257) in it on no paper of its own, its header and stripes a tint of the ink, so /// it reads on whatever is behind it (a dark page, or the element's background). A column whose /// field the layer hasn't (removed or renamed since) keeps its name, its cells a dash. pub(super) fn table(pm: &mut Canvas, r: Rect, ds: &rustgis_data::Dataset, look: TableLook, ink: Option, ppp: f64) { let ppp = ppp as f32; - let pt = rustgis_map::layout::layout_text_in_range(look.text_size, TABLE_TEXT_PT) as f32; - let px = pt * 1.33 * ppp; - let row_h = px * 1.6; - // 90 points wide at the default size, and in proportion at another. - let col_w = (90.0 * (pt / TABLE_TEXT_PT as f32) * ppp).min(r.width()); - let count = if look.fields.is_empty() { ds.fields.len() } else { look.fields.len() }; - let cols = ((r.width() / col_w).floor() as usize).clamp(1, count.max(1)); + let TableFit { pt, px, row_h, col_w, cols, rows: n } = table_fit(r, look, ds.fields.len(), ds.features.len(), ppp); // Each column shown: its field's place in the layer, and its heading. let columns: Vec<(Option, &str)> = if look.fields.is_empty() { ds.fields.iter().enumerate().take(cols).map(|(i, f)| (Some(i), f.display())).collect() @@ -41,7 +125,6 @@ pub(super) fn table(pm: &mut Canvas, r: Rect, ds: &rustgis_data::Dataset, look: .collect() }; let head = usize::from(look.header); - let n = look.rows.min(ds.features.len()).min(((r.height() / row_h) as usize).saturating_sub(head)); let dark = ink.unwrap_or(INK); // Without an ink, the white paper, header and stripes it always had, so a table drawn before // draws to the same pixels. With one, white cells could hide a light ink. diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 433cb02d45..08d8a5d43d 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -9025,3 +9025,29 @@ fn a_legend_counts_graduated_ranges_and_missing_values() { assert_eq!(said, [("Low", Some(2)), ("High", Some(1)), ("No data", Some(1))]); assert_eq!(total, 4); } + +/// What [`table_fit`] counts is what [`table`] paints, at either resolution (#3416). +#[test] +fn a_tables_fit_is_what_it_draws() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, Value}; + let fields = (1..=4).map(|i| Field::new(format!("f{i}"), FieldType::Integer)).collect(); + let mut ds = Dataset::new("t", GeometryType::Point, fields); + for n in 0..20 { + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Int(n); 4]); + } + for (ppp, header) in [(1.0_f32, true), (1.0, false), (3.125, true), (3.125, false)] { + let (w, h) = ((200.0 * ppp) as u32, (120.0 * ppp) as u32); + let r = Rect::from_xywh(0.0, 0.0, w as f32, h as f32).unwrap(); + let look = TableLook { rows: 20, fields: &[], text_size: 8.0, header }; + let fit = table_fit(r, look, ds.fields.len(), ds.features.len(), ppp); + assert_eq!((fit.cols, fit.rows), (2, if header { 6 } else { 7 }), "{ppp} {header}"); + let mut c = Canvas::new(w, h).unwrap(); + table(&mut c, r, &ds, look, None, f64::from(ppp)); + // The white paper's right and bottom ends: two columns of 90, and its rows of 17.024. + let painted = c.pixmap().pixels().iter().enumerate().filter(|(_, p)| p.alpha() > 0); + let (right, bottom) = painted.fold((0, 0), |(x, y), (i, _)| (x.max(i as u32 % w + 1), y.max(i as u32 / w + 1))); + let lines = (fit.rows + usize::from(header)) as f32; + assert!((right as f32 - 180.0 * ppp).abs() <= 1.0, "{right}"); + assert!((bottom as f32 - lines * 17.024 * ppp).abs() <= 1.0, "{bottom}"); + } +} diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 1263f5b1c7..53541c741a 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -852,7 +852,9 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu `layout.update={"element":6,"fields":["NAME","POP"],"textSize":10,"header":false}`. `"fields":[]` shows every field again, and another layer without fields of its own does too. A field removed or renamed afterwards keeps its column, headed by that name over a dash in every row, until the - layer has a field of exactly that name again, which the column then shows. + layer has a field of exactly that name again, which the column then shows. When its box doesn't + hold the rows and columns it is asked to show, adding or changing the table says how many it + shows, and so does an export or a report. - **Chart frame**: a bar chart of a layer of the frame's map. Its properties pick the **Layer** and the numeric **Field**, and by default draw a bar per feature, the largest first, each labelled by the **Label** field. **Group by** a field draws a bar per value of that field From 7868f33f96ca4296af9c149b24af121b88f6cf97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 04:49:12 -0500 Subject: [PATCH 2/3] fix(layout): a report says its cut tables in one notice --- crates/engine/src/cmd/layout/update.rs | 4 ++-- crates/engine/src/cmd/report.rs | 15 +++++++++----- crates/engine/src/tests/layout_table.rs | 27 ++++++++++++++++++++++++- crates/render/src/layout/table.rs | 19 +++++++++++++---- 4 files changed, 53 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 4f8d546f53..62e14811c0 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -845,7 +845,7 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { matches!(&e.kind, ElementKind::Legend { .. }) && (p.get("exclude").is_some_and(|v| !v.is_null()) || b(p, "allClasses").is_some()); let fit = tells_legend_fit(&e.kind, p); // `null` included: it gives a text size or the header back. - let table_fit = TABLE_FIT_KEYS.iter().any(|k| p.get(*k).is_some()); + let tells_table_fit = TABLE_FIT_KEYS.iter().any(|k| p.get(*k).is_some()); if unremembered { s.notify(picture_unremembered(), false); } @@ -861,7 +861,7 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { if excluding { say_raster_keys(s, li, id); } - if table_fit { + if tells_table_fit { say_table_cut(s, li, id); } // A chart told what to draw, or coloured by classes, says what it leaves out of it. diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 3a0a03b636..aeea2006f2 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1266,9 +1266,11 @@ fn report_pages_bytes( } /// Says the tables cut by their boxes (#3416) on the layouts of the first `n` of `pages`, drawn -/// at `dpi`, one notice a layout, which it names; a layout on several pages is said once. +/// at `dpi`, in one notice however many layouts cut one, each table named with its layout; a +/// layout on several pages is counted once. fn say_report_tables(s: &mut Session, pages: &[rustgis_render::report::Page], n: usize, dpi: f64) { let mut seen = Vec::new(); + let mut cut = Vec::new(); for page in pages.iter().take(n) { let rustgis_render::report::Page::Layout(li) = page else { continue }; if seen.contains(li) { @@ -1276,10 +1278,13 @@ fn say_report_tables(s: &mut Session, pages: &[rustgis_render::report::Page], n: } seen.push(*li); let Some(layout) = s.project.layouts.get(*li) else { continue }; - let cut = rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi); - let Some(note) = rustgis_render::layout::table_cut_notice(&cut) else { continue }; - let name = crate::project::short_name(&layout.name); - s.warn(format!("The report, layout \"{name}\": {note}")); + for mut table in rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi) { + table.layout = Some(layout.name.clone()); + cut.push(table); + } + } + if let Some(note) = rustgis_render::layout::table_cut_notice(&cut) { + s.warn(format!("The report: {note}")); } } diff --git a/crates/engine/src/tests/layout_table.rs b/crates/engine/src/tests/layout_table.rs index 4de870478e..69621a46d8 100644 --- a/crates/engine/src/tests/layout_table.rs +++ b/crates/engine/src/tests/layout_table.rs @@ -376,5 +376,30 @@ fn a_report_says_the_tables_cut_on_its_layout_pages() { std::fs::create_dir_all(&dir).unwrap(); let said = cut_said(&mut s, "report.export", json!({"report": "R", "path": dir.join("r.pdf"), "dpi": 36})); std::fs::remove_dir_all(&dir).unwrap(); - assert_eq!(said, [format!("The report, layout \"Tables\": {}", cut(&s, id, "8 of 20 rows"))]); + let one = cut(&s, id, "8 of 20 rows").replace(&format!("({id}):"), &format!("({id}) in \"Tables\":")); + assert_eq!(said, [format!("The report: {one}")]); +} + +#[test] +fn a_report_says_the_tables_cut_on_several_layouts_in_one_notice() { + let mut s = parcels(); + let (first, _) = added(&mut s, 100.0, 42.0, json!({})); + s.run("layout.new", &json!({"name": "More"})).unwrap(); + s.run("layout.addElement", &json!({"layout": 1, "kind": "table", "layer": "Parcels", "rows": 20, "w": 60, "h": 100})).unwrap(); + let second = s.project.layouts[1].elements.last().unwrap().id; + s.run("report.new", &json!({"layer": "Few", "name": "R"})).unwrap(); + for layout in ["Tables", "More"] { + s.run("report.existingTemplate", &json!({"report": "R", "layout": layout, "end": true})).unwrap(); + } + let dir = std::env::temp_dir().join(format!("rustgis-3416m-{}-{:?}", std::process::id(), std::thread::current().id())); + std::fs::create_dir_all(&dir).unwrap(); + let said = cut_said(&mut s, "report.export", json!({"report": "R", "path": dir.join("r.pdf"), "dpi": 36})); + std::fs::remove_dir_all(&dir).unwrap(); + let name = |li: usize, id: u32| s.project.layouts[li].element(id).unwrap().name.clone(); + let want = format!( + "The report: 2 tables show only part of what they are asked to: \"{}\" ({first}) in \"Tables\" 8 of 20 rows; \"{}\" ({second}) in \"More\" 2 of 4 columns; make them larger, reduce their text size, or show fewer rows or fields", + name(0, first as u32), + name(1, second) + ); + assert_eq!(said, [want]); } diff --git a/crates/render/src/layout/table.rs b/crates/render/src/layout/table.rs index 4ccbfba5f8..59fd8b0995 100644 --- a/crates/render/src/layout/table.rs +++ b/crates/render/src/layout/table.rs @@ -49,6 +49,8 @@ fn asked_columns(look: TableLook, fields: usize) -> usize { pub struct TableCut { pub id: u32, pub name: String, + /// Its layout's name, said with it: set by a report, whose pages draw several. + pub layout: Option, pub rows: (usize, usize), pub cols: (usize, usize), } @@ -68,9 +70,15 @@ pub fn tables_cut(layout: &Layout, maps: &[Map], dpi: f64) -> Vec { let look = TableLook { rows: *rows, fields, text_size: *text_size, header: *header }; let fit = table_fit(r, look, ds.fields.len(), ds.features.len(), ppp); let asked = asked_columns(look, ds.fields.len()); - let rows = (fit.rows, (*rows).min(ds.features.len())); - let cols = (fit.cols.min(asked), asked); - (rows.0 < rows.1 || cols.0 < cols.1).then(|| TableCut { id: e.id, name: e.name.clone(), rows, cols }) + let shown_rows = (fit.rows, (*rows).min(ds.features.len())); + let shown_cols = (fit.cols.min(asked), asked); + (shown_rows.0 < shown_rows.1 || shown_cols.0 < shown_cols.1).then(|| TableCut { + id: e.id, + name: e.name.clone(), + layout: None, + rows: shown_rows, + cols: shown_cols, + }) }); cut.collect() } @@ -82,7 +90,10 @@ pub fn table_cut_notice(cut: &[TableCut]) -> Option { let part = |(shown, asked): (usize, usize), what: &str| (shown < asked).then(|| format!("{shown} of {asked} {what}")); [part(t.rows, "rows"), part(t.cols, "columns")].into_iter().flatten().collect::>().join(" and ") }; - let named = |t: &TableCut| format!("\"{}\" ({})", notice_cut(&t.name), t.id); + let named = |t: &TableCut| { + let layout = t.layout.as_ref().map(|l| format!(" in \"{}\"", notice_cut(l))).unwrap_or_default(); + format!("\"{}\" ({}){layout}", notice_cut(&t.name), t.id) + }; match cut { [] => None, [t] => Some(format!( From d8e236409fbd1d2c90f4f2c6183e8eaee409b6f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 05:15:42 -0500 Subject: [PATCH 3/3] fix(layout): count a table's cut after each page is drawn --- crates/engine/src/cmd/layout/elements.rs | 2 + crates/engine/src/cmd/layout/export.rs | 21 +++-- crates/engine/src/cmd/report.rs | 36 ++++---- crates/engine/src/tests/layout_table.rs | 101 +++++++++++++++++------ 4 files changed, 112 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 487bd63844..257e479f74 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -282,6 +282,8 @@ pub(in crate::cmd::layout) fn held_rows(p: &Value) -> Option { /// measured as [`super::text::text_fit_loss`] measures a text; nothing of another element. pub(in crate::cmd::layout) fn say_table_cut(s: &mut Session, li: usize, id: u32) { let Some(l) = s.project.layouts.get(li) else { return }; + // The counts don't depend on the resolution: the box, its columns and its rows scale with it. + // Nothing is drawn here, so a layer read in place counts the rows it holds now. let mut cut = rustgis_render::layout::tables_cut(l, &s.project.maps, 300.0); cut.retain(|t| t.id == id); if let Some(note) = rustgis_render::layout::table_cut_notice(&cut) { diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index 97130e6a7c..d885cf1a5d 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -79,10 +79,6 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> if let Some(r) = region { clipped.retain(|(id, _)| layout.element(*id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); } - let mut cut = rustgis_render::layout::tables_cut(&layout, &s.project.maps, dpi); - if let Some(r) = region { - cut.retain(|t| layout.element(t.id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); - } let mut gaps: SectionGaps = rustgis_render::layout::sections_not_drawn(&layout, &s.project.maps).into_iter().map(|g| (g, 1)).collect(); if let Some(r) = region { gaps.retain(|g, _| layout.element(g.frame).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); @@ -105,7 +101,10 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> }) }); let img = img?; + // After drawing: a layer read in place holds the rows its frame just read. + let mut cut = rustgis_render::layout::tables_cut(&layout, &s.project.maps, dpi); if let Some(r) = region { + 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))); } @@ -235,6 +234,8 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( let mut clipped = BTreeMap::new(); let mut gaps = SectionGaps::new(); let mut profiles = ProfileNotes::new(); + // Each table cut on a page, as its first such page cut it. + let mut cut = BTreeMap::new(); let render_pages = || -> Result<(Vec, Option>), String> { let mut out = Vec::new(); let mut png = None; @@ -302,6 +303,12 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( let img = rustgis_render::layout::render(layout, &mut s.project.maps, dpi, &info)?; png = Some(crate::cmd::exports::held_to(download, |limit| rustgis_render::png::within(&img, limit))?); } + // Counted once the page is drawn: a layer read in place holds that page's rows. + if let Some(layout) = s.project.layouts.get(li) { + for table in rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi) { + cut.entry(table.id).or_insert(table); + } + } // A cancelled export stops here, its layout put back below. rustgis_data::progress::step(1).map_err(|e| e.to_string())?; } @@ -336,8 +343,7 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( s.warn(note); } say_unfitted_legends(s, &unfitted); - // A table reads its layer whole, so a series' pages leave the same out: said once. - if let Some(note) = rustgis_render::layout::table_cut_notice(&rustgis_render::layout::tables_cut(&saved, &s.project.maps, dpi)) { + if let Some(note) = rustgis_render::layout::table_cut_notice(&cut.into_values().collect::>()) { s.warn(note); } for note in chart_notice_lines(&saved, &charts) { @@ -574,7 +580,6 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd let note = rustgis_render::layout::clipped_text_notice(layout, &clipped); 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 cut = rustgis_render::layout::table_cut_notice(&rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi)); 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(|| { @@ -585,6 +590,8 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd }); let (text, pictured) = drawn?; let chart_notes = chart_notice_lines(layout, &charts); + // After drawing, as the other exports count. + let cut = rustgis_render::layout::table_cut_notice(&rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi)); for note in [note, rustgis_render::layout::sections_notice(&gaps, 1)].into_iter().flatten() { s.warn(note); } diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index aeea2006f2..5b6ef5db2a 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1191,6 +1191,8 @@ fn report_pages_bytes( let (mut unfitted, mut charts) = (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. + let mut tables = Vec::new(); // Counted, and stopped on Cancel, a page at a time. rustgis_data::progress::begin(n); for k in 0..n { @@ -1214,12 +1216,13 @@ fn report_pages_bytes( let (drawn, listed, shown) = 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); say_report_unfitted(s, &unfitted); say_report_charts(s, &charts); say_report_clipped(s, &clipped); - say_report_tables(s, pages, 1, dpi); + say_report_tables(s, tables); say_sections_not_drawn(s, pages, 1); say_report_pictures(s, pages, 1); let png = super::exports::held_to(download, |limit| rustgis_render::png::within(&img, limit))?; @@ -1228,6 +1231,7 @@ fn report_pages_bytes( let (drawn, listed, shown) = 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); if page.overflowed() { @@ -1258,31 +1262,29 @@ fn report_pages_bytes( say_report_charts(s, &charts); say_report_clipped(s, &clipped); super::layout::pictured_notices(s, &frames_pictured, &pages_pictured); - say_report_tables(s, pages, n, dpi); + say_report_tables(s, tables); say_sections_not_drawn(s, pages, n); say_report_pictures(s, pages, n); let pdf = super::exports::held_to(download, |limit| rustgis_render::pdf::write_within(&out, &doc.title, limit))?; Ok((pdf, pages.len())) } -/// Says the tables cut by their boxes (#3416) on the layouts of the first `n` of `pages`, drawn -/// at `dpi`, in one notice however many layouts cut one, each table named with its layout; a -/// layout on several pages is counted once. -fn say_report_tables(s: &mut Session, pages: &[rustgis_render::report::Page], n: usize, dpi: f64) { - let mut seen = Vec::new(); - let mut cut = Vec::new(); - for page in pages.iter().take(n) { - let rustgis_render::report::Page::Layout(li) = page else { continue }; - if seen.contains(li) { - continue; - } - seen.push(*li); - let Some(layout) = s.project.layouts.get(*li) else { continue }; - for mut table in rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi) { +/// Keeps the tables the layout just drawn, `layout` by its index, cuts at `dpi` (#3416), each +/// with its layout's name: counted after the page is drawn, as a layer read in place then holds +/// that page's rows. A table a layout cut on an earlier page is kept as it was. +fn keep_tables(s: &Session, kept: &mut Vec<(usize, rustgis_render::layout::TableCut)>, layout: Option, dpi: f64) { + let Some((li, layout)) = layout.and_then(|li| Some((li, s.project.layouts.get(li)?))) else { return }; + for mut table in rustgis_render::layout::tables_cut(layout, &s.project.maps, dpi) { + if !kept.iter().any(|(at, t)| *at == li && t.id == table.id) { table.layout = Some(layout.name.clone()); - cut.push(table); + kept.push((li, table)); } } +} + +/// Says the tables [`keep_tables`] kept in one notice however many layouts cut one. +fn say_report_tables(s: &mut Session, kept: Vec<(usize, rustgis_render::layout::TableCut)>) { + let cut: Vec<_> = kept.into_iter().map(|(_, table)| table).collect(); if let Some(note) = rustgis_render::layout::table_cut_notice(&cut) { s.warn(format!("The report: {note}")); } diff --git a/crates/engine/src/tests/layout_table.rs b/crates/engine/src/tests/layout_table.rs index 69621a46d8..2329247bb5 100644 --- a/crates/engine/src/tests/layout_table.rs +++ b/crates/engine/src/tests/layout_table.rs @@ -244,13 +244,43 @@ fn cut(s: &Session, id: u64, shown: &str) -> String { format!("Table \"{name}\" ({id}): its box shows {shown}; {ADVICE}") } +/// 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-3416-{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(); + } +} + /// What exporting the layout to a file of `ext` says of its tables. fn table_exported(s: &mut Session, ext: &str) -> Vec { - let dir = std::env::temp_dir().join(format!("rustgis-3416-{}-{:?}", std::process::id(), std::thread::current().id())); - std::fs::create_dir_all(&dir).unwrap(); - let said = cut_said(s, "layout.export", json!({"path": dir.join(format!("page.{ext}")), "dpi": 36})); - std::fs::remove_dir_all(&dir).unwrap(); - said + let dir = Dir::new("export"); + cut_said(s, "layout.export", json!({"path": dir.0.join(format!("page.{ext}")), "dpi": 36})) +} + +/// What a report "R" drawing each of `layouts` as a page after its own says of tables, exported +/// to a file of `ext`. +fn reported(s: &mut Session, layouts: &[&str], ext: &str) -> Vec { + s.run("report.new", &json!({"layer": "Few", "name": "R"})).unwrap(); + for layout in layouts { + s.run("report.existingTemplate", &json!({"report": "R", "layout": layout, "end": true})).unwrap(); + } + let dir = Dir::new("report"); + cut_said(s, "report.export", json!({"report": "R", "path": dir.0.join(format!("r.{ext}")), "dpi": 36})) +} + +/// `said` of the table `id`, as a report says it: naming its layout. +fn in_layout(said: &str, id: u64, layout: &str) -> String { + said.replace(&format!("({id}):"), &format!("({id}) in \"{layout}\":")) } #[test] @@ -315,9 +345,10 @@ fn a_table_that_draws_nothing_of_its_box_says_nothing() { let (id, _) = added(&mut s, 60.0, 42.0, json!({})); s.run("layout.update", &json!({"element": id, "visible": false})).unwrap(); assert!(table_exported(&mut s, "png").is_empty()); - // Its layer gone: a placeholder. + // Shown again, it is cut. s.run("layout.update", &json!({"element": id, "visible": true})).unwrap(); assert_eq!(table_exported(&mut s, "png").len(), 1); + // Its layer gone: a placeholder. let layer = s.map().layer_by_name("Parcels").unwrap().id; s.map_mut().layers.retain(|l| l.id != layer); assert!(table_exported(&mut s, "png").is_empty()); @@ -368,16 +399,8 @@ fn a_map_series_says_a_cut_table_once() { fn a_report_says_the_tables_cut_on_its_layout_pages() { let mut s = parcels(); let (id, _) = added(&mut s, 100.0, 42.0, json!({})); - s.run("report.new", &json!({"layer": "Few", "name": "R"})).unwrap(); - for _ in 0..2 { - s.run("report.existingTemplate", &json!({"report": "R", "layout": "Tables", "end": true})).unwrap(); - } - let dir = std::env::temp_dir().join(format!("rustgis-3416r-{}-{:?}", std::process::id(), std::thread::current().id())); - std::fs::create_dir_all(&dir).unwrap(); - let said = cut_said(&mut s, "report.export", json!({"report": "R", "path": dir.join("r.pdf"), "dpi": 36})); - std::fs::remove_dir_all(&dir).unwrap(); - let one = cut(&s, id, "8 of 20 rows").replace(&format!("({id}):"), &format!("({id}) in \"Tables\":")); - assert_eq!(said, [format!("The report: {one}")]); + let said = reported(&mut s, &["Tables", "Tables"], "pdf"); + assert_eq!(said, [format!("The report: {}", in_layout(&cut(&s, id, "8 of 20 rows"), id, "Tables"))]); } #[test] @@ -387,14 +410,7 @@ fn a_report_says_the_tables_cut_on_several_layouts_in_one_notice() { s.run("layout.new", &json!({"name": "More"})).unwrap(); s.run("layout.addElement", &json!({"layout": 1, "kind": "table", "layer": "Parcels", "rows": 20, "w": 60, "h": 100})).unwrap(); let second = s.project.layouts[1].elements.last().unwrap().id; - s.run("report.new", &json!({"layer": "Few", "name": "R"})).unwrap(); - for layout in ["Tables", "More"] { - s.run("report.existingTemplate", &json!({"report": "R", "layout": layout, "end": true})).unwrap(); - } - let dir = std::env::temp_dir().join(format!("rustgis-3416m-{}-{:?}", std::process::id(), std::thread::current().id())); - std::fs::create_dir_all(&dir).unwrap(); - let said = cut_said(&mut s, "report.export", json!({"report": "R", "path": dir.join("r.pdf"), "dpi": 36})); - std::fs::remove_dir_all(&dir).unwrap(); + let said = reported(&mut s, &["Tables", "More"], "pdf"); let name = |li: usize, id: u32| s.project.layouts[li].element(id).unwrap().name.clone(); let want = format!( "The report: 2 tables show only part of what they are asked to: \"{}\" ({first}) in \"Tables\" 8 of 20 rows; \"{}\" ({second}) in \"More\" 2 of 4 columns; make them larger, reduce their text size, or show fewer rows or fields", @@ -403,3 +419,40 @@ fn a_report_says_the_tables_cut_on_several_layouts_in_one_notice() { ); assert_eq!(said, [want]); } + +/// Parcels read in place: its table lists the rows the page's frame read, so an export counts them +/// once it has drawn. +#[test] +fn an_export_counts_a_layer_read_in_place_after_drawing_it() { + let features: Vec = (0..20) + .map(|n| json!({"type": "Feature", "properties": {"f1": n}, "geometry": {"type": "Point", "coordinates": [f64::from(n), 0.0]}})) + .collect(); + let dir = Dir::new("streamed"); + let data = dir.0.join("streamed.geojson"); + std::fs::write(&data, json!({"type": "FeatureCollection", "features": features}).to_string()).unwrap(); + for ext in ["png", "pdf", "svg", "report.pdf", "report.png", "region"] { + let mut s = parcels(); + s.run("layer.addData", &json!({"path": data.display().to_string(), "stream": true, "name": "Streamed"})).unwrap(); + // Nothing read yet, so nothing to count. + let (id, said) = added(&mut s, 100.0, 42.0, json!({"layer": "Streamed"})); + assert!(said.is_empty(), "{ext}: {said:?}"); + let one = cut(&s, id, "8 of 20 rows"); + let (said, want) = match ext { + "region" => { + let mark = s.notice_mark(); + crate::cmd::layout::layout_png(&mut s, 0, 36.0, Some([0.0, 0.0, 50.0, 30.0])).unwrap(); + let said = s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("box shows")).collect(); + (said, one) + } + "report.pdf" => (reported(&mut s, &["Tables"], "pdf"), format!("The report: {}", in_layout(&one, id, "Tables"))), + "report.png" => { + s.run("report.new", &json!({"layer": "Few", "name": "R"})).unwrap(); + s.run("report.existingTemplate", &json!({"report": "R", "layout": "Tables"})).unwrap(); + let said = cut_said(&mut s, "report.export", json!({"report": "R", "path": dir.0.join("first.png"), "dpi": 36})); + (said, format!("The report: {}", in_layout(&one, id, "Tables"))) + } + _ => (table_exported(&mut s, ext), one), + }; + assert_eq!(said, [want], "{ext}"); + } +}