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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 37 additions & 19 deletions crates/engine/src/cmd/layout/chart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
};
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<String> {
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,
Expand Down
61 changes: 53 additions & 8 deletions crates/engine/src/cmd/layout/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<u8>, String> {
let layout = s.project.layouts.get(li).ok_or("no layout")?.clone();
if let Some(note) = named_fonts_unread(&layout) {
Expand All @@ -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<String> {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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) {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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::<Vec<_>>().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<rustgis_render::layout::SectionGap, usize>;

Expand Down Expand Up @@ -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);
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
}
3 changes: 3 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
181 changes: 181 additions & 0 deletions crates/engine/src/tests/layout_chart_notices.rs
Original file line number Diff line number Diff line change
@@ -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<String> {
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<String> {
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::<Vec<_>>()
};
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}");
}
}
Loading
Loading