Skip to content
33 changes: 27 additions & 6 deletions crates/engine/src/cmd/layout/publication/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1163,15 +1163,36 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu
(fw * 0.3, fh * 0.25)
}
};
// Whether a layer the legend isn't asked to leave out may have rows in it.
let listed = legend.as_ref().is_some_and(|legend| {
let asked_out = |name: &str| legend.exclude.iter().any(|n| n.eq_ignore_ascii_case(name));
s.map().layers.iter().any(|l| s.map().shows(l) && crate::render::layout::legend_lists(l) && !asked_out(&l.name))
// Of the layers the legend lists, or may list once read (a raster still without its style):
// whether one is still reading, and whether a raster's read failed, leaving it no classes to
// measure. Those it leaves out, asked or as context, count for neither.
let (listed_reading, listed_failed) = legend.as_ref().map_or((false, false), |legend| {
let out = legend.left_out(&context);
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
s.map().layers.iter().filter(|l| s.map().draws_at(l, render_scale) && !out.iter().any(|n| n.eq_ignore_ascii_case(&l.name))).fold(
(false, false),
|(reading, failed), l| {
let lists = crate::render::layout::legend_lists(l);
let raster = l.raster.as_ref();
(
reading
|| raster.is_some_and(|r| r.is_reading() && (lists || r.awaits_style()))
|| (lists && l.source.as_ref().is_some_and(|src| src.is_pending())),
failed || (lists && raster.is_some_and(|r| r.error.is_some() && r.data.is_none() && !r.is_reading())),
)
},
)
});
if reading && listed {
let unread = if reading && listed_reading {
Some("the legend's classes aren't known yet (a layer still reading): it has a fixed size to fit by hand")
} else if listed_failed {
Some("a layer the legend lists couldn't be read, so the legend has a fixed size to fit by hand")
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
} else {
None
};
if let Some(why) = unread {
(cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25));
sizes = None;
warnings.push("the legend's classes aren't known yet (a layer still reading): it has a fixed size to fit by hand".into());
warnings.push(why.into());
} else if pictures_pending(s, render_scale) {
// Not waited for: a slow legend server would hold the command up.
(cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25));
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/layout/publication/parts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ impl PublicationLegend {
/// The legend's size in each number of columns the placement tries, in mm, its text `text_pt`
/// points, at the renderer's scale denominator `scale`, with its title when it has rows. A
/// legend asked for some columns has that size in every one, so the placement has no other to
/// pick. `None` when a complete source can't be read.
/// pick. `None` when a listed layer's complete source can't be read.
pub(super) fn sizes(
&self,
map: &mut Map,
Expand Down
91 changes: 91 additions & 0 deletions crates/engine/src/tests/layout_publication_parts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,97 @@ fn a_publication_legend_does_not_wait_for_a_layer_it_leaves_out() {
assert!(!left_out.contains("classes aren't known yet") && left_out.contains("the legend lists nothing"), "{left_out}");
}

#[test]
fn a_publication_legend_is_sized_while_only_a_layer_it_leaves_out_reads() {
let points = temp("sites.geojson");
let point = json!({"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [5.0, 5.0]}});
std::fs::write(&points, json!({"type": "FeatureCollection", "features": [point]}).to_string()).unwrap();
let mut s = Session::new(Project::default());
s.run("layer.addData", &json!({"path": points.display().to_string()})).unwrap();
// A raster read in place from a host that never answers: still reading throughout.
let host = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let address = format!("http://{}/depth.tif", host.local_addr().unwrap());
let mut raster = rustgis_map::raster::RasterLayer::opening_in_place(address);
raster.style.renderer = rustgis_map::raster::RasterRenderer::Colormap;
s.map_mut().add_raster("Depth".to_string(), raster);
let mut said = |legend: Value| {
let p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "colorbar": "none", "legend": legend});
s.run("layout.publication", &p).unwrap()["warnings"].to_string()
};
let listed = said(json!({}));
assert!(listed.contains("classes aren't known yet"), "{listed}");
let left_out = said(json!({"exclude": ["depth"]}));
assert!(!left_out.contains("classes aren't known yet") && !left_out.contains("fixed size"), "{left_out}");
let _ = std::fs::remove_file(points);
}

#[test]
fn a_publication_legend_waits_for_a_raster_whose_style_isnt_known_yet() {
let points = temp("stations.geojson");
let point = json!({"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [5.0, 5.0]}});
std::fs::write(&points, json!({"type": "FeatureCollection", "features": [point]}).to_string()).unwrap();
let mut s = Session::new(Project::default());
s.run("layer.addData", &json!({"path": points.display().to_string()})).unwrap();
// Added and not yet read, from a host that never answers: a placeholder style until its pixels
// say whether it draws classes.
let host = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let address = format!("http://{}/cover.tif", host.local_addr().unwrap());
s.map_mut().add_raster("Cover".to_string(), rustgis_map::raster::RasterLayer::opening_in_place(address));
let mut said = |legend: Value| {
let p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "colorbar": "none", "legend": legend});
s.run("layout.publication", &p).unwrap()["warnings"].to_string()
};
let listed = said(json!({}));
assert!(listed.contains("classes aren't known yet"), "{listed}");
let left_out = said(json!({"exclude": ["Cover"]}));
assert!(!left_out.contains("fixed size"), "{left_out}");
let _ = std::fs::remove_file(points);
}

#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_publication_legend_is_sized_past_an_unreadable_source_it_leaves_out() {
let path = temp("survey.shp");
let mut ds = rustgis_data::Dataset::new("sites", rustgis_data::GeometryType::Point, vec![]);
ds.push(Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(5.0, 5.0))), vec![]);
rustgis_data::io::write_path(&ds, &path).unwrap();
let handle = rustgis_data::source::open_path(&path, None).unwrap();
let source = rustgis_map::source::SourceLayer::from_path(path.to_string_lossy(), None, handle);
let mut s = Session::new(Project::default());
s.map_mut().add_streamed("Survey", source);
s.map_mut().add_dataset(ds);
std::fs::remove_file(&path).unwrap();
let p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "legend": {"exclude": ["Survey"]}});
let said = s.run("layout.publication", &p).unwrap()["warnings"].to_string();
for ext in ["shx", "dbf", "prj", "cpg"] {
let _ = std::fs::remove_file(path.with_extension(ext));
}
assert!(!said.contains("so the legend has a fixed size"), "{said}");
}

#[test]
fn a_publication_legend_has_a_fixed_size_for_a_listed_raster_that_failed() {
let points = temp("wells.geojson");
let point = json!({"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [5.0, 5.0]}});
std::fs::write(&points, json!({"type": "FeatureCollection", "features": [point]}).to_string()).unwrap();
let mut s = Session::new(Project::default());
s.run("layer.addData", &json!({"path": points.display().to_string()})).unwrap();
// A classified raster whose read failed: no pixels, so none of its classes.
let mut raster = rustgis_map::raster::RasterLayer::unread_in_place("https://example.invalid/soil.tif");
raster.style.renderer = rustgis_map::raster::RasterRenderer::Colormap;
raster.fail("the host is gone");
s.map_mut().add_raster("Soil".to_string(), raster);
let mut said = |legend: Value| {
let p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "colorbar": "none", "legend": legend});
s.run("layout.publication", &p).unwrap()["warnings"].to_string()
};
let listed = said(json!({}));
assert!(listed.contains("couldn't be read, so the legend has a fixed size"), "{listed}");
let left_out = said(json!({"exclude": ["Soil"]}));
assert!(!left_out.contains("fixed size"), "{left_out}");
let _ = std::fs::remove_file(points);
}

#[test]
fn a_publication_legend_lists_the_layers_asked_to_leave_out_first() {
// A loaded project keeps the first `MAX_LEGEND_EXCLUDED` names: those asked come first.
Expand Down
11 changes: 11 additions & 0 deletions crates/map/src/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,17 @@ impl RasterLayer {
self.in_place || self.tiled
}

/// Whether a read of its pixels is still under way.
pub fn is_reading(&self) -> bool {
self.opening.is_some()
}

/// Whether its style is a placeholder until its pixels land: how it draws, by classes or not,
/// isn't known yet.
pub fn awaits_style(&self) -> bool {
self.restyle
}

/// Detaches a fully read replacement from the prior opening's pending reads and notices.
pub fn reset_replacement_read(&mut self) {
self.read_generation = next_read_generation();
Expand Down
4 changes: 3 additions & 1 deletion crates/render/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,9 @@ fn draw_page(
let scale = map.ground_res_at(&cam) / rustgis_geom::PIXEL_M;
map.sync_sources_in(&lonlat, own.as_ref(), scale, true, env);
let mut failed_source = None;
let Some(entries) = complete_shown_legends(map, scale, *show_no_data, &mut failed_source, env) else {
// Every layer, those a legend leaves out too: the frame draws them, and the legends of
// a frame share this read, each leaving out its own as it lists its rows.
let Some(entries) = complete_shown_legends(map, scale, *show_no_data, &[], &mut failed_source, env) else {
*source_error = failed_source_error(map, failed_source);
return None;
};
Expand Down
31 changes: 21 additions & 10 deletions crates/render/src/layout/legend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,14 @@ pub(super) fn failed_source_error(map: &Map, failed_source: Option<u64>) -> Opti
layer.source.as_ref()?.read_error().map(|why| format!("{}: {why}", layer.name))
}

/// Complete-source legends retain one minimal value per used class, never its geometry.
/// A failed traversal returns its live layer identity for the page's source-error report.
/// Complete-source legends retain one minimal value per used class, never its geometry. A layer
/// named in `exclude` isn't read from its source. A failed traversal returns its live layer
/// identity for the page's source-error report.
pub(super) fn complete_shown_legends(
map: &mut Map,
scale: f64,
show_no_data: bool,
exclude: &[String],
failed_source: &mut Option<u64>,
env: &Env,
) -> Option<Vec<(u32, Vec<LegendEntry>)>> {
Expand All @@ -66,8 +68,15 @@ pub(super) fn complete_shown_legends(
return Some(shown_legends(map, scale, show_no_data, env));
}
let style_env = env.at_scale(Some(scale));
let wanted: Vec<usize> =
map.layers.iter().enumerate().filter(|(_, l)| map.draws_at(l, scale) && legend_lists(l)).map(|(i, _)| i).collect();
// A layer left out is not read: its rows aren't listed, and its failure doesn't stop the rest.
let excluded = |name: &str| exclude.iter().any(|n| n.eq_ignore_ascii_case(name));
let wanted: Vec<usize> = map
.layers
.iter()
.enumerate()
.filter(|(_, l)| map.draws_at(l, scale) && legend_lists(l) && !excluded(&l.name))
.map(|(i, _)| i)
.collect();
let mut out = Vec::new();
for index in wanted {
let layer = map.layers.get_mut(index)?;
Expand Down Expand Up @@ -1217,9 +1226,10 @@ pub(super) fn legend_picture(pm: &mut Canvas, r: Rect, y: f32, pic: &Pixmap, ppp
/// its rows as [`legend`] draws them, the classes a frame shows at the renderer's scale denominator
/// `scale` (as the layout finds it for a frame, a complete source read through as [`render`] reads
/// it), or every class with `all_classes`. For sizing a legend to its content. `None` when a
/// complete source can't be read, as [`render`] then draws no page. A WMS or WMTS layer's legend
/// picture still on its way isn't waited for, nor counted ([`tile_legends_pending`] says whether
/// one is). Its layers' rows are measured by the `labels` it shows for them, else their names.
/// listed layer's complete source can't be read; one in `exclude` isn't read. A WMS or WMTS
/// layer's legend picture still on its way isn't waited for, nor counted
/// ([`tile_legends_pending`] says whether one is). Its layers' rows are measured by the `labels`
/// it shows for them, else their names.
pub fn legend_sizes_mm(
map: &mut Map,
scale: f64,
Expand Down Expand Up @@ -1288,10 +1298,11 @@ pub struct LegendFitted {
}

/// The rows of the legend `asked` of `map` at the renderer's scale denominator `scale`, as the
/// drawing makes them, given to `with`. `None` when a complete source can't be read.
/// drawing makes them, given to `with`. `None` when a listed layer's complete source can't be read.
fn asked_rows<T>(map: &mut Map, scale: f64, asked: &LegendAsked, with: impl FnOnce(&[LegendRow]) -> T) -> Option<T> {
let LegendAsked { all_classes, hide_other, show_no_data, layer_names, text_size, exclude, labels, class_labels } = *asked;
let drawn = if all_classes { None } else { Some(complete_shown_legends(map, scale, show_no_data, &mut None, &Env::default())?) };
let drawn =
if all_classes { None } else { Some(complete_shown_legends(map, scale, show_no_data, exclude, &mut None, &Env::default())?) };
let size = legend_size(text_size);
let opts = LegendOptions { show_no_data, hide_other, names: layer_names, exclude, labels, class_labels, scale, size, text_size };
Some(with(&legend_rows(map, drawn.as_deref(), &opts)))
Expand Down Expand Up @@ -1337,7 +1348,7 @@ fn measure_mm(m: Measured, columns: usize) -> (f64, f64) {
/// The columns and text size the legend `asked` of `map` at the renderer's scale denominator
/// `scale` is drawn at under its `fit` from its `columns`, in a room of `room_mm` (its box less its
/// title, as [`legend_title_mm`] gives it), and whether it is still wider or taller than that: the
/// drawing's own rule ([`fit_legend`]). `None` when a complete source can't be read.
/// drawing's own rule ([`fit_legend`]). `None` when a listed layer's complete source can't be read.
pub fn legend_fitted_mm(
map: &mut Map,
scale: f64,
Expand Down
2 changes: 1 addition & 1 deletion crates/render/src/layout/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -799,7 +799,7 @@ fn layout_no_data_legend_follows_the_frame() {
.unwrap();
let fallback = l.renderer.symbol_for(&l.dataset, 2);
let listed = |map: &mut Map, all: bool, show: bool| {
let drawn = (!all).then(|| complete_shown_legends(map, 1e6, show, &mut None, &Env::default()).unwrap());
let drawn = (!all).then(|| complete_shown_legends(map, 1e6, show, &[], &mut None, &Env::default()).unwrap());
let opts = LegendOptions {
show_no_data: show,
hide_other: true,
Expand Down
30 changes: 30 additions & 0 deletions crates/render/src/stream_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,36 @@ fn legend_sizing_clears_recovered_source_errors_and_reports_a_later_failure() {
}
}

#[test]
#[cfg(not(target_arch = "wasm32"))]
fn legend_sizing_reads_no_source_the_legend_leaves_out() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("classes.shp");
let mut ds = Dataset::new("classes", GeometryType::Point, vec![]);
ds.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![]);
rustgis_data::io::write_path(&ds, &path).unwrap();
let source = SourceLayer::from_path(path.to_string_lossy(), None, rustgis_data::source::open_path(&path, None).unwrap());
let mut map = Map::new("legend exclude");
let id = map.add_streamed("Survey classes", source);
// A listed layer beside it, so the legend has rows to measure.
map.add_dataset(ds);
std::fs::remove_file(&path).unwrap();
let mut sized = |exclude: &[String]| {
layout::legend_sizes_with_no_data_mm(
&mut map,
300000.0,
false,
false,
(false, rustgis_map::layout::LEGEND_TEXT_PT),
(exclude, &Default::default()),
)
};
// Left out, under any capitalisation: not read, and the layers listed are measured.
assert!(sized(&["survey CLASSES".to_string()]).is_some());
assert!(sized(&[]).is_none());
assert!(map.layer_mut(id).unwrap().source.as_ref().unwrap().error.is_some());
}

#[test]
fn chunked_label_compaction_keeps_late_priorities_stable_ties_and_nan_order() {
let candidates: Vec<Candidate> = (0..50_003)
Expand Down
Loading