From 1deb16183b70b8b0bf3f0f654191a5cf3d2c8787 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 10 Nov 2026 22:41:57 -0300 Subject: [PATCH 01/16] feat(layout): a legend lists a classified raster's classes, as the Layers pane does (#1679) A raster drawn by a colour table, unique values or class breaks is listed in a layout legend under its name, with the Layers pane's rows for it: a swatch of each class's colour and its label. Without allClasses, the classes the raster holds (its statistics, without masked values); with it, every class of a Unique Values or Classify renderer. exclude and labels work by its name, and legend_sizes_mm measures its rows, so layout.publication sizes the box and its columns to them and says when they don't fit. layout.publication no longer gives a classified raster a colorbar: the top visible raster on a ramp gets it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 24 ++++-- crates/engine/src/tests.rs | 103 ++++++++++++++++++++++- crates/map/src/raster.rs | 127 ++++++++++++++++++++++++++++ crates/render/src/layout.rs | 140 +++++++++++++++++++++++++++++-- crates/ui-egui/src/layoutview.rs | 9 +- docs/user-guide/layouts.md | 15 +++- 6 files changed, 395 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 1e44bbabb0..f02018f123 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -31,7 +31,7 @@ pub fn commands() -> Vec { r#"{"name"?: string, "page"?: "letter"|"legal"|"tabloid"|"a5"|"a4"|"a3"|"a2"|"a1"|"a0", "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "template"?: "map" (frame, title, legend, north arrow, scale bar; the default)|"blank"}"#, ), C::new("layout.publication", "New Publication Layout", "Publish › Layout", publication).inputs(publication_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"profile"?: "a4" (the default) | "a3" | "a2" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | "a4-portrait"|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster with a colour scale gets one, under the legend in its box) | "none" (no colorbar, and the legend's box has no room for one), "veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite and each arrangement by name laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, + r#"{"profile"?: "a4" (the default) | "a3" | "a2" (a sheet turned to portrait or landscape, whichever the area's map comes out larger on: its extent east to west against north to south, on the map's projection) | "a4-portrait"|"a4-landscape"|"a3-portrait"|"a3-landscape"|"a2-portrait"|"a2-landscape" (a sheet: frame, title, subtitle, the map, a boxed footer)|"figure-1col" (90 mm)|"figure-1.5col" (140 mm)|"figure-2col" (190 mm)|"thesis-full" (160 × 225 mm)|"thesis-half" (160 × 110 mm) (a figure: the map edge to edge, its title and sources left to the caption), "extent"?: [west, south, east, north] in degrees that must fit (default: the map view), "name"?: string, "title"?: text, "subtitle"?: text, "sources"?: text | [texts], "reference"?: text | [texts] (default: the projection, datum and graticule), "note"?: text, "author"?: text (default: "Made with RustGIS · {date}"; "" or [] for none), "headings"?: [the sources' heading, the reference's heading, an editorial column's heading], "locator"?: "globe" (a globe with the area outlined; the default on sheets) | "inset" (the surrounding region, the area outlined) | "none" (the default on figures), "decimal"?: "." (the default) | "," (graticule, scale bar and colorbar numbers and {scale} with a decimal comma: 0,05 and 1:6.300.000), "colorbar"?: "auto" (the default: the top visible raster on a colour scale gets one, under the legend in its box; a raster drawn by classes has them in the legend's rows instead) | "none" (no colorbar, and the legend's box has no room for one), "veil"?: true (the default: when no shape of the legend fits, a map that runs on past the extent, with a long legend, has what is outside the extent veiled and its surrounds grouped there, at up to half the scale on a sheet) | false (never veiled, and drawn at its scale; the map may still move aside), "style"?: "classic" (the default: the title over the map, the footer under it) | "banner" (the title and subtitle in a band of the accent colour across the top) | "panel" (the map at the left, a panel at the right with the title, locator, legend, sources and reference) | "editorial" (the title large in serif, a column at the right with the note, the locator and the legend) | "modular" (cards on a light page: the map, the locator and the legend each in one, the sources and reference in tinted ones) | "poster" (the page in the accent colour, the title in light text, the map in a light card, the footer in darker blocks) (a sheet's arrangement; figures leave it to the caption), "accent"?: a colour as #RRGGBB (the style's colour: its band, panel tint, headings and rules, a poster's page), "arrangement"?: "best" (the default: the favourite and each arrangement by name laid out, the one moving the least area off its corners kept, then the one leaving the least over the data, the favourite on a tie) | "favourite" (layout.arrangement's) | an arrangement by name or corner by corner, as layout.arrangement takes (the corners the locator, north arrow, legend and scale bar are at home in; one covering what the map draws there still moves)} → a new layout of the active map at a round scale, its texts wrapped to their boxes; {projection}, {datum} and {grid} in the texts are filled from the map"#, ), C::new("layout.arrangement", "Favourite Arrangement", "Publish › Layout", arrangement).roles(&[]).effects(crate::policy::Effects::NONE).view().params( r#"{"favourite"?: "classic" (the locator top left, the north arrow top right, the legend bottom left, the scale bar bottom right) | "mirrored" | "legendRight" | "legendTop" | {"locator", "northArrow", "legend", "scaleBar": "top-left"|"top-right"|"bottom-left"|"bottom-right", each a corner of its own}} → the favourite arrangement of publication layouts (kept with the app's preferences), its corners and the arrangements by name; with no favourite given, it is only shown"#, @@ -1811,7 +1811,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { (fw * 0.3, fh * 0.25) } }; - let listed = s.map().layers.iter().any(|l| s.map().shows(l) && !l.graphics && !l.is_raster()); + let listed = s.map().layers.iter().any(|l| s.map().shows(l) && crate::render::layout::legend_lists(l)); if reading && listed { (cw, ch) = (cw.max(fw * 0.3), ch.max(fh * 0.25)); sizes = None; @@ -1830,12 +1830,20 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { surrounds.push((Surround::Locator, side, side)); } surrounds.push((Surround::Arrow, aw, ah)); - // The topmost visible raster drawn on a ramp gets a colorbar, under the legend in its box (a - // map whose theme is a raster has its key there, which the legend's rows don't give). - // `"colorbar": "none"` leaves it out, and its room in the box with it (#1680). - let bar = rustgis_map::layout::colorbar_layer(s.map(), None) - .filter(|l| colorbar && l.raster.as_ref().and_then(rustgis_map::layout::color_scale).is_some()) - .map(|l| l.name.clone()); + // The topmost visible raster with a colour scale that the legend doesn't list by its classes + // gets a colorbar, under the legend in its box (a map whose theme is a raster on a ramp has its + // key there, which the legend's rows don't give). A raster drawn by classes has them in the + // legend's rows instead (#1679). `"colorbar": "none"` leaves it out, and its room in the box + // with it (#1680). + let bar = s + .map() + .layers + .iter() + .filter(|l| l.visible) + .filter_map(|l| Some((l, l.raster.as_ref()?))) + .find(|(_, r)| !r.style.renderer.draws_classes()) + .filter(|(_, r)| colorbar && rustgis_map::layout::color_scale(r).is_some()) + .map(|(l, _)| l.name.clone()); let (bar_w, bar_h) = (if sheet { 50.0 * k } else { 40.0 }, COLORBAR_MM); let bar_part = if bar.is_some() { bar_h + if ch > 0.0 { 2.0 } else { 0.0 } } else { 0.0 }; let (content_w, content_h) = (if bar.is_some() { cw.max(bar_w) } else { cw }, ch + bar_part); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bc520d580e..8405681409 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7664,14 +7664,15 @@ fn a_publication_legend_takes_the_columns_that_fit_the_free_rectangle() { fn a_publication_without_a_colorbar_sizes_the_legend_box_to_the_legend() { use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; let mut s = Session::new(Project::default()); - // A classified raster (four values, each a class), over a polygon layer the legend lists. + // A raster on a ramp (a classified one has its classes in the legend instead, #1679), over a + // polygon layer the legend lists. let (w, h) = (20u32, 20u32); let z: Vec = (0..w * h).map(|i| (i % 4) as f32 + 1.0).collect(); let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 0.5, pixel_height: -0.5 }; let r = Raster::new("classes", w, h, vec![z], gt, Crs::LonLat, None, ColorHint::Gray, "Byte").unwrap(); let bytes = geotiff::write(&r, 0).unwrap(); crate::cmd::raster::add_raster(&mut s, "classes", rustgis_map::RasterLayer::from_bytes(r, "classes.tif".to_string(), bytes)).unwrap(); - s.run("raster.symbology", &json!({"type": "unique"})).unwrap(); + s.run("raster.symbology", &json!({"type": "stretch"})).unwrap(); let path = std::env::temp_dir().join(format!("rustgis-1680-{}.geojson", std::process::id())); std::fs::write( &path, @@ -7703,6 +7704,104 @@ fn a_publication_without_a_colorbar_sizes_the_legend_box_to_the_legend() { let _ = std::fs::remove_file(&path); } +/// Adds a land cover raster over 0–10° east and north drawn by its colour table: `classes`' +/// values, each a run of cells, named as the file names them (an empty name shows the value). +fn add_land_cover(s: &mut Session, name: &str, classes: &[(u8, &str)]) { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let (w, h) = (40usize, 40usize); + let z: Vec = (0..w * h).map(|i| f32::from(classes[i * classes.len() / (w * h)].0)).collect(); + let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 0.25, pixel_height: -0.25 }; + let mut palette = vec![[0, 0, 0, 0]; 256]; + let mut names = vec![String::new(); 256]; + for (v, n) in classes { + palette[usize::from(*v)] = [v.wrapping_mul(37), v.wrapping_mul(91), 255 - v, 255]; + names[usize::from(*v)] = (*n).to_string(); + } + let mut r = Raster::new(name, w as u32, h as u32, vec![z], gt, Crs::LonLat, None, ColorHint::Palette(palette), "Byte").unwrap(); + r.bands[0].classes = names; + let bytes = geotiff::write(&r, 0).unwrap(); + let mut rl = rustgis_map::RasterLayer::from_bytes(r, format!("{name}.tif"), bytes); + rl.style.renderer = rustgis_map::raster::RasterRenderer::Colormap; + crate::cmd::raster::add_raster(s, name, rl).unwrap(); +} + +/// A publication of a land cover (MapBiomas clipped to a municipality: 11 classes in its colour +/// table) lists its classes in the legend instead of a colorbar, and sizes the box to them (#1679). +/// A raster on a ramp under it still gets the colorbar. +#[test] +fn a_publication_lists_a_land_covers_classes_instead_of_a_colorbar() { + let mapbiomas = [ + (3, "Formação Florestal"), + (4, "Formação Savânica"), + (9, "Silvicultura"), + (12, "Formação Campestre"), + (15, "Pastagem"), + (21, "Mosaico de Usos"), + (24, "Área Urbanizada"), + (33, "Rio, Lago e Oceano"), + (39, "Soja"), + (41, "Outras Lavouras Temporárias"), + (46, "Café"), + ]; + let mut s = Session::new(Project::default()); + add_land_cover(&mut s, "Uso do solo", &mapbiomas); + let p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "author": "", "locator": "none"}); + let r = s.run("layout.publication", &p).unwrap(); + let l = s.project.layouts.last().unwrap(); + let el = |name: &str| l.elements.iter().find(|e| e.name == name); + assert!(el("Colorbar").is_none(), "the classes are the key: {r}"); + let (bx, legend) = (el("Legend Box").unwrap().h, el("Legend").unwrap().h); + assert!((bx - legend - 4.0).abs() < 1e-6, "{bx} {legend}: {r}"); + // Its name and 11 classes, in the columns it took. + let row = 15.0 * 25.4 / 96.0; + let columns = r["legendColumns"].as_f64().unwrap_or(1.0); + assert!(legend >= (12.0 / columns).floor() * row - 1e-6, "{legend} mm in {columns}: {r}"); + assert!(!r["warnings"].to_string().contains("more than fits"), "{r}"); + let map = s.map_mut(); + let sizes = crate::render::layout::legend_sizes_mm(map, 1e6, false, false, (&[], &Default::default())).unwrap(); + assert!((sizes[0].1 - 12.0 * row).abs() < 1e-6, "{sizes:?}"); + // A stretched raster under it: its colorbar stays, and the classes too. + { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 0.5, pixel_height: -0.5 }; + let z: Vec = (0..400).map(|i| i as f32 * 1.5).collect(); + let dem = Raster::new("dem", 20, 20, vec![z], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let bytes = rustgis_data::raster::geotiff::write(&dem, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "Altitude", rustgis_map::RasterLayer::from_bytes(dem, "dem.tif".to_string(), bytes)) + .unwrap(); + } + s.run("layer.move", &json!({"layer": "Altitude", "to": 99})).unwrap(); + let r = s.run("layout.publication", &p).unwrap(); + let l = s.project.layouts.last().unwrap(); + let bar = l.elements.iter().find_map(|e| match &e.kind { + rustgis_map::layout::ElementKind::Colorbar { layer, .. } => Some(layer.clone()), + _ => None, + }); + assert_eq!(bar, Some(Some("Altitude".to_string())), "{r}"); + assert!(l.elements.iter().any(|e| e.name == "Legend"), "{r}"); +} + +/// A land cover with more classes than its legend's box holds: the publication says it leaves the +/// last out, and so does a legend added in a small box; five classes fit, and nothing is said +/// (#1679). +#[test] +fn a_legend_with_too_many_raster_classes_says_it_leaves_some_out() { + let names: Vec = (1..=200).map(|v| format!("Classe {v}")).collect(); + let classes: Vec<(u8, &str)> = names.iter().enumerate().map(|(i, n)| (i as u8 + 1, n.as_str())).collect(); + let publication = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "author": "", "locator": "none"}); + let legend = json!({"kind": "legend", "x": 10, "y": 10, "w": 60, "h": 60, "columns": 2}); + for (n, cut) in [(200, true), (5, false)] { + let mut s = Session::new(Project::default()); + add_land_cover(&mut s, "Uso do solo", &classes[..n]); + let r = s.run("layout.publication", &publication).unwrap(); + assert_eq!(r["warnings"].to_string().contains("more than fits its box"), cut, "{n} classes: {r}"); + let mark = s.notice_mark(); + s.run("layout.addElement", &legend).unwrap(); + let said = s.notices_since(mark).iter().any(|n| n.text.contains("more than fits its box")); + assert_eq!(said, cut, "{n} classes: {:?}", s.notices_since(mark)); + } +} + /// A smaller scale whose legend can't be measured (a streamed layer shown only there, whose file is /// gone) isn't tried, and the result says so. #[test] diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index e54be60c54..59616867e9 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1012,6 +1012,12 @@ impl RasterRenderer { RasterRenderer::KINDS.iter().find(|(c, _)| *c == self.code()).map(|(_, l)| *l).unwrap_or("Stretch") } + /// Whether it draws classes (a colour table, unique values, class breaks), which a legend lists + /// as the Layers pane does (#1679), rather than a ramp or bands. + pub fn draws_classes(&self) -> bool { + matches!(self, RasterRenderer::Classify { .. } | RasterRenderer::UniqueValues { .. } | RasterRenderer::Colormap) + } + /// The bands it reads. pub fn bands(&self) -> Vec { match self { @@ -1658,6 +1664,56 @@ impl RasterLayer { } } } + + /// The classes a layout's legend lists for this raster (#1679): the Layers pane's class rows + /// ([`RasterLayer::legend`]), a colour and a label each, in the renderer's order. `None` for a + /// renderer that draws no classes (a stretch, a hillshade, RGB bands), which a colorbar keys. + /// Without `all_classes`, the classes the raster holds: those of the values in its statistics + /// (without the masked pixels). A raster with too many values to list (over 256, or not whole) + /// gives every Unique Values class, and for Classify the classes from its lowest value's to its + /// highest's. With `all_classes`, every class of a Unique Values or Classify renderer. A colour + /// table's 256 entries have no meaningful "all": it lists the values the raster holds either + /// way, as the Layers pane does. + pub fn legend_classes(&self, all_classes: bool) -> Option> { + let classes = || { + self.legend().into_iter().filter_map(|row| match row { + RasterLegend::Class { color, label } => Some((color, label)), + _ => None, + }) + }; + if !self.style.renderer.draws_classes() { + return None; + } + // Not read (yet): no class known. + let Some(r) = self.data.as_ref() else { return Some(Vec::new()) }; + let masked = self.masked_stats(); + let stats = |band: usize| masked.as_ref().and_then(|m| m.first()).or_else(|| r.bands.get(band).map(|b| &b.stats)); + match &self.style.renderer { + RasterRenderer::Colormap => Some(classes().collect()), + RasterRenderer::UniqueValues { band, values, .. } => { + let held = stats(*band).and_then(|s| s.categories.as_ref()).filter(|_| !all_classes); + // The pane's rows are the values its mask doesn't hide, one each, in order. + let shown = values.iter().filter(|(v, _)| !self.style.mask.hides(*v as f32)); + Some(shown.zip(classes()).filter(|((v, _), _)| held.is_none_or(|held| held.contains(v))).map(|(_, class)| class).collect()) + } + RasterRenderer::Classify { band, breaks, .. } => { + // The class a value is drawn in, as the map draws it: the first break at or above + // it, else the last class. + let class_of = |v: f64| breaks.iter().position(|b| v <= *b).unwrap_or(breaks.len().saturating_sub(1)); + let held: Option> = match stats(*band) { + _ if all_classes => None, + Some(s) if s.count == 0 => Some(Vec::new()), + Some(s) => Some(match &s.categories { + Some(values) => values.iter().map(|v| class_of(*v)).collect(), + None => (class_of(s.min)..=class_of(s.max)).collect(), + }), + None => None, + }; + Some(classes().enumerate().filter(|(i, _)| held.as_ref().is_none_or(|held| held.contains(i))).map(|(_, c)| c).collect()) + } + RasterRenderer::Stretch { .. } | RasterRenderer::Rgb { .. } | RasterRenderer::ShadedRelief { .. } => None, + } + } } impl RasterLayer { @@ -1778,6 +1834,77 @@ mod tests { assert_eq!(labels(&rl), ["1", "2", "3"], "no names: the values, as before"); } + /// A layout's legend lists a classified raster's classes as the Layers pane draws them (#1679): + /// those the raster holds, or every class of a Unique Values or Classify renderer with + /// `all_classes`; a colour table the values it holds either way; a ramp or bands none. + #[test] + fn legend_classes_are_the_panes_rows_the_raster_holds() { + let gt = GeoTransform { origin_x: 10.0, origin_y: 50.0, pixel_width: 0.5, pixel_height: -0.5 }; + let mut palette = vec![[0, 0, 0, 0]; 256]; + for v in 1..=7u8 { + palette[usize::from(v)] = [v * 30, 100, 200 - v * 20, 255]; + } + // Five classes held (1 to 5), two named in the file. + let values: Vec = (1..=5).map(|v| v as f32).collect(); + let mut r = Raster::new("lc", 5, 1, vec![values], gt, Crs::LonLat, None, ColorHint::Palette(palette), "UInt8").unwrap(); + r.bands[0].classes = vec![String::new(), "Forest".into(), String::new(), "Pasture".into()]; + let mut rl = RasterLayer::from_path(r, "lc.tif"); + let labels = |rl: &RasterLayer, all: bool| -> Vec { rl.legend_classes(all).unwrap().into_iter().map(|(_, l)| l).collect() }; + let pane = |rl: &RasterLayer| -> Vec<(Rgba, String)> { + rl.legend() + .into_iter() + .filter_map(|e| match e { + RasterLegend::Class { color, label } => Some((color, label)), + _ => None, + }) + .collect() + }; + rl.style.renderer = RasterRenderer::Colormap; + assert_eq!(labels(&rl, false), ["Forest", "2", "Pasture", "4", "5"]); + assert_eq!(rl.legend_classes(true), rl.legend_classes(false), "a colour table: the values held either way"); + assert_eq!(rl.legend_classes(false).unwrap(), pane(&rl), "the pane's colours and labels"); + // Unique values for 1 to 7: the raster holds five. + let unique = (1..=7u8).map(|v| (f64::from(v), Rgba::rgb(v * 30, 0, 0))).collect(); + rl.style.renderer = RasterRenderer::UniqueValues { band: 0, ramp: Ramp::Harbour, values: unique }; + assert_eq!(labels(&rl, false), ["Forest", "2", "Pasture", "4", "5"]); + assert_eq!(labels(&rl, true), ["Forest", "2", "Pasture", "4", "5", "6", "7"]); + assert_eq!(rl.legend_classes(true).unwrap(), pane(&rl), "every class: the pane's rows"); + assert_eq!(rl.legend_classes(false).unwrap()[0].0, Rgba::rgb(30, 0, 0)); + // A value its mask hides is left out, held or not. + rl.style.mask = RasterMask { values: vec![2.0, 6.0], ..RasterMask::default() }; + assert_eq!(labels(&rl, false), ["Forest", "Pasture", "4", "5"]); + assert_eq!(labels(&rl, true), ["Forest", "Pasture", "4", "5", "7"]); + rl.style.mask = RasterMask::default(); + // Class breaks: values 1 to 5 fall in the first three of four classes. + let breaks = vec![2.0, 4.0, 10.0, 20.0]; + rl.style.renderer = + RasterRenderer::Classify { band: 0, method: ClassMethod::EqualInterval, ramp: Ramp::Harbour, breaks, classes: 4 }; + assert_eq!(labels(&rl, false), ["1 – 2", "2 – 4", "4 – 10"]); + assert_eq!(labels(&rl, true), ["1 – 2", "2 – 4", "4 – 10", "10 – 20"]); + // A ramp and bands have no classes: a colorbar keys them, or nothing does. + rl.style.renderer = RasterRenderer::Stretch { band: 0, ramp: Ramp::Harbour, invert: false }; + assert_eq!(rl.legend_classes(false), None); + rl.style.renderer = RasterRenderer::Rgb { red: 0, green: 0, blue: 0 }; + assert_eq!(rl.legend_classes(true), None); + } + + /// Class breaks over a raster with too many values to list them: the classes from its lowest + /// value's to its highest's (#1679). + #[test] + fn legend_classes_of_breaks_over_many_values_follow_the_range() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 0.01, pixel_height: -0.01 }; + // 1,000 distinct values from 100 to 199.9: no categories. + let values: Vec = (0..1000).map(|i| 100.0 + i as f32 / 10.0).collect(); + let r = Raster::new("dem", 1000, 1, vec![values], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + assert!(r.bands[0].stats.categories.is_none()); + let mut rl = RasterLayer::from_path(r, "dem.tif"); + let breaks = vec![50.0, 120.0, 150.0, 200.0, 300.0]; + rl.style.renderer = + RasterRenderer::Classify { band: 0, method: ClassMethod::EqualInterval, ramp: Ramp::Harbour, breaks, classes: 5 }; + let n = |all| rl.legend_classes(all).unwrap().len(); + assert_eq!((n(false), n(true)), (3, 5), "120, 150 and 200: the classes 100 to 199.9 fall in"); + } + /// A following layer's dates are its steps from `offset` on, one each: repair keeps them as /// they are when they are in order, and follows none rather than the wrong step otherwise. #[test] diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 68555a3405..a75e02af1a 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1457,23 +1457,54 @@ fn scale_bar( fn shown_legends(map: &Map, scale: f64) -> Vec<(u32, Vec)> { map.layers .iter() - .filter(|l| map.draws_at(l, scale) && !l.graphics && !l.is_raster()) - .filter_map(|l| l.shown_legend(scale).map(|entries| (l.id, entries))) + .filter(|l| map.draws_at(l, scale) && legend_lists(l)) + .filter_map(|l| layer_shown(l, scale).map(|entries| (l.id, entries))) .collect() } +/// Whether a legend can list a layer: a vector layer, by its symbols, or a raster drawn by classes +/// (a colour table, unique values, class breaks), by its classes (#1679). Not a graphics layer, +/// nor a raster on a ramp or in RGB bands, which a colorbar keys or nothing does. +pub fn legend_lists(l: &rustgis_map::Layer) -> bool { + !l.graphics && l.raster.as_ref().is_none_or(|r| r.style.renderer.draws_classes()) +} + +/// What a layer a legend lists draws at 1:`scale` ([`rustgis_map::Layer::shown_legend`]); for a +/// classified raster, the classes it holds ([`raster_classes`]). `None` when it draws nothing +/// there. +fn layer_shown(l: &rustgis_map::Layer, scale: f64) -> Option> { + if l.is_raster() { + return raster_classes(l, false).filter(|classes| l.in_scale_range(scale) && !classes.is_empty()); + } + l.shown_legend(scale) +} + +/// A classified raster's classes as legend rows (#1679), as the Layers pane draws them +/// ([`rustgis_map::RasterLayer::legend_classes`]): a filled swatch with a thin outline, and its +/// label. `None` for a raster on a ramp or in RGB bands, and for a vector layer. +fn raster_classes(l: &rustgis_map::Layer, all_classes: bool) -> Option> { + let classes = l.raster.as_ref()?.legend_classes(all_classes)?; + let symbol = |fill| rustgis_map::Symbol { fill, stroke: RASTER_SWATCH_EDGE, stroke_width: 0.5, size: 0.0, marker: Default::default() }; + Some( + classes + .into_iter() + .map(|(fill, label)| LegendEntry { label, symbol: symbol(fill), strokes: Vec::new(), fallback: false }) + .collect(), + ) +} + /// Complete-source legends retain one minimal value per used class, never its geometry. fn complete_shown_legends(map: &mut Map, scale: f64) -> Option)>> { if !map.layers.iter().any(|l| l.source.as_ref().and_then(|s| s.chunk_source()).is_some()) { return Some(shown_legends(map, scale)); } let wanted: Vec = - map.layers.iter().enumerate().filter(|(_, l)| map.draws_at(l, scale) && !l.graphics && !l.is_raster()).map(|(i, _)| i).collect(); + map.layers.iter().enumerate().filter(|(_, l)| map.draws_at(l, scale) && legend_lists(l)).map(|(i, _)| i).collect(); let mut out = Vec::new(); for index in wanted { let layer = map.layers.get_mut(index)?; let Some(source) = layer.source.as_ref().and_then(|s| s.chunk_source()) else { - if let Some(entries) = layer.shown_legend(scale) { + if let Some(entries) = layer_shown(layer, scale) { out.push((layer.id, entries)); } continue; @@ -1748,6 +1779,8 @@ const MAX_LEGEND_SIDE: u32 = 2048; /// A legend's text colour. const LEGEND_TEXT: Rgba = Rgba::rgb(0x22, 0x22, 0x22); +/// The outline of a raster class's swatch in a legend, as the Layers pane draws one around it. +const RASTER_SWATCH_EDGE: Rgba = Rgba::rgb(0x80, 0x80, 0x80); /// A legend row's height, in points. const LEGEND_ROW: f32 = 15.0; /// A legend swatch's width, in points. @@ -1779,7 +1812,7 @@ fn legend_rows<'a>(map: &'a Map, drawn: Option<&[(u32, Vec)]>, opts continue; } }; - if !(map.shows(l) && !l.graphics && !l.is_raster() && !excluded(&l.name)) { + if !(map.shows(l) && legend_lists(l) && !excluded(&l.name)) { continue; } let mut entries = match drawn { @@ -1787,6 +1820,8 @@ fn legend_rows<'a>(map: &'a Map, drawn: Option<&[(u32, Vec)]>, opts Some((_, entries)) => entries.clone(), None => continue, }, + // A classified raster's every class (#1679). + None if l.is_raster() => raster_classes(l, true).unwrap_or_default(), None => l.renderer.legend(), }; // The fallback row only (a class that happens to bear its name stays). @@ -1803,8 +1838,9 @@ fn legend_rows<'a>(map: &'a Map, drawn: Option<&[(u32, Vec)]>, opts entries.extend(d.legend(l.geometry_type() == GeometryType::Polyline)); } if entries.is_empty() { - // A Unique Values layer that lists nothing draws nothing visible (#207). - if !matches!(l.renderer, rustgis_map::Renderer::Unique { .. }) { + // A Unique Values layer that lists nothing draws nothing visible (#207); a raster has + // no symbol of its own to show. + if !l.is_raster() && !matches!(l.renderer, rustgis_map::Renderer::Unique { .. }) { rows.push(LegendRow::Plain(l, opts.shown(&l.name))); } continue; @@ -3310,6 +3346,96 @@ mod tests { map } + /// A map with a land cover raster of `n` classes (values 1 to `n`, one cell each) drawn by its + /// colour table, the first named "Forest". + fn classes_map(n: u8) -> Map { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 0.01, pixel_height: -0.01 }; + let mut palette = vec![[0, 0, 0, 0]; 256]; + for v in 1..=n { + palette[usize::from(v)] = [v, 255 - v, 128, 255]; + } + let data: Vec = (1..=n).map(f32::from).collect(); + let mut r = Raster::new("lc", u32::from(n), 1, vec![data], gt, Crs::LonLat, None, ColorHint::Palette(palette), "UInt8").unwrap(); + r.bands[0].classes = vec![String::new(), "Forest".into()]; + let mut rl = rustgis_map::raster::RasterLayer::from_path(r, "lc.tif"); + rl.style.renderer = rustgis_map::raster::RasterRenderer::Colormap; + let mut map = Map::new("m"); + map.add_raster("Land cover", rl); + map + } + + /// A classified raster's legend: its name over its classes, as the Layers pane lists them, by + /// what the frame shows and with every class alike (a colour table lists the values it holds); + /// left out by name; a raster on a ramp isn't listed (#1679). + #[test] + fn a_legend_lists_a_classified_rasters_classes() { + let mut map = classes_map(5); + let opts = LegendOptions { hide_other: true, exclude: &[], labels: &NO_LABELS, scale: 1e6 }; + let labels = |rows: &[LegendRow]| -> Vec { + rows.iter() + .map(|r| match r { + LegendRow::Head(name) => format!("[{name}]"), + LegendRow::Class(_, en) => en.label.clone(), + LegendRow::Plain(_, name) => format!("plain {name}"), + LegendRow::Picture(_) => "picture".into(), + }) + .collect() + }; + let want = ["[Land cover]", "Forest", "2", "3", "4", "5"]; + assert_eq!(labels(&legend_rows(&map, None, &opts)), want); + let drawn = shown_legends(&map, 1e6); + assert_eq!(labels(&legend_rows(&map, Some(&drawn), &opts)), want); + // Its swatches are the pane's colours. + let pane: Vec = map.layers[0] + .raster + .as_ref() + .unwrap() + .legend() + .into_iter() + .filter_map(|e| match e { + rustgis_map::raster::RasterLegend::Class { color, .. } => Some(color), + _ => None, + }) + .collect(); + let swatches: Vec = legend_rows(&map, None, &opts) + .iter() + .filter_map(|r| if let LegendRow::Class(_, en) = r { Some(en.symbol.fill) } else { None }) + .collect(); + assert_eq!(swatches, pane); + // Sized by its rows: its name and five classes. + let mm = 25.4 / 96.0; + let [(_, h), ..] = legend_sizes_mm(&mut map, 1e6, false, false, (&[], &NO_LABELS)).unwrap(); + assert!((h - 6.0 * f64::from(LEGEND_ROW) * mm).abs() < 1e-6, "{h} mm"); + let labelled = BTreeMap::from([("Land cover".to_string(), "Classes do MapBiomas".to_string())]); + let opts_labelled = LegendOptions { labels: &labelled, ..opts }; + assert_eq!(labels(&legend_rows(&map, None, &opts_labelled))[0], "[Classes do MapBiomas]"); + // Left out by name, or when hidden. + let exclude = ["land cover".to_string()]; + assert!(legend_rows(&map, None, &LegendOptions { exclude: &exclude, ..opts }).is_empty()); + map.layers[0].visible = false; + assert!(shown_legends(&map, 1e6).is_empty()); + assert!(legend_rows(&map, None, &opts).is_empty()); + // A raster on a ramp: a colorbar keys it, the legend doesn't list it. + let ramp = ramp_map( + rustgis_map::raster::RasterRenderer::Stretch { band: 0, ramp: rustgis_map::Ramp::Harbour, invert: false }, + rustgis_map::raster::Stretch::MinMax, + ); + assert!(legend_rows(&ramp, None, &opts).is_empty() && shown_legends(&ramp, 1e6).is_empty()); + } + + /// A drawn legend fills each class's swatch with its colour, under the raster's name. + #[test] + fn a_drawn_legend_fills_a_raster_class_with_its_colour() { + let map = classes_map(5); + let pm = point_legend(&map); + for v in 1..=5u8 { + let c = (v, 255 - v, 128); + let found = pm.pixels().iter().any(|p| (p.red(), p.green(), p.blue()) == c); + assert!(found, "class {v}'s colour {c:?}"); + } + } + /// A page with a main frame and an inset (5–55 mm) that outlines it in `color` at `width`. fn indicator_page(color: Rgba, width: f64) -> Pixmap { let map = Map::new("m"); diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index 6de19d22ce..80597c0652 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -1958,8 +1958,8 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { update(app, font); } } - // The layers a legend lists: a checkbox for each vector layer of its frame's map and each - // WMS or WMTS layer with a legend, ticked when listed. Names gone from the map drop out of + // The layers a legend lists: a checkbox for each vector layer of its frame's map, each raster + // drawn by classes (#1679) and each WMS or WMTS layer with a legend, ticked when listed. Names gone from the map drop out of // the list as it's written back. if let ElementKind::Legend { frame, exclude, .. } = &e.kind { let map = layout.element(*frame).and_then(|f| match &f.kind { @@ -1970,7 +1970,7 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { .map(|m| { // Once each: layers may share a name, and the legend leaves names out. let mut names: Vec = Vec::new(); - let listed = m.layers.iter().filter(|l| !l.graphics && !l.is_raster()).map(|l| &l.name); + let listed = m.layers.iter().filter(|l| rustgis_engine::render::layout::legend_lists(l)).map(|l| &l.name); for name in listed.chain(m.tiles.iter().filter(|t| !t.legends.is_empty()).map(|t| &t.name)) { if !names.iter().any(|n| n.eq_ignore_ascii_case(name)) { names.push(name.clone()); @@ -1979,7 +1979,8 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { names }) .unwrap_or_default(); - // The names left out that the map still has, those not listed here (a raster's) too. + // The names left out that the map still has, those not listed here (a raster's on a ramp) + // too. let kept: Vec = exclude .iter() .filter(|x| { diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 544a17078f..4124a0e87e 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -55,8 +55,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu size had more than a quarter less, to move by hand if that matters (data under every corner alike, such as a context layer filling the frame, isn't worth a warning); two that overlap (a frame too small) are said too. - The top visible raster gets a colorbar beneath the vector legend if its renderer has a colour - scale; RGB and untinted hillshade do not. `"colorbar": "none"` leaves it out, and the legend's + The top visible raster on a colour scale (Stretch, a tinted hillshade) gets a colorbar + beneath the legend; RGB and untinted hillshade do not. A raster drawn by classes (Colormap, + Unique Values, Classify) has its classes in the legend's rows instead, so a map whose only + theme is a land cover gets a filled legend and no colorbar. `"colorbar": "none"` leaves it out, and the legend's box is sized for the legend alone: hiding the colorbar afterwards would leave its room empty in the box. The legend takes the fewest columns, up to three, that fit the largest rectangle the map leaves free; when none fits, a long one is laid in more @@ -190,6 +192,15 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu (`"allClasses": true`) to list every class of every visible layer instead, and **Hide other values** (`"hideOther": true`) to leave `` out of the legend in either mode (the features it stands for are still drawn). + - **Rasters drawn by classes** (Colormap, Unique Values, Classify) are listed under their name + with the rows the Layers pane shows for them: a swatch of each class's colour and its label, + the class name in the file when it has one, else the value or the range. The legend lists the + classes the raster holds (the values in its statistics, without those its mask hides; for + Classify on a raster with too many values to list, the classes from its lowest value to its + highest), and with **All classes** every class of a Unique Values or Classify renderer. A + colour table lists the values the raster holds either way: its 256 entries have no + meaningful "all". Rasters on a ramp (Stretch, a tinted hillshade) and RGB composites are left + out: a colorbar keys the ramp. **Exclude** leaves a classified raster out by its name. - **Columns** (`"columns"`, 1 to 3): its rows side by side under its title, as even as they go, each column as wide as its widest row, with its own column of symbols, and a layer's name staying with the row under it. The box keeps its size, so widen it for the columns: in a box From 3468bd2c5414e380fda1bef8932f5eb9298e026e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 11 Nov 2026 00:12:50 -0300 Subject: [PATCH 02/16] fix(layout): the colorbar goes to the top raster with a colour scale; an unlisted colour table is said (#1679) layout.publication gave the colorbar to the topmost visible raster that doesn't draw classes and dropped it when that one had no colour scale, so an RGB composite over a DEM left the DEM without a key; it now takes the topmost one with a colour scale, as its comment and the guide say. A colour table over more values than its statistics list (over 256, or not whole) gives the legend no class and a colorbar none: the publication now warns (RasterLayer::classes_unknown). Comment and guide rewrapped. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 19 +++++++++--- crates/engine/src/tests.rs | 53 ++++++++++++++++++++++++++++++++ crates/map/src/raster.rs | 19 ++++++++++-- crates/ui-egui/src/layoutview.rs | 4 +-- docs/user-guide/layouts.md | 15 +++++---- 5 files changed, 95 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index f02018f123..2a5efbdfe2 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1832,18 +1832,27 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { surrounds.push((Surround::Arrow, aw, ah)); // The topmost visible raster with a colour scale that the legend doesn't list by its classes // gets a colorbar, under the legend in its box (a map whose theme is a raster on a ramp has its - // key there, which the legend's rows don't give). A raster drawn by classes has them in the - // legend's rows instead (#1679). `"colorbar": "none"` leaves it out, and its room in the box - // with it (#1680). + // key there, which the legend's rows don't give): an RGB composite over a DEM leaves it to the + // DEM. A raster drawn by classes has them in the legend's rows instead (#1679). `"colorbar": + // "none"` leaves it out, and its room in the box with it (#1680). let bar = s .map() .layers .iter() .filter(|l| l.visible) .filter_map(|l| Some((l, l.raster.as_ref()?))) - .find(|(_, r)| !r.style.renderer.draws_classes()) - .filter(|(_, r)| colorbar && rustgis_map::layout::color_scale(r).is_some()) + .find(|(_, r)| colorbar && !r.style.renderer.draws_classes() && rustgis_map::layout::color_scale(r).is_some()) .map(|(l, _)| l.name.clone()); + // A colour table whose values can't be known (too many to list) gives the legend no class, and + // the sheet no key for it: said rather than left blank. + for l in s.map().layers.iter().filter(|l| s.map().shows(l)) { + if l.raster.as_ref().is_some_and(rustgis_map::RasterLayer::classes_unknown) { + warnings.push(format!( + "'{}' draws its colour table over more values than a legend can list (over 256, or not whole numbers): the legend has no key for it", + l.name + )); + } + } let (bar_w, bar_h) = (if sheet { 50.0 * k } else { 40.0 }, COLORBAR_MM); let bar_part = if bar.is_some() { bar_h + if ch > 0.0 { 2.0 } else { 0.0 } } else { 0.0 }; let (content_w, content_h) = (if bar.is_some() { cw.max(bar_w) } else { cw }, ch + bar_part); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8405681409..046a90c2e8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7781,6 +7781,59 @@ fn a_publication_lists_a_land_covers_classes_instead_of_a_colorbar() { assert!(l.elements.iter().any(|e| e.name == "Legend"), "{r}"); } +/// The colorbar goes to the topmost visible raster with a colour scale: an RGB composite over a +/// stretched DEM leaves it to the DEM. A colour table over more values than a legend lists gives +/// neither classes nor a colorbar, and the publication says so; one with its classes known says +/// nothing (#1679). +#[test] +fn a_publication_keys_the_raster_under_an_rgb_and_says_an_unlisted_colour_table() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + use rustgis_map::layout::ElementKind; + let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 0.5, pixel_height: -0.5 }; + let add = |s: &mut Session, name: &str, r: Raster| { + let bytes = geotiff::write(&r, 0).unwrap(); + crate::cmd::raster::add_raster(s, name, rustgis_map::RasterLayer::from_bytes(r, format!("{name}.tif"), bytes)).unwrap(); + }; + let p = json!({"profile": "a4-portrait", "extent": [0, 0, 10, 10], "author": "", "locator": "none"}); + let bar_of = |s: &Session| { + s.project.layouts.last().unwrap().elements.iter().find_map(|e| match &e.kind { + ElementKind::Colorbar { layer, .. } => Some(layer.clone()), + _ => None, + }) + }; + // A stretched DEM under an RGB composite. + let mut s = Session::new(Project::default()); + let z: Vec = (0..400).map(|i| i as f32 * 1.5).collect(); + add(&mut s, "Altitude", Raster::new("dem", 20, 20, vec![z], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap()); + let band = |k: f32| (0..400).map(|i| (i as f32 * k) % 255.0).collect::>(); + let rgb = + Raster::new("rgb", 20, 20, vec![band(1.0), band(2.0), band(3.0)], gt, Crs::LonLat, None, ColorHint::Rgb { alpha: false }, "Byte"); + add(&mut s, "Imagem", rgb.unwrap()); + assert!(s.map().layers[0].raster.as_ref().is_some_and(|r| matches!(r.style.renderer, rustgis_map::RasterRenderer::Rgb { .. }))); + let r = s.run("layout.publication", &p).unwrap(); + assert_eq!(bar_of(&s), Some(Some("Altitude".to_string())), "{r}"); + // A colour table over 300 values: no class to list, no colorbar, and a warning. + let mut s = Session::new(Project::default()); + let mut palette = vec![[0, 0, 0, 0]; 256]; + for (i, c) in palette.iter_mut().enumerate() { + *c = [i as u8, 100, 255 - i as u8, 255]; + } + let z: Vec = (0..400).map(|i| (i % 300) as f32).collect(); + let many = Raster::new("many", 20, 20, vec![z], gt, Crs::LonLat, None, ColorHint::Palette(palette), "UInt16").unwrap(); + assert!(many.bands[0].stats.categories.is_none()); + let mut rl = rustgis_map::RasterLayer::from_path(many, "many.tif"); + rl.style.renderer = rustgis_map::RasterRenderer::Colormap; + crate::cmd::raster::add_raster(&mut s, "Classes", rl).unwrap(); + let r = s.run("layout.publication", &p).unwrap(); + assert_eq!(bar_of(&s), None, "{r}"); + assert!(r["warnings"].to_string().contains("'Classes' draws its colour table over more values than a legend can list"), "{r}"); + // Its classes known: nothing said. + let mut s = Session::new(Project::default()); + add_land_cover(&mut s, "Uso do solo", &[(3, "Floresta"), (15, "Pastagem")]); + let r = s.run("layout.publication", &p).unwrap(); + assert!(!r["warnings"].to_string().contains("more values than a legend"), "{r}"); +} + /// A land cover with more classes than its legend's box holds: the publication says it leaves the /// last out, and so does a legend added in a small box; five classes fit, and nothing is said /// (#1679). diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 59616867e9..a28dc8603e 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1665,13 +1665,21 @@ impl RasterLayer { } } + /// Whether it is drawn by its colour table over values its statistics don't list (over 256 + /// distinct values, or values that aren't whole): [`RasterLayer::legend_classes`] then has no + /// class to give, and a colorbar none either (#1679). + pub fn classes_unknown(&self) -> bool { + matches!(self.style.renderer, RasterRenderer::Colormap) + && self.data.as_ref().and_then(|r| r.bands.first()).is_some_and(|b| b.stats.count > 0 && b.stats.categories.is_none()) + } + /// The classes a layout's legend lists for this raster (#1679): the Layers pane's class rows /// ([`RasterLayer::legend`]), a colour and a label each, in the renderer's order. `None` for a /// renderer that draws no classes (a stretch, a hillshade, RGB bands), which a colorbar keys. /// Without `all_classes`, the classes the raster holds: those of the values in its statistics /// (without the masked pixels). A raster with too many values to list (over 256, or not whole) - /// gives every Unique Values class, and for Classify the classes from its lowest value's to its - /// highest's. With `all_classes`, every class of a Unique Values or Classify renderer. A colour + /// gives every Unique Values class, for Classify the classes from its lowest value's to its + /// highest's, and for a colour table none ([`RasterLayer::classes_unknown`]). With `all_classes`, every class of a Unique Values or Classify renderer. A colour /// table's 256 entries have no meaningful "all": it lists the values the raster holds either /// way, as the Layers pane does. pub fn legend_classes(&self, all_classes: bool) -> Option> { @@ -1881,6 +1889,9 @@ mod tests { RasterRenderer::Classify { band: 0, method: ClassMethod::EqualInterval, ramp: Ramp::Harbour, breaks, classes: 4 }; assert_eq!(labels(&rl, false), ["1 – 2", "2 – 4", "4 – 10"]); assert_eq!(labels(&rl, true), ["1 – 2", "2 – 4", "4 – 10", "10 – 20"]); + assert!(!rl.classes_unknown(), "breaks, not a colour table"); + rl.style.renderer = RasterRenderer::Colormap; + assert!(!rl.classes_unknown(), "its values are known"); // A ramp and bands have no classes: a colorbar keys them, or nothing does. rl.style.renderer = RasterRenderer::Stretch { band: 0, ramp: Ramp::Harbour, invert: false }; assert_eq!(rl.legend_classes(false), None); @@ -1903,6 +1914,10 @@ mod tests { RasterRenderer::Classify { band: 0, method: ClassMethod::EqualInterval, ramp: Ramp::Harbour, breaks, classes: 5 }; let n = |all| rl.legend_classes(all).unwrap().len(); assert_eq!((n(false), n(true)), (3, 5), "120, 150 and 200: the classes 100 to 199.9 fall in"); + // By a colour table, over values it can't list: no class, said by `classes_unknown`. + rl.style.renderer = RasterRenderer::Colormap; + assert_eq!(rl.legend_classes(false), Some(Vec::new())); + assert!(rl.classes_unknown()); } /// A following layer's dates are its steps from `offset` on, one each: repair keeps them as diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index 80597c0652..4cd151b1fe 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -1959,8 +1959,8 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { } } // The layers a legend lists: a checkbox for each vector layer of its frame's map, each raster - // drawn by classes (#1679) and each WMS or WMTS layer with a legend, ticked when listed. Names gone from the map drop out of - // the list as it's written back. + // drawn by classes (#1679) and each WMS or WMTS layer with a legend, ticked when listed. Names + // gone from the map drop out of the list as it's written back. if let ElementKind::Legend { frame, exclude, .. } = &e.kind { let map = layout.element(*frame).and_then(|f| match &f.kind { ElementKind::MapFrame { map, .. } => app.session.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)), diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 4124a0e87e..4e5f0f4943 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -56,9 +56,11 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu alike, such as a context layer filling the frame, isn't worth a warning); two that overlap (a frame too small) are said too. The top visible raster on a colour scale (Stretch, a tinted hillshade) gets a colorbar - beneath the legend; RGB and untinted hillshade do not. A raster drawn by classes (Colormap, - Unique Values, Classify) has its classes in the legend's rows instead, so a map whose only - theme is a land cover gets a filled legend and no colorbar. `"colorbar": "none"` leaves it out, and the legend's + beneath the legend; RGB and untinted hillshade do not, so an RGB composite over a DEM leaves + it to the DEM. A raster drawn by classes (Colormap, Unique Values, Classify) has its classes + in the legend's rows instead, so a map whose only theme is a land cover gets a filled legend + and no colorbar; a colour table over more values than a legend lists (over 256, or not whole) + has neither, and a warning says so. `"colorbar": "none"` leaves it out, and the legend's box is sized for the legend alone: hiding the colorbar afterwards would leave its room empty in the box. The legend takes the fewest columns, up to three, that fit the largest rectangle the map leaves free; when none fits, a long one is laid in more @@ -195,9 +197,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu - **Rasters drawn by classes** (Colormap, Unique Values, Classify) are listed under their name with the rows the Layers pane shows for them: a swatch of each class's colour and its label, the class name in the file when it has one, else the value or the range. The legend lists the - classes the raster holds (the values in its statistics, without those its mask hides; for - Classify on a raster with too many values to list, the classes from its lowest value to its - highest), and with **All classes** every class of a Unique Values or Classify renderer. A + classes the raster holds (the values in its statistics, without those its mask hides). On a + raster with too many values to list (over 256, or not whole) it lists every Unique Values + class, and for Classify the classes from its lowest value to its highest. With **All + classes** it lists every class of a Unique Values or Classify renderer. A colour table lists the values the raster holds either way: its 256 entries have no meaningful "all". Rasters on a ramp (Stretch, a tinted hillshade) and RGB composites are left out: a colorbar keys the ramp. **Exclude** leaves a classified raster out by its name. From 1f48e1058c22826cc5a4456275cefd3338ead735 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 11 Nov 2026 01:19:40 -0300 Subject: [PATCH 03/16] fix(layout): rasters a legend can't key are said once, with a count, by every legend made (#1679) The warning for colour tables over more values than a legend lists was one per layer and only from layout.publication. It is now one notice for all of them, with their count and names (unlisted_colour_tables), and a legend added by layout.addElement, or given its exclude by layout.update, says it too, for the rasters it doesn't leave out. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 49 +++++++++++++++++++++++++++------ crates/engine/src/tests.rs | 32 ++++++++++++++++++--- 2 files changed, 69 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 2a5efbdfe2..fb522196d2 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1845,14 +1845,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { .map(|(l, _)| l.name.clone()); // A colour table whose values can't be known (too many to list) gives the legend no class, and // the sheet no key for it: said rather than left blank. - for l in s.map().layers.iter().filter(|l| s.map().shows(l)) { - if l.raster.as_ref().is_some_and(rustgis_map::RasterLayer::classes_unknown) { - warnings.push(format!( - "'{}' draws its colour table over more values than a legend can list (over 256, or not whole numbers): the legend has no key for it", - l.name - )); - } - } + warnings.extend(unlisted_colour_tables(s.map(), &[])); let (bar_w, bar_h) = (if sheet { 50.0 * k } else { 40.0 }, COLORBAR_MM); let bar_part = if bar.is_some() { bar_h + if ch > 0.0 { 2.0 } else { 0.0 } } else { 0.0 }; let (content_w, content_h) = (if bar.is_some() { cw.max(bar_w) } else { cw }, ch + bar_part); @@ -2685,6 +2678,38 @@ fn legend_fit_warnings(columns: usize, (w, h): (f64, f64), (room_w, room_h): (f6 said } +/// The one warning for the rasters `map` shows by a colour table over more values than a legend +/// can list (over 256, or not whole numbers), which give it no class and no key (#1679): how many +/// and their names, those `exclude` leaves out aside. `None` when there are none. +fn unlisted_colour_tables(map: &Map, exclude: &[String]) -> Option { + let names: Vec<&str> = map + .layers + .iter() + .filter(|l| map.shows(l) && !exclude.iter().any(|n| n.eq_ignore_ascii_case(&l.name))) + .filter(|l| l.raster.as_ref().is_some_and(rustgis_map::RasterLayer::classes_unknown)) + .map(|l| l.name.as_str()) + .collect(); + (!names.is_empty()).then(|| { + format!( + "{} raster(s) drawn by a colour table over more values than a legend can list (over 256, or not whole numbers) have no key in the legend: {}", + names.len(), + names.join(", ") + ) + }) +} + +/// Says, once, which rasters the legend `id` of the layout `li` can't key ([`unlisted_colour_tables`]), +/// as `layout.publication` does for its own: for a legend added, or told what it leaves out. +fn say_unlisted_colour_tables(s: &mut Session, li: usize, id: u32) { + let Some(l) = s.project.layouts.get(li) else { return }; + let Some(ElementKind::Legend { frame, exclude, .. }) = l.element(id).map(|e| &e.kind) else { return }; + let Some(ElementKind::MapFrame { map, .. }) = l.element(*frame).map(|f| &f.kind) else { return }; + let said = s.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)).and_then(|m| unlisted_colour_tables(m, exclude)); + if let Some(said) = said { + s.warn(said); + } +} + /// Says what a legend loses in its box, as `layout.publication` does for its own, or that it can't /// tell. fn say_legend_fit(s: &mut Session, li: usize, id: u32) { @@ -2979,6 +3004,9 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { if p.get("columns").is_some_and(|v| !v.is_null()) || labelled { say_legend_fit(s, i, id); } + if kind == "legend" { + say_unlisted_colour_tables(s, i, id); + } let mut out = json!({"element": id}); if let Some(w) = warning { out["warning"] = json!(w); @@ -3806,9 +3834,14 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { || p.get("labels").is_some_and(|v| !v.is_null()); // Labels given are told in one column too: a label is text chosen for the box. let labelled = matches!(&e.kind, ElementKind::Legend { .. }) && p.get("labels").is_some_and(|v| !v.is_null()); + // Told what it leaves out, it says again which rasters it can't key. + let excluding = matches!(&e.kind, ElementKind::Legend { .. }) && p.get("exclude").is_some_and(|v| !v.is_null()); if new_columns.is_some() || (in_columns && refitted) || labelled { say_legend_fit(s, li, id); } + if excluding { + say_unlisted_colour_tables(s, li, id); + } if let Some(text) = p.get("grid").and_then(|grid| grid.get("crs")).and_then(Value::as_str) { super::say_crs_note(s, text); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 046a90c2e8..4c9b514e9b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7821,17 +7821,41 @@ fn a_publication_keys_the_raster_under_an_rgb_and_says_an_unlisted_colour_table( let z: Vec = (0..400).map(|i| (i % 300) as f32).collect(); let many = Raster::new("many", 20, 20, vec![z], gt, Crs::LonLat, None, ColorHint::Palette(palette), "UInt16").unwrap(); assert!(many.bands[0].stats.categories.is_none()); - let mut rl = rustgis_map::RasterLayer::from_path(many, "many.tif"); - rl.style.renderer = rustgis_map::RasterRenderer::Colormap; - crate::cmd::raster::add_raster(&mut s, "Classes", rl).unwrap(); + for name in ["Classes", "Mais classes"] { + let mut rl = rustgis_map::RasterLayer::from_path(many.clone(), "many.tif"); + rl.style.renderer = rustgis_map::RasterRenderer::Colormap; + crate::cmd::raster::add_raster(&mut s, name, rl).unwrap(); + } + let said = "2 raster(s) drawn by a colour table over more values than a legend can list (over 256, or not whole numbers) have no key in the legend: Mais classes, Classes"; let r = s.run("layout.publication", &p).unwrap(); assert_eq!(bar_of(&s), None, "{r}"); - assert!(r["warnings"].to_string().contains("'Classes' draws its colour table over more values than a legend can list"), "{r}"); + let warnings: Vec = serde_json::from_value(r["warnings"].clone()).unwrap(); + assert_eq!( + warnings.iter().filter(|w| w.contains("over more values than a legend")).collect::>(), + [said], + "one, with the count: {r}" + ); + // A legend added says it too, once; told to leave one out, it names the other. + let mark = s.notice_mark(); + let id = s.run("layout.addElement", &json!({"kind": "legend"})).unwrap()["element"].as_u64().unwrap(); + let notices = |s: &Session, mark| -> Vec { + s.notices_since(mark).iter().filter(|n| n.text.contains("over more values than a legend")).map(|n| n.text.clone()).collect() + }; + assert_eq!(notices(&s, mark), [said]); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "exclude": ["classes"]})).unwrap(); + assert_eq!(notices(&s, mark), [said.replace("2 raster(s)", "1 raster(s)").replace(": Mais classes, Classes", ": Mais classes")]); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "exclude": ["Classes", "Mais classes"]})).unwrap(); + assert!(notices(&s, mark).is_empty(), "both left out: nothing to say"); // Its classes known: nothing said. let mut s = Session::new(Project::default()); add_land_cover(&mut s, "Uso do solo", &[(3, "Floresta"), (15, "Pastagem")]); let r = s.run("layout.publication", &p).unwrap(); assert!(!r["warnings"].to_string().contains("more values than a legend"), "{r}"); + let mark = s.notice_mark(); + s.run("layout.addElement", &json!({"kind": "legend"})).unwrap(); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("more values than a legend"))); } /// A land cover with more classes than its legend's box holds: the publication says it leaves the From 6c463ad5078209f19efbbba2b727ba37a9ac273c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 11 Nov 2026 01:41:54 -0300 Subject: [PATCH 04/16] fix(layout): a colorbar with no layer skips classed rasters; classes from an overview are said (#1679) A colorbar added with no layer took the top visible raster whatever its renderer, so over a land cover it drew the class codes. colorbar_layer's default now takes the topmost visible raster with a colour scale that isn't drawn by classes, the rule layout.publication used, which now calls it. A Colormap (or Unique Values, Classify) raster read through an overview, as a COG read in place is, has the overview's statistics, so a rare class the map draws at full resolution can be missing from the legend. layout.publication and a legend added, or given its exclude or allClasses, now say so, once for all such rasters with their count and names (raster_key_notices). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 83 +++++++++++++++++++-------------- crates/engine/src/tests.rs | 35 +++++++++++++- crates/map/src/layout.rs | 11 ++++- crates/map/src/raster.rs | 18 +++++++ crates/render/src/layout.rs | 15 ++++-- docs/user-guide/layouts.md | 8 +++- 6 files changed, 125 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index fb522196d2..3dfae5835f 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -93,7 +93,7 @@ pub fn commands() -> Vec { r#"{"layout"?, "shape"?: "rectangle"|"circle"|"ellipse"|"polygon"|"lasso", "points"?: [[u, v], …] (polygon/lasso, 0..1 across the frame), "map"?: name, "x"?, "y"?, "w"?, "h"?: mm}"#, ), C::new("layout.addElement", "Add Element", "Publish › Map Surrounds", add_element).inputs(element_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( - r##"{"layout"?, "kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid", "frame"?: element id (default: the first map frame), "of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "text"?, "size"?, "color"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; scaleBar; refused for other kinds), "bold"?: bool (text), "italic"?: bool, "align"?: "left"|"center"|"right", "letterSpacing"?: points, -5 to 50 (text, dynamicText), "font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "title"?: legend title (default "Legend"), "allClasses"?: bool (legend: every class, not only those the frame draws), "hideOther"?: bool (legend: leave out ), "exclude"?: [layer names] (legend: layers it leaves out though the map draws them), "columns"?: 1..3 (legend: the columns its rows are laid in; default 1), "orientation"?: "horizontal"|"vertical" (colorbar), "ticks"?: 2..21 (colorbar: labelled values, ends included), "tickSide"?: "below"|"above"|"right"|"left" (colorbar), "reverse"?: bool (colorbar: high values first), "fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white; refused for other kinds), "width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid), "radius"?: mm, 0 to 50 (rectangle: rounded corners), "dir"?: "horizontal"|"vertical"|"falling"|"rising" (line), "head"?: "none"|"end"|"start"|"both" (line; default "end" for an arrow), "angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "length"?: mm (line, arrow), "image"?: base64, "path"?: picture file, "layer"?: (table, chart; colorbar: a raster layer, default the top visible one), "field"?, "label"?, "rows"?, "step"?: degrees, or a measured grid's units (metres) (0 picks one), "type"?: "graticule" (latitudes and longitudes, default) | "measured" (eastings and northings in a projected system, as ArcGIS Pro's measured grid), "crs"?: a measured grid's coordinate system: EPSG:25832, WKT or a PROJ string ("" or none: the map's when projected, else the UTM zone at the frame's centre), "short"?: bool (a measured grid's labels as their kilometres' last two digits, 43 for 543000), "labels"?: bool (grid) | {"": "