diff --git a/crates/engine/src/cmd/layout/chart.rs b/crates/engine/src/cmd/layout/chart.rs index dc66ab8cf1..a83c8cf8f8 100644 --- a/crates/engine/src/cmd/layout/chart.rs +++ b/crates/engine/src/cmd/layout/chart.rs @@ -411,46 +411,64 @@ pub(in crate::cmd::layout) fn chart_update( Ok(Some((o, Some(to.name.clone()), said))) } -/// What a chart leaves out of what it is told to draw (an existing loss made said): the bars -/// past its limit, and the features with no number in its field; coloured by classes, the bars -/// that keep its bar colour, their features having several, and stacked, the values of its key -/// gathered in its Other or keeping their palette colour. It reads each feature of the -/// chart's layer once, on the command's thread, as drawing the chart does on every draw of the -/// page: run only when a chart is added, told what to draw or coloured by classes, not when it -/// is moved; resized or restyled, a stacked chart reads it for [`say_chart_crowded`] alone. +/// Says [`chart_notices`] of the chart `id` of layout `li`: what it leaves out of what it is told +/// to draw (an existing loss made said) and whether its box is too small for it. It reads each +/// feature of the chart's layer once, on the command's thread, as drawing the chart does on every +/// draw of the page: run when a chart is added, told what to draw or coloured by classes; resized +/// or restyled, it reads them too, for [`say_chart_crowded`] to say the last alone: whether the +/// box is too small depends on the bars, and the Layout view reads them on this thread as well +/// when it draws the edited page. An export +/// says [`chart_notices`] of what its pages drew. pub(in crate::cmd::layout) fn say_chart_losses(s: &mut Session, li: usize, id: u32) { say_chart(s, li, id, false); } -/// [`say_chart_losses`]' warning of a chart whose title and key leave its bars no room, alone. +/// [`say_chart_losses`]' warning of a chart whose box is too small for it, alone. pub(in crate::cmd::layout) fn say_chart_crowded(s: &mut Session, li: usize, id: u32) { say_chart(s, li, id, true); } /// [`say_chart_losses`], or `crowded_only` [`say_chart_crowded`]. -pub(in crate::cmd::layout) fn say_chart(s: &mut Session, li: usize, id: u32, crowded_only: bool) { +fn say_chart(s: &mut Session, li: usize, id: u32, crowded_only: bool) { let said = { let Some(l) = s.project.layouts.get(li) else { return }; let Some(e) = l.element(id) else { return }; - let ElementKind::Chart { frame, layer, field, .. } = &e.kind else { return }; - // Only a stacked chart can be crowded, so for that alone an unstacked one reads nothing. - if crowded_only && e.kind.chart_stack().is_none() { - return; - } + let ElementKind::Chart { frame, layer, .. } = &e.kind else { return }; // Read as the page draws it: at the frame's scale and on the series page shown. let Some((m, env)) = rustgis_render::layout::frame_page_env(l, &s.project.maps, *frame) else { return }; let Some(data) = m.layer_by_name(layer).and_then(|fl| e.kind.chart_data_of(fl, &env)) else { return }; - let mut said = if crowded_only { Vec::new() } else { chart_losses(&e.kind, &data, layer, field) }; - if rustgis_render::layout::chart_crowded(&data, &e.kind.chart_look().unwrap_or_default(), e.w, e.h) { - said.push("the chart's title and key leave its bars no room: it draws as a placeholder until its box is taller".to_string()); - } - said + chart_notices(e, &data, crowded_only) }; for w in said { s.warn(w); } } +/// The notices of the chart element `e` drawing `data`; `crowded_only`, that its box is too small +/// for it alone. None of an element that isn't a chart. +pub(in crate::cmd::layout) fn chart_notices( + e: &rustgis_map::layout::Element, + data: &rustgis_map::layout::ChartData, + crowded_only: bool, +) -> Vec { + use rustgis_render::layout::Crowded; + let ElementKind::Chart { layer, field, .. } = &e.kind else { return Vec::new() }; + let mut said = if crowded_only { Vec::new() } else { chart_losses(&e.kind, data, layer, field) }; + if let Some(why) = rustgis_render::layout::chart_crowded(data, &e.kind.chart_look().unwrap_or_default(), e.w, e.h) { + said.push( + match why { + Crowded::Head => "the chart's title and key leave its bars no room: it draws as a placeholder until its box is taller", + Crowded::Columns => { + "the chart's labels and values leave its columns no height: it draws as a placeholder until its box is taller" + } + Crowded::Thin => "the chart is too small for its bars: some draw under 1 pt until its box is larger", + } + .to_string(), + ); + } + said +} + /// What [`say_chart_losses`] says of the chart `kind` of `layer` and `field`, drawing `data`. pub(in crate::cmd::layout) fn chart_losses( kind: &ElementKind, diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index d48463674a..e9c8f97e12 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -44,7 +44,8 @@ pub fn layout_bytes_with( /// Layout `li`'s current page as a PNG at `dpi`, or only its part in `region` (`[x, y, w, h]` in /// millimetres from the page's top left), drawn at that `dpi` rather than cut out of the whole /// page: what the assistant's `view_map` shows of a layout. It says what exporting the page says -/// of it: texts cut off, named fonts still being read, frames drawn without their cast shadows. +/// of it: texts cut off, named fonts still being read, frames drawn without their cast shadows, +/// charts' notices. pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]>) -> Result, String> { let layout = s.project.layouts.get(li).ok_or("no layout")?.clone(); if let Some(note) = named_fonts_unread(&layout) { @@ -66,26 +67,60 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> if let Some(r) = region { gaps.retain(|g, _| layout.element(g.frame).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); } - let (img, mut unfitted) = rustgis_render::layout::unfitted_legends(|| { - crate::cmd::share::saying_shadows(s, "The layout", |s| match region { - Some(r) => rustgis_render::layout::render_region(&layout, &mut s.project.maps, dpi, &info, r), - None => rustgis_render::layout::render(&layout, &mut s.project.maps, dpi, &info), + 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| match region { + Some(r) => rustgis_render::layout::render_region(&layout, &mut s.project.maps, dpi, &info, r), + None => rustgis_render::layout::render(&layout, &mut s.project.maps, dpi, &info), + }) }) }); let img = img?; if let Some(r) = region { 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))); } if let Some(note) = rustgis_render::layout::clipped_text_notice(&layout, &clipped) { s.warn(note); } say_unfitted_legends(s, &unfitted); + for note in chart_notice_lines(&layout, &charts) { + s.warn(note); + } if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) { s.warn(note); } img.encode_png().map_err(|e| e.to_string()) } +/// [`chart_notices`] of the charts of `layout` a drawing of it drew, one notice for each text, +/// in the order first met, naming the charts it is true of by name and id, each once whatever the +/// pages: the first ten, and how many more. +fn chart_notice_lines(layout: &Layout, drawn: &[rustgis_render::layout::DrawnChart]) -> Vec { + let mut said: Vec<(String, Vec<(u32, String)>)> = Vec::new(); + for (id, data) in drawn { + let Some(e) = layout.element(*id) else { continue }; + let named = (*id, format!("\"{}\" ({id})", crate::project::short_name(&e.name))); + for note in chart_notices(e, data, false) { + match said.iter_mut().find(|(n, _)| *n == note) { + Some((_, charts)) if charts.iter().any(|(at, _)| at == id) => {} + Some((_, charts)) => charts.push(named.clone()), + None => said.push((note, vec![named.clone()])), + } + } + } + said.into_iter() + .map(|(note, charts)| { + let n = charts.len(); + let mut names = charts.into_iter().take(10).map(|(_, named)| named).collect::>().join(", "); + if n > 10 { + names.push_str(&format!(" and {} more", n - 10)); + } + if n == 1 { format!("Chart {names}: {note}") } else { format!("{n} charts ({names}): {note}") } + }) + .collect() +} + /// The section lines an export doesn't draw, each with the pages it is missing from. type SectionGaps = BTreeMap; @@ -214,7 +249,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( // browser, no memory, still being worked out on the interface's thread): said, as the map's // export says them. // And the legends a fit drew that still don't fit, each once, whatever the page. - let ((result, said), unfitted) = rustgis_render::layout::unfitted_legends(|| rustgis_render::shadows_said(render_pages)); + // 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))); if result.is_ok() { for w in crate::cmd::share::shadow_warnings("The layout", &said) { s.warn(w); @@ -232,6 +269,9 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( s.warn(note); } say_unfitted_legends(s, &unfitted); + for note in chart_notice_lines(&saved, &charts) { + s.warn(note); + } pictured_notices(s, &frames_pictured, &pages_pictured); georeference_notices(s, &left_out, &by_corners, pages.len()); if !pdf { @@ -455,13 +495,18 @@ pub(in crate::cmd::layout) fn layout_svg(s: &mut Session, li: usize, dpi: f64) - let clipped = rustgis_render::layout::clipped_text(layout, &s.project.maps, dpi, &info); 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 (drawn, unfitted) = - rustgis_render::layout::unfitted_legends(|| rustgis_render::svg::layout_svg(layout, &mut s.project.maps, dpi, &info)); + let ((drawn, unfitted), charts) = rustgis_render::layout::drawn_charts(|| { + rustgis_render::layout::unfitted_legends(|| rustgis_render::svg::layout_svg(layout, &mut s.project.maps, dpi, &info)) + }); let (text, pictured) = drawn?; + let chart_notes = chart_notice_lines(layout, &charts); for note in [note, rustgis_render::layout::sections_notice(&gaps, 1)].into_iter().flatten() { s.warn(note); } say_unfitted_legends(s, &unfitted); + for note in chart_notes { + s.warn(note); + } pictured_notices(s, &pictured, &[]); Ok(text) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f945c219a1..ca34e68c32 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -111,6 +111,9 @@ mod layout_removed_layer; #[path = "tests/layout_edge.rs"] mod layout_edge; +#[path = "tests/layout_chart_notices.rs"] +mod layout_chart_notices; + #[path = "tests/layout_publication_parts.rs"] mod layout_publication_parts; diff --git a/crates/engine/src/tests/layout_chart_notices.rs b/crates/engine/src/tests/layout_chart_notices.rs new file mode 100644 index 0000000000..caaf94e92e --- /dev/null +++ b/crates/engine/src/tests/layout_chart_notices.rs @@ -0,0 +1,181 @@ +//! A layout chart's notices on export, and in a box too small to draw it (#3156). + +use super::*; +use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as Data}; + +const COLUMNS: &str = "the chart's labels and values leave its columns no height: it draws as a placeholder until its box is taller"; +const THIN: &str = "the chart is too small for its bars: some draw under 1 pt until its box is larger"; + +/// A layout "Charts" over a map with the points layer "Shops": `region` (E, N, S), `kind` and `n`. +fn shops() -> Session { + let mut s = Session::new(sample::world_project()); + let mut ds = Dataset::new( + "Shops", + GeometryType::Point, + vec![Field::new("region", FieldType::Text), Field::new("kind", FieldType::Text), Field::new("n", FieldType::Double)], + ); + for (region, kind) in [("E", "city"), ("E", "town"), ("N", "town"), ("S", "town")] { + ds.push( + Some(Geometry::Point(rustgis_data::Coord::new(0.0, 0.0))), + vec![Data::Text(region.into()), Data::Text(kind.into()), Data::Float(1.0)], + ); + } + s.map_mut().add_dataset(ds); + s.run("layout.new", &json!({"name": "Charts"})).unwrap(); + s +} + +/// Adds a chart of Shops summed by region, with `extra` keys; its element id. +fn chart(s: &mut Session, extra: Value) -> u64 { + let mut p = json!({"kind": "chart", "layer": "Shops", "field": "n", "group": "region"}); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + s.run("layout.addElement", &p).unwrap()["element"].as_u64().unwrap() +} + +/// What running `command` with `p` says. +fn 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()).collect() +} + +/// What exporting the layout to a file of `ext` says of its charts. +fn exported(s: &mut Session, ext: &str) -> Vec { + let dir = std::env::temp_dir().join(format!("rustgis-3156-{}-{:?}", std::process::id(), std::thread::current().id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(format!("page.{ext}")); + let mut all = said(s, "layout.export", json!({"path": path, "dpi": 36})); + std::fs::remove_dir_all(&dir).unwrap(); + all.retain(|t| t.contains("chart")); + all +} + +/// What the export says of the chart `id`'s `note`. +fn of(s: &Session, id: u64, note: &str) -> String { + let name = &s.project.layouts[0].element(id as u32).unwrap().name; + format!("Chart \"{name}\" ({id}): {note}") +} + +#[test] +fn an_export_says_what_each_chart_leaves_out() { + let mut s = shops(); + let id = chart(&mut s, json!({"bars": 2})); + let want = + of(&s, id, "the chart draws 2 of 3 bars: 1 left out (\"bars\" draws up to 100, \"other\": true gathers the rest in an Other bar)"); + for ext in ["png", "pdf", "svg"] { + assert_eq!(exported(&mut s, ext), std::slice::from_ref(&want), "{ext}"); + } + // A project opened again says it too: nothing is kept from adding the chart. + let mut again = Session::new(serde_json::from_value(serde_json::to_value(&s.project).unwrap()).unwrap()); + assert_eq!(exported(&mut again, "png"), [want]); +} + +#[test] +fn an_export_reads_the_layer_as_it_is_now() { + let mut s = shops(); + let id = chart(&mut s, json!({})); + assert!(exported(&mut s, "png").is_empty(), "nothing lost, nothing said"); + let layer = s.map_mut().layers.iter_mut().find(|l| l.name == "Shops").unwrap(); + layer.dataset.push( + Some(Geometry::Point(rustgis_data::Coord::new(0.0, 0.0))), + vec![Data::Text("N".into()), Data::Text("town".into()), Data::Null], + ); + let want = of(&s, id, "1 feature of Shops with no number in n left out of the chart"); + assert_eq!(exported(&mut s, "png"), [want]); +} + +#[test] +fn a_map_series_export_says_a_pages_losses_once() { + let mut s = shops(); + s.run("layout.series", &json!({"layer": "Shops", "nameField": "region"})).unwrap(); + // On page 2 alone, East's city and town take different colours. + s.map_mut().layers.iter_mut().find(|l| l.name == "Shops").unwrap().symbol_by.fill = + Some("CASE WHEN @page_number = 2 AND kind = 'city' THEN '#ff0000' ELSE '#0000ff' END".into()); + let id = chart(&mut s, json!({"classes": true})); + let want = of(&s, id, "1 bar keeps the chart's bar colour: its features have several colours on the map"); + assert!(exported(&mut s, "png").is_empty(), "page 1 has one colour"); + assert_eq!(exported(&mut s, "pdf"), [want]); + // The same loss on every page is said once. + s.run("layout.update", &json!({"element": id, "classes": false, "bars": 2})).unwrap(); + let said = exported(&mut s, "pdf"); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("draws 2 of 3 bars"), "{said:?}"); +} + +#[test] +fn an_export_names_charts_with_the_same_notice_in_one() { + let mut s = shops(); + let ids: Vec<_> = (0..12).map(|_| chart(&mut s, json!({"bars": 2}))).collect(); + let other = chart(&mut s, json!({"bars": 1})); + let said = exported(&mut s, "png"); + assert_eq!(said.len(), 2, "{said:?}"); + let named = |id: u64| format!("\"{}\" ({id})", s.project.layouts[0].element(id as u32).unwrap().name); + let listed: Vec<_> = ids[..10].iter().map(|id| named(*id)).collect(); + let want = format!("12 charts ({} and 2 more): the chart draws 2 of 3 bars", listed.join(", ")); + assert!(said[0].starts_with(&want), "{said:?}"); + assert!(said[1].starts_with(&format!("Chart {}: the chart draws 1 of 3 bars", named(other))), "{said:?}"); +} + +#[test] +fn an_export_says_nothing_of_a_chart_it_does_not_draw() { + let mut s = shops(); + let id = chart(&mut s, json!({"bars": 2})); + s.run("layout.update", &json!({"element": id, "visible": false})).unwrap(); + assert!(exported(&mut s, "png").is_empty(), "hidden"); + s.run("layout.update", &json!({"element": id, "visible": true})).unwrap(); + s.run("layer.remove", &json!({"layer": "Shops"})).unwrap(); + assert!(exported(&mut s, "png").is_empty(), "its layer is gone"); +} + +/// The assistant's view of a layout says what exporting it says, of the charts in the region it +/// shows alone when it shows one. +#[test] +fn a_view_of_the_layout_says_the_notices_of_the_charts_it_shows() { + let mut s = shops(); + let id = chart(&mut s, json!({"bars": 2, "x": 10, "y": 10, "w": 60, "h": 40})); + let mut viewed = |region| { + let mark = s.notice_mark(); + crate::cmd::layout::layout_png(&mut s, 0, 36.0, region).unwrap(); + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("chart")).collect::>() + }; + for region in [None, Some([0.0, 0.0, 40.0, 30.0])] { + let said = viewed(region); + assert!(said.len() == 1 && said[0].contains(&format!("({id}): the chart draws 2 of 3 bars")), "{region:?}: {said:?}"); + } + assert!(viewed(Some([150.0, 100.0, 40.0, 30.0])).is_empty(), "a region without it"); +} + +#[test] +fn a_chart_of_columns_without_height_says_so() { + let mut s = shops(); + // 10 mm high: its title, a line of labels and one of values leave the columns nothing. + let small = 10.0; + let mark = s.notice_mark(); + let id = chart(&mut s, json!({"orientation": "vertical", "values": true, "h": small})); + let added: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(added.iter().any(|t| t == COLUMNS), "added: {added:?}"); + let want = of(&s, id, COLUMNS); + assert_eq!(exported(&mut s, "png"), [want]); + let taller = said(&mut s, "layout.update", json!({"element": id, "h": 60})); + assert!(!taller.iter().any(|t| t == COLUMNS), "{taller:?}"); + let resized = said(&mut s, "layout.update", json!({"element": id, "h": small})); + assert!(resized.iter().any(|t| t == COLUMNS), "resized: {resized:?}"); + let moved = said(&mut s, "layout.update", json!({"element": id, "x": 20})); + assert!(!moved.iter().any(|t| t == COLUMNS), "moved: {moved:?}"); +} + +#[test] +fn a_chart_with_bars_under_a_point_says_so() { + let mut s = shops(); + let id = chart(&mut s, json!({"h": 60, "w": 80})); + assert!(exported(&mut s, "png").is_empty(), "room enough"); + for (key, value) in [("h", 5.0), ("w", 1.0)] { + s.run("layout.update", &json!({"element": id, "h": 60, "w": 80})).unwrap(); + let resized = said(&mut s, "layout.update", json!({"element": id, key: value})); + assert!(resized.iter().any(|t| t == THIN), "{key}: {resized:?}"); + let want = of(&s, id, THIN); + assert_eq!(exported(&mut s, "svg"), [want], "{key}"); + } +} diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 1212e657e3..f51b7a8177 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -663,6 +663,7 @@ fn draw_page( }); match data { Some(data) => { + drawn_chart(e.id, &data); let look = e.kind.chart_look().unwrap_or_default(); chart(&mut pm, r, &data, &look, color.unwrap_or(INK), ppp, layout.decimal_comma) } diff --git a/crates/render/src/layout/chart.rs b/crates/render/src/layout/chart.rs index ceb6d25b2a..504786068b 100644 --- a/crates/render/src/layout/chart.rs +++ b/crates/render/src/layout/chart.rs @@ -2,6 +2,54 @@ use super::*; +/// A chart as a page drew it ([`drawn_charts`]): its element's id and the data it read. +pub type DrawnChart = (u32, rustgis_map::layout::ChartData); + +thread_local! { + /// While [`drawn_charts`] runs on this thread: the charts drawn, each with each data once. + static DRAWN: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Ends the list [`drawn_charts`] opened when dropped, even by a panic. +struct DrawnList(bool); + +impl Drop for DrawnList { + fn drop(&mut self) { + if self.0 { + DRAWN.set(None); + } + } +} + +/// `f`, and the charts the pages it drew on this thread drew, each once for each data it was +/// drawn with (a map series draws a chart a page), in the order first drawn: what an export says +/// of them, from the rows each page read, which a streamed layer holds only as it is drawn. A +/// call inside another lists nothing and leaves its charts to the outer one. +pub fn drawn_charts(f: impl FnOnce() -> T) -> (T, Vec) { + let opened = DRAWN.with_borrow_mut(|d| { + let none = d.is_none(); + if none { + *d = Some(Vec::new()); + } + none + }); + let _list = DrawnList(opened); + let out = f(); + let listed = if opened { DRAWN.with_borrow_mut(Option::take).unwrap_or_default() } else { Vec::new() }; + (out, listed) +} + +/// Lists the chart `id` drawn with `data`, while [`drawn_charts`] runs. +pub(super) fn drawn_chart(id: u32, data: &rustgis_map::layout::ChartData) { + DRAWN.with_borrow_mut(|d| { + if let Some(listed) = d + && !listed.iter().any(|(i, drawn)| *i == id && drawn == data) + { + listed.push((id, data.clone())); + } + }); +} + /// A bar chart of `data`'s bars ([`ElementKind::chart_data`]) drawn as `look` says, its title, /// labels and values in `dark`, its values with a decimal comma when `comma`. With a negative /// value, bars run either way from a zero line (#2487). Stacked, each bar is drawn as its @@ -10,10 +58,7 @@ use super::*; pub(super) fn chart(pm: &mut Canvas, r: Rect, data: &rustgis_map::layout::ChartData, look: &ChartLook, dark: Rgba, ppp: f64, comma: bool) { let ppp = ppp as f32; let vals = &data.bars; - let (min, reach) = chart_span(data); - // A fixed maximum is the far end of the bars' room, whatever they reach (#2487 part 4). - let max = look.max.unwrap_or(reach); - if vals.is_empty() || (reach <= 0.0 && min >= 0.0) { + if !has_bars(data) { placeholder(pm, r, "Chart", ppp as f64); return; } @@ -26,27 +71,8 @@ pub(super) fn chart(pm: &mut Canvas, r: Rect, data: &rustgis_map::layout::ChartD text::text_at(pm, &data.title, r.x(), r.y() + title_h / 2.0, px * 1.15, dark, true, text::Align::Left, false); } chart_key(Some(pm), r, r.y() + title_h, &data.key, px, ppp, dark); - // Each bar's value as written past its end, when it has them. - let values: Vec = if look.values { - vals.iter().map(|(v, _)| decimal(rustgis_map::layout::chart_value_text(*v, look.decimals), comma)).collect() - } else { - Vec::new() - }; - let bars = ChartBars { - r, - title_h: title_h + key_h, - vals, - values: &values, - colors: &data.colors, - stretches: &data.stretches, - key: &data.key, - min, - max, - px, - ppp, - dark, - look, - }; + let values = written_values(vals, look, comma); + let bars = ChartBars::new(r, title_h + key_h, data, &values, look, (px, ppp), dark); let labelled = data.labelled && !look.hide_labels; match look.orientation { Orientation::Horizontal => bars.across(pm, labelled), @@ -85,12 +111,86 @@ pub(super) fn chart_head(r: Rect, data: &rustgis_map::layout::ChartData, look: & (data.key.is_empty() || title_h + key_h + line + below <= r.height()).then_some((title_h, key_h)) } -/// Whether a chart with bars to draw, `w` × `h` mm in its look, draws its placeholder instead as -/// its title and key leave the bars no room ([`chart_head`]): what the commands warn of, so the page and the commands -/// never tell it apart. -pub fn chart_crowded(data: &rustgis_map::layout::ChartData, look: &ChartLook, w: f64, h: f64) -> bool { - let Some(r) = Rect::from_xywh(0.0, 0.0, (w * PT_PER_MM).max(1.0) as f32, (h * PT_PER_MM).max(1.0) as f32) else { return false }; - !data.bars.is_empty() && chart_head(r, data, look, 7.5 * 1.33, 1.0).is_none() +/// Whether a chart has a bar to draw: without one it draws its placeholder whatever its box. +fn has_bars(data: &rustgis_map::layout::ChartData) -> bool { + let (min, reach) = chart_span(data); + !data.bars.is_empty() && (reach > 0.0 || min < 0.0) +} + +/// Each bar's value as written past its end, when the look has them. +fn written_values(vals: &[(f64, String)], look: &ChartLook, comma: bool) -> Vec { + if !look.values { + return Vec::new(); + } + vals.iter().map(|(v, _)| decimal(rustgis_map::layout::chart_value_text(*v, look.decimals), comma)).collect() +} + +/// Why a chart's box is too small for it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Crowded { + /// Stacked, its title and key leave its bars no room: it draws its placeholder. + Head, + /// As columns, their labels and values leave them no height: it draws its placeholder. + Columns, + /// Its bars, or the room they run in, come under a point. + Thin, +} + +/// Why a chart with bars to draw, `w` × `h` mm in its look, can't be read in that box, if it +/// can't: what the commands warn of, worked out as [`chart`] lays it out at a pixel per +/// [`PT_PER_MM`] unit, so the page and the commands never tell it apart. +pub fn chart_crowded(data: &rustgis_map::layout::ChartData, look: &ChartLook, w: f64, h: f64) -> Option { + let r = Rect::from_xywh(0.0, 0.0, (w * PT_PER_MM).max(1.0) as f32, (h * PT_PER_MM).max(1.0) as f32)?; + if !has_bars(data) { + return None; + } + let px = 7.5 * 1.33; + let Some((title_h, key_h)) = chart_head(r, data, look, px, 1.0) else { return Some(Crowded::Head) }; + let values = written_values(&data.bars, look, false); + let bars = ChartBars::new(r, title_h + key_h, data, &values, look, (px, 1.0), INK); + let labelled = data.labelled && !look.hide_labels; + match look.orientation { + Orientation::Horizontal => { + let room = bars.across_room(labelled); + (room.bar_h * BAR_SHARE < POINT || room.bar_area < POINT).then_some(Crowded::Thin) + } + Orientation::Vertical => { + let room = bars.column_room(labelled); + if room.plot_h <= 0.0 { + Some(Crowded::Columns) + } else { + (room.plot_h < POINT || room.slot * BAR_SHARE < POINT).then_some(Crowded::Thin) + } + } + } +} + +/// A typographic point (1/72 inch) in the layout's units ([`PT_PER_MM`], 96 to the inch). +const POINT: f32 = (PT_PER_MM * 25.4 / 72.0) as f32; + +/// The part of its row, or of its slot, that a bar is thick. +const BAR_SHARE: f32 = 0.7; + +/// The room [`ChartBars::across`] lays its bars in: the labels' column, each bar's row and the +/// size its label and value are written at, the room for values at either side and the bars'. +pub(super) struct AcrossRoom { + label_w: f32, + bar_h: f32, + size: f32, + value_size: f32, + room_lo: f32, + bar_area: f32, +} + +/// The room [`ChartBars::columns`] stands its columns in: each one's slot, the size and the line +/// of its value, the line of the labels, and the columns' top and height. +pub(super) struct ColumnRoom { + slot: f32, + value_px: f32, + value_h: f32, + label_h: f32, + top: f32, + plot_h: f32, } /// How far a bar's stretches reach below zero (its negative ones added up) and above it. @@ -159,7 +259,38 @@ pub(super) struct ChartBars<'a> { pub(super) look: &'a ChartLook, } -impl ChartBars<'_> { +impl<'a> ChartBars<'a> { + /// The bars of `data` in `r`, under a title and key `title_h` high, `values` written out, text + /// `px` high at `ppp` pixels per point. + fn new( + r: Rect, + title_h: f32, + data: &'a rustgis_map::layout::ChartData, + values: &'a [String], + look: &'a ChartLook, + (px, ppp): (f32, f32), + dark: Rgba, + ) -> Self { + let (min, reach) = chart_span(data); + // A fixed maximum is the far end of the bars' room, whatever they reach (#2487 part 4). + let max = look.max.unwrap_or(reach); + Self { + r, + title_h, + vals: &data.bars, + values, + colors: &data.colors, + stretches: &data.stretches, + key: &data.key, + min, + max, + px, + ppp, + dark, + look, + } + } + /// Bar `i` (of value `v`) as the stretches it is drawn in, each with the share of the span /// ([`ChartBars::share`]) where it starts from zero, its own share (negative running back) and /// its colour. A whole bar (none stacked, or no stretches) is one stretch, in its own colour or @@ -206,9 +337,7 @@ impl ChartBars<'_> { .fold(0.0, f32::max) } - /// Bars running across, labels in a column at their left, each value past its bar's end with - /// room kept for it at the side its bar runs to. - pub(super) fn across(&self, pm: &mut Canvas, labelled: bool) { + pub(super) fn across_room(&self, labelled: bool) -> AcrossRoom { let (r, ppp, px) = (self.r, self.ppp, self.px); let label_w = if labelled { r.width() * 0.32 } else { 0.0 }; let bh = ((r.height() - self.title_h) / self.vals.len() as f32).min(18.0 * ppp); @@ -230,6 +359,15 @@ impl ChartBars<'_> { (room_lo, room_hi) = (room(true, value_size), room(false, value_size)); } let bar_area = beside - room_lo - room_hi; + AcrossRoom { label_w, bar_h: bh, size, value_size, room_lo, bar_area } + } + + /// Bars running across, labels in a column at their left, each value past its bar's end with + /// room kept for it at the side its bar runs to. + pub(super) fn across(&self, pm: &mut Canvas, labelled: bool) { + let (r, ppp) = (self.r, self.ppp); + let AcrossRoom { label_w, bar_h: bh, size, value_size, room_lo, bar_area } = self.across_room(labelled); + let gap = 2.0 * ppp; // Where the bars start: the left of the bar area when none is negative. let zero = r.x() + label_w + room_lo + bar_area * self.share(-self.min); let right = self.look.label_align == TextAlign::Right; @@ -250,7 +388,7 @@ impl ChartBars<'_> { drawn.push((place(x, w), w, colour)); (left, right_end) = (left.min(x), right_end.max(x + w)); } - self.bar(pm, &drawn, (y + bh * 0.15, bh * 0.7), true); + self.bar(pm, &drawn, (y + bh * (1.0 - BAR_SHARE) / 2.0, bh * BAR_SHARE), true); if labelled { let t = fit_label(name, |t| text::measure(t, 7.5, false) * ppp > label_w - 4.0 * ppp); // At the column's right, the label ends where the bars' side begins. @@ -272,10 +410,8 @@ impl ChartBars<'_> { } } - /// Columns standing on a zero line, each label centred under its column and cut to its width, - /// each value over a column (under one going down), made smaller to fit a narrow column. - pub(super) fn columns(&self, pm: &mut Canvas, labelled: bool) { - let (r, ppp, px) = (self.r, self.ppp, self.px); + pub(super) fn column_room(&self, labelled: bool) -> ColumnRoom { + let (r, px) = (self.r, self.px); let slot = r.width() / self.vals.len() as f32; let widest = self.widest(px, false).max(self.widest(px, true)); let value_px = if widest > slot * 0.95 { px * slot * 0.95 / widest } else { px }; @@ -285,6 +421,14 @@ impl ChartBars<'_> { let label_h = if labelled { px * 1.4 } else { 0.0 }; let top = r.y() + self.title_h + room_hi; let plot_h = r.bottom() - label_h - room_lo - top; + ColumnRoom { slot, value_px, value_h, label_h, top, plot_h } + } + + /// Columns standing on a zero line, each label centred under its column and cut to its width, + /// each value over a column (under one going down), made smaller to fit a narrow column. + pub(super) fn columns(&self, pm: &mut Canvas, labelled: bool) { + let (r, ppp, px) = (self.r, self.ppp, self.px); + let ColumnRoom { slot, value_px, value_h, label_h, top, plot_h } = self.column_room(labelled); if plot_h <= 0.0 { placeholder(pm, r, "Chart", ppp as f64); return; @@ -308,7 +452,7 @@ impl ChartBars<'_> { drawn.push((place(y, h), h, colour)); (top_end, bottom) = (top_end.min(y), bottom.max(y + h)); } - self.bar(pm, &drawn, (cx - slot * 0.35, slot * 0.7), false); + self.bar(pm, &drawn, (cx - slot * BAR_SHARE / 2.0, slot * BAR_SHARE), false); if let Some(t) = self.values.get(i) { let vy = if *v < 0.0 { bottom + value_h / 2.0 } else { top_end - value_h / 2.0 }; text::text_at(pm, t, cx, write(vy), value_px, self.dark, false, text::Align::Center, false); diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 1d86fdd957..28d0a21861 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -280,9 +280,19 @@ fn stacked_bars_draw_their_stretches_and_key() { short.labelled = true; let (w, h) = (200.0 / PT_PER_MM, 40.0 / PT_PER_MM); let valued = |orientation| ChartLook { orientation, values: true, ..ChartLook::default() }; - assert!(chart_crowded(&short, &valued(Orientation::Vertical), w, h)); - assert!(!chart_crowded(&short, &valued(Orientation::Horizontal), w, h)); - assert!(!chart_crowded(&stacked(vec![6.0, 4.0]), &ChartLook::default(), w, 120.0 / PT_PER_MM)); + assert_eq!(chart_crowded(&short, &valued(Orientation::Vertical), w, h), Some(Crowded::Head)); + assert_eq!(chart_crowded(&short, &valued(Orientation::Horizontal), w, h), None); + assert_eq!(chart_crowded(&stacked(vec![6.0, 4.0]), &ChartLook::default(), w, 120.0 / PT_PER_MM), None); + // Unstacked, columns without height and bars under a point are told apart; no bar, nothing. + let mut plain = short.clone(); + (plain.key, plain.stretches) = (Vec::new(), Vec::new()); + assert_eq!(chart_crowded(&plain, &valued(Orientation::Vertical), w, 20.0 / PT_PER_MM), Some(Crowded::Columns)); + assert_eq!(chart_crowded(&plain, &valued(Orientation::Vertical), 1.0 / PT_PER_MM, h * 2.0), Some(Crowded::Thin)); + assert_eq!(chart_crowded(&plain, &valued(Orientation::Horizontal), w, 1.0 / PT_PER_MM), Some(Crowded::Thin)); + // Columns left some height, under a point of it. + assert_eq!(chart_crowded(&plain, &valued(Orientation::Vertical), w, 28.5 / PT_PER_MM), Some(Crowded::Thin)); + plain.bars = vec![(0.0, String::new())]; + assert_eq!(chart_crowded(&plain, &valued(Orientation::Vertical), w, 1.0 / PT_PER_MM), None); // A box narrower than a swatch draws the placeholder too, nothing past its right. // Sample above the centered "Chart" label so system font glyph shapes at y=60 don't mask the fill. let mut c = Canvas::new(200, 120).unwrap(); @@ -290,6 +300,30 @@ fn stacked_bars_draw_their_stretches_and_key() { assert!(is(&c, 2, 10, Rgba::rgb(0xF0, 0xF1, 0xF3)) && (6..20).all(|x| c.pixmap().pixel(x, 7).is_some_and(|p| p.alpha() == 0))); } +/// An unstacked chart in a box too small draws what it did before it was warned of (#3156): as +/// columns without height its placeholder; across, bars under a point high. +#[test] +fn an_unstacked_chart_too_small_draws_as_before() { + let data = rustgis_map::layout::ChartData { + bars: (0..4).map(|k| (f64::from(k + 1), String::new())).collect(), + title: "Shops".into(), + labelled: true, + ..Default::default() + }; + let draw = |orientation, h: f32| { + let mut c = Canvas::new(200, 60).unwrap(); + let look = ChartLook { orientation, values: true, ..ChartLook::default() }; + chart(&mut c, Rect::from_xywh(0.0, 0.0, 200.0, h).unwrap(), &data, &look, INK, 1.0, false); + c + }; + let c = draw(Orientation::Vertical, 40.0); + assert!(c.pixmap().pixel(100, 5).is_some_and(|p| p.red() == 0xF0 && p.blue() == 0xF3), "the placeholder"); + // 4 pt under its title: bars a pixel high, no placeholder. + let c = draw(Orientation::Horizontal, 20.0); + assert!((0..200).all(|x| c.pixmap().pixel(x, 40).is_some_and(|p| p.alpha() == 0)), "nothing under the box"); + assert!((100..110).any(|x| (15..21).any(|y| c.pixmap().pixel(x, y).is_some_and(|p| p.alpha() > 0))), "its bars"); +} + fn bar_blue(c: &Canvas, x: u32, y: u32) -> bool { c.pixmap().pixel(x, y).is_some_and(|p| p.blue() > 150 && p.red() < 100) } diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 37622dfa0e..641f3c5b62 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -514,6 +514,30 @@ fn partial_source_failure_and_incomplete_summary_reach_unchanged_owner() { } } +/// An export says a chart's notices of the rows its page drew (#3156): a streamed layer holding +/// none before the page is drawn is listed with those the frame read. +#[test] +fn drawn_charts_list_the_rows_a_streamed_layer_held_as_drawn() { + use rustgis_map::layout::{ElementKind, Layout}; + let mut ds = Dataset::new("points", GeometryType::Point, vec![Field::new("value", FieldType::Integer)]); + ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![Value::Int(5)]); + let mut map = Map::new("streamed"); + map.add_dataset(ds); + map.layers[0] = streamed(&map.layers[0], 1); + map.layers[0].dataset.features = Vec::new().into(); + let mut page = Layout::new("page", 140.0, 100.0); + let frame = serde_json::json!({"MapFrame": {"map": "streamed", "center": {"x": 0.0, "y": 0.0}, "scale": 300000.0}}); + let frame = page.add("map", (0.0, 0.0, 60.0, 60.0), serde_json::from_value(frame).unwrap()); + let chart = serde_json::json!({"Chart": {"frame": frame, "layer": "points", "field": "value"}}); + let chart: ElementKind = serde_json::from_value(chart).unwrap(); + let id = page.add("chart", (70.0, 0.0, 60.0, 40.0), chart); + let mut maps = [map]; + let (drawn, charts) = layout::drawn_charts(|| layout::render(&page, &mut maps, 72.0, &layout::PageInfo::default())); + drawn.unwrap(); + let [(listed, data)] = &charts[..] else { panic!("{charts:?}") }; + assert_eq!((*listed, data.bars.len()), (id, 1)); +} + #[test] fn layout_export_keeps_all_drawn_legend_classes() { use rustgis_map::layout::{ElementKind, FrameShape, INDICATOR_COLOR, INDICATOR_WIDTH, Layout}; diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index b69b00760b..bf76f9a99e 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -741,9 +741,9 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu are drawn whole. Features of a hidden class, or points drawn as an image, show none and leave the bar to the others. A bar whose features have several colours or show none, and an Other bar, keep the bar colour, and the chart says how many bars do, and why, when it - is added or changed. The bars follow the symbology when it changes; those counts are not said - again then. The bars take the layer's colours whether the frame draws the layer or not: a - layer turned off, or outside its visible scale range, still colours them. + is added, told what to draw or colored by class, and when the layout is exported. The bars follow the symbology when it + changes. The bars take the layer's colours whether the frame draws the layer or not: a layer + turned off, or outside its visible scale range, still colours them. **Labels** puts the labels of bars running across at the left of their column, or **By the bars**, against them. Keep a title out of the chart to style it as you like with a text element. From a command: @@ -763,14 +763,20 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu colour; a value whose features have several colours, or show none, keeps its palette colour, and the chart says how many do. Stretches below zero run the other way from the zero line, and **Values** writes the bar's total. An Other bar is stacked too, from the bars it gathers. A - box too short to leave the bars room under the title and key shows the chart's placeholder, - and the chart says so when it is added, resized, retitled or turned (not when the layer's data - changes): make it taller. A stack field deleted from the layer leaves the bars whole, and the + box too short to leave the bars room under the title and key shows the chart's placeholder: + make it taller. A stack field deleted from the layer leaves the bars whole, and the chart's next change lets the stack go, saying so. Turning grouping off, taking a mean, minimum or maximum, or moving the chart to a layer without the field lets the stack go, and the chart says so. From a command: `layout.update={"element":6,"group":"continent","stack":"income_grp"}`, and `"stack":""` for whole bars again; `layout.addElement` takes it too. +- **What a chart says**: exporting a layout (or the Assistant viewing it) says again what each chart it shows leaves out, and + whether its box is too small for it, read as the exported page draws it, on every page of a map + series it exports: charts with the same notice are named together in one, by name and element + number, the first ten and how many more there are. A box is too small when columns are left no height by their labels + and values (the chart shows its placeholder), or when bars, or the room they run in, come under + a point. The chart also says that when it is added, resized, retitled, turned, or given or + denied values or labels. - **Facing charts**: two charts side by side compare two fields per category back to back, such as the share of businesses against the share of people in each district. **Mirror** draws a chart as its mirror image, its text reading as ever: bars running across start from the right