From d68adc5d3abaad5adcbfc195185453d66bb80e08 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 08:21:33 -0300 Subject: [PATCH 1/5] =?UTF-8?q?feat(layout):=20layout.update=20changes=20a?= =?UTF-8?q?=20profile,=20which=20follows=20its=20names;=20Publish=20?= =?UTF-8?q?=E2=80=BA=20Map=20Surrounds=20=E2=80=BA=20Profile=20(#2863=20pa?= =?UTF-8?q?rt=202f)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit layout.update changes a profile's options as layout.addElement takes them, null giving back no fill, its samples' own min and max, or the default ink. An x, y, w or h given (the layout view's drag and resize) sets its gap and thickness, along its frame it keeping the frame's; one that isn't a number is refused. A profile follows its section line and its layer when they are renamed, and keeps its layer's name when that layer is removed, which is said. A saved layout.update with a key only a profile reads requires layout-profile. Publish › Map Surrounds › Profile adds one, and the user guide describes it. The render crate's `testing` feature gives the tests of the crates over it one grid builder, which replaces five hand-built grids. Co-Authored-By: Claude Opus 5.5 --- crates/engine/Cargo.toml | 2 + crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/layer.rs | 10 ++- crates/engine/src/cmd/layout.rs | 13 +++- crates/engine/src/cmd/layout/inputs.rs | 7 ++ crates/engine/src/cmd/layout/profile.rs | 90 +++++++++++++++++++++- crates/engine/src/cmd/layout/update.rs | 19 +++-- crates/engine/src/project_capabilities.rs | 15 +++- crates/engine/src/tests/layout_profiles.rs | 66 +++++++++++----- crates/map/src/layout/elements.rs | 4 +- crates/map/src/layout/profile.rs | 21 ++++- crates/map/src/layout/tests.rs | 19 ++++- crates/render/Cargo.toml | 4 + crates/render/src/layout/profile_tests.rs | 49 +++++------- crates/render/src/lib.rs | 3 + crates/render/src/testing.rs | 23 ++++++ crates/ui-egui/src/icons.rs | 18 +++++ crates/ui-egui/src/ribbon.rs | 6 ++ docs/maintaining.md | 6 +- docs/user-guide/layouts.md | 25 ++++++ 20 files changed, 324 insertions(+), 78 deletions(-) create mode 100644 crates/render/src/testing.rs diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 8daca54a84..e3b615c617 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -51,6 +51,8 @@ miniz_oxide = { workspace = true } # Writing sample GeoPackages. rusqlite = { workspace = true } rustgis-plugins = { workspace = true, features = ["testing"] } +# Test rasters to draw layouts from. +rustgis-render = { workspace = true, features = ["testing"] } # Cancelling a command at each of its checks in turn. rustgis-analysis = { workspace = true, features = ["testing"] } tiny-skia = { workspace = true } diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 74d1bc35bb..f8184f3977 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -304,7 +304,7 @@ layout.save layout? path layout.series layout? layer nameField? frame? margin? off? layout.seriesPage layout? page layout.seriesRefresh layout? -layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? layerOrder? labels? classLabels? columns? textSize? showLayerNames? showCounts? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? background? +layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? layerOrder? labels? classLabels? columns? textSize? showLayerNames? showCounts? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? barOutline? hideLabels? rows? background? locator.find locator? text limit? zoom? map.activate name map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a670435610..49eaab5827 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7564,6 +7564,7 @@ fn references_follow_layer(s: &mut Session, old: &str, new: &str) { replace(layer) } ElementKind::Colorbar { frame, layer: Some(layer), .. } if frames.contains(frame) => replace(layer), + ElementKind::Profile(p) if frames.contains(&p.frame) => replace(&mut p.layer), ElementKind::Text { text, .. } if texts_read_this_map => { match renamed_statistics(text, rustgis_map::layout::MAX_TEXT_CHARS, braces, &mut replace) { Renamed::To(renamed) => *text = renamed, @@ -7725,10 +7726,10 @@ fn removed_notice(keys: [&'static str; 2], count: usize, named: &[&str]) -> Opti Some(crate::notice_text::NoticeText::format(key, [("count", count.to_string().into()), ("names", names.into())])) } -/// After layers called `names` are removed: a table's, chart's or colorbar's layer, and a text's -/// layer statistics (#2853), keep the name, so a layer of that name brings them back, and are drawn -/// without it meanwhile: how many elements, said once. Which elements read the active map is as for -/// a rename (`references_follow_layer`). +/// After layers called `names` are removed: a table's, chart's, colorbar's or profile's layer, and a +/// text's layer statistics (#2853), keep the name, so a layer of that name brings them back, and are +/// drawn without it meanwhile: how many elements, said once. Which elements read the active map is +/// as for a rename (`references_follow_layer`). fn layouts_follow_removal(s: &mut Session, names: &[String]) { use rustgis_map::layout::ElementKind; @@ -7746,6 +7747,7 @@ fn layouts_follow_removal(s: &mut Session, names: &[String]) { vec![layer] } ElementKind::Colorbar { frame, layer: Some(layer), .. } if frames.contains(frame) => vec![layer], + ElementKind::Profile(p) if frames.contains(&p.frame) => vec![&p.layer], ElementKind::Text { text, .. } if texts_read_this_map => { rustgis_map::layout::stat_tokens(text).iter().map(|t| t.layer).collect() } diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index d74c40bec5..5707701ec3 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -302,7 +302,7 @@ pub fn commands() -> Vec { r##""locked"?: bool (a locked element takes no other change until unlocked; "locked": false unlocks it and may come with changes), "##, r##""text"? (a text's words; {count:Layer}, {sum:Layer:field}, {mean:Layer:field}, {min:Layer:field} and {max:Layer:field} show the layer's figure, as {scale} shows the scale: of the first map frame's map, over the features the layer's definition query keeps, with the layout's decimal mark; one with no figure shows as written and says why), "##, r##""size"?, "##, - r##""color"? (text, line, rectangle, ellipse: its outline; scaleBar: its lines, dark divisions and labels; legend, colorbar, table, chart: its ink, as in layout.addElement, null giving it the default again; refused for other elements), "##, + r##""color"? (text, line, rectangle, ellipse: its outline; scaleBar: its lines, dark divisions and labels; legend, colorbar, table, chart, profile: its ink, as in layout.addElement, null giving it the default again; refused for other elements), "##, r##""bold"?, "##, r##""italic"?, "##, r##""align"?, "##, @@ -372,7 +372,16 @@ pub fn commands() -> Vec { r##""classes"?: bool, "##, r##""labelAlign"?: "left"|"right", "##, r##""mirror"?: bool, "##, - r##""max"?: a number above 0|"auto"|null (null or "auto" giving it its bars' own again), "##, + r##""max"?: a number above 0|"auto"|null (null or "auto" giving it its bars' own again; profile: a number, or null for its samples' own), "##, + r##""band"?, "##, + r##""side"?, "##, + r##""gap"?, "##, + r##""thickness"?, "##, + r##""unit"?, "##, + r##""lineColor"?, "##, + r##""lineWidth"?, "##, + r##""min"?, "##, + r##""guides"? (profile, as in layout.addElement: "section" its line's name, "layer" its raster, "fill", "min" and "max" null for none or its samples' own, "color" its ink; its x, y, w and h set its gap and thickness, along its frame it keeping the frame's), "##, r##""barOutline"?: {"color"?, "width"?: points, 0 to 5, a wider one held to 5, the keys not given keeping the outline's}|null (null or a width of 0 for none), "##, r##""hideLabels"?: bool (chart, as in layout.addElement: null leaves each other one as it is; refused for other elements unless null), "##, r##""rows"?, "##, diff --git a/crates/engine/src/cmd/layout/inputs.rs b/crates/engine/src/cmd/layout/inputs.rs index 443305f5c1..5bc27cb3fc 100644 --- a/crates/engine/src/cmd/layout/inputs.rs +++ b/crates/engine/src/cmd/layout/inputs.rs @@ -235,6 +235,12 @@ pub(in crate::cmd::layout) fn update_inputs(input: &crate::cmd::InputContext<'_> inputs.extend(crate::cmd::Inputs::named(frame_map(input, l, *frame)?, [name.as_str()])?); } } + // A profile's new raster (#2863 part 2). + Some(ElementKind::Profile(profile)) if ps(p, "layer").is_some_and(|n| !n.trim().is_empty()) => { + let map = frame_map(input, l, profile.frame)?; + let name = added_profile_layer(map, p)?; + inputs.extend(crate::cmd::Inputs::named(map, [name.as_str()])?); + } Some(ElementKind::Legend { frame, .. }) => { let (names, labels) = (legend_exclude(input, l, *frame, p)?, legend_labels(input, l, *frame, p)?); let classes = legend_class_labels(input, l, *frame, p)?; @@ -302,6 +308,7 @@ pub(in crate::cmd::layout) fn element_selectors(kind: &ElementKind) -> Option json!({"frame":frame,"layer":layer}), + ElementKind::Profile(p) => json!({"frame":p.frame,"layer":p.layer,"section":p.section}), ElementKind::NorthArrow { frame, .. } | ElementKind::ScaleBar { frame, .. } => json!({"frame":frame}), _ => return None, }) diff --git a/crates/engine/src/cmd/layout/profile.rs b/crates/engine/src/cmd/layout/profile.rs index afbc7e3a61..ae36659a6f 100644 --- a/crates/engine/src/cmd/layout/profile.rs +++ b/crates/engine/src/cmd/layout/profile.rs @@ -7,7 +7,7 @@ use rustgis_map::layout::{ use super::*; -/// The keys of a profile's own, which `layout.addElement` reads. +/// The keys of a profile's own, which `layout.addElement` and `layout.update` read. const PROFILE_KEYS: &[&str] = &[ "section", "layer", @@ -28,6 +28,18 @@ const PROFILE_KEYS: &[&str] = &[ ]; /// What `layout.addElement` reads for a profile, besides [`PROFILE_KEYS`]. const ADD_PROFILE_KEYS: &[&str] = &["layout", "kind", "frame", "background"]; +/// What `layout.update` reads for a profile, besides [`PROFILE_KEYS`]: `x`, `y`, `w` and `h` as its +/// gap and thickness ([`Profile::take_rect`]). +const UPDATE_PROFILE_KEYS: &[&str] = &["layout", "element", "name", "visible", "locked", "background", "x", "y", "w", "h"]; + +/// A profile's keys that null gives back their default: no fill, the samples' own ends, the dark +/// grey ink. +const PROFILE_NULL_KEYS: &[&str] = &["fill", "min", "max", "color", "background"]; + +/// Whether element `id` of layout `li` is a profile. +pub(in crate::cmd::layout) fn is_profile(s: &Session, li: usize, id: u32) -> bool { + s.project.layouts.get(li).and_then(|l| l.element(id)).is_some_and(|e| e.kind.is_profile()) +} /// A frame's map, its section lines and its box (x, y, w, h in mm). fn frame_parts<'a>(s: &'a Session, l: &'a Layout, frame: u32) -> Result<(&'a Map, &'a [Section], (f64, f64, f64, f64)), String> { @@ -219,6 +231,69 @@ pub(in crate::cmd::layout) fn add_profile(s: &mut Session, p: &Value) -> CmdResu Ok(json!({"element": id})) } +/// `layout.update` for a profile: its own options, its name, visibility, lock and background, and +/// `x`, `y`, `w` and `h` read as its gap and thickness, along its frame it keeping the frame's. +pub(in crate::cmd::layout) fn update_profile(s: &mut Session, p: &Value, li: usize, id: u32) -> CmdResult { + let keys: Vec<&str> = UPDATE_PROFILE_KEYS.iter().chain(PROFILE_KEYS).copied().collect(); + if let Some(k) = p.as_object().and_then(|o| o.keys().find(|k| !keys.contains(&k.as_str()) && gives(p, k))) { + let shown: String = k.chars().take(40).map(|c| if c.is_control() { '?' } else { c }).collect(); + return Err(format!("layout.update: a profile takes no \"{shown}\" (it reads {})", keys.join(", "))); + } + let l = s.project.layouts.get(li).ok_or("no layout")?; + let e = l.element(id).ok_or_else(|| format!("no element {id}"))?; + let ElementKind::Profile(current) = &e.kind else { return Err(format!("element {id} isn't a profile")) }; + let changes = p.as_object().is_some_and(|o| { + o.iter().any(|(k, v)| { + (!v.is_null() || PROFILE_NULL_KEYS.contains(&k.as_str())) && !matches!(k.as_str(), "layout" | "element" | "locked") + }) + }); + if changes && b(p, "locked") != Some(false) { + unlocked(l, id)?; + } + let new_name = crate::cmd::name_given(p, "an element's name", 200)?; + let new_background = match element_background(p, e.background)? { + BackgroundParam::Set(b) => Some(Some(b)), + BackgroundParam::Remove => Some(None), + BackgroundParam::Absent => None, + }; + let boxed = ["x", "y", "w", "h"].iter().any(|k| gives(p, k)); + if boxed && (gives(p, "gap") || gives(p, "thickness")) { + return Err("give a profile a gap and thickness, or x, y, w and h, not both".into()); + } + let (mut new, mut held) = profile_params(s, l, p, current.clone())?; + let (_, _, frame_box) = frame_parts(s, l, new.frame)?; + if boxed { + let at = |k: &str, now: f64| given_num(p, k, "a number of mm").map(|v| v.unwrap_or(now)); + let rect = (at("x", e.x)?, at("y", e.y)?, at("w", e.w)?, at("h", e.h)?); + if new.take_rect(frame_box, rect) { + let ((g0, g1), (t0, t1)) = (PROFILE_GAPS, PROFILE_THICKNESSES); + held.push(format!("its gap held to {} ({g0} to {g1} mm) and thickness to {} ({t0} to {t1} mm)", new.gap, new.thickness)); + } + } + let reread = ["section", "layer", "band", "side"].iter().any(|k| gives(p, k)); + let l = s.project.layouts.get_mut(li).ok_or("no layout")?; + let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?; + e.kind = ElementKind::Profile(new); + if let Some(n) = new_name { + e.name = n; + } + if let Some(v) = b(p, "visible") { + e.visible = v; + } + if let Some(v) = b(p, "locked") { + e.locked = v; + } + if let Some(v) = new_background { + e.background = v; + } + l.fit_profiles(); + say_held(s, "Element Properties", held); + if reread { + say_profile_drawn(s, li, id); + } + Ok(Value::Null) +} + /// Says that profile `id` of layout `li` isn't drawn, and why, or that it is read at fewer samples /// than its raster's cells along its section line, when it is. pub(in crate::cmd::layout) fn say_profile_drawn(s: &mut Session, li: usize, id: u32) { @@ -230,6 +305,19 @@ pub(in crate::cmd::layout) fn say_profile_drawn(s: &mut Session, li: usize, id: } } +/// The profiles of section line `old` of frame `frame` named `new` instead, after the line was +/// renamed: they follow it. +pub(in crate::cmd::layout) fn profiles_follow_section(l: &mut Layout, frame: u32, old: &str, new: &str) { + for e in &mut l.elements { + if let ElementKind::Profile(p) = &mut e.kind + && p.frame == frame + && p.section.eq_ignore_ascii_case(old) + { + p.section = new.to_string(); + } + } +} + /// The raster layer `layout.addElement` reads for a profile, for its inputs: the one given, else the /// top one its frame's map shows that it can read. pub(in crate::cmd::layout) fn added_profile_layer(map: &Map, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 3ebeb4f864..6f3e4d778a 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -147,6 +147,12 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result CmdResult { let id = element_id(p)?; + // A profile reads its own keys (#2863 part 2), several of them other kinds' too. + if let Ok(li) = index(s, p) + && is_profile(s, li, id) + { + return update_profile(s, p, li, id); + } // The first frame's map as it is, to say what the texts lose only when it changes (#2853). let map_before = index(s, p).ok().and_then(|li| first_frame_map(s, li)); // Checked before anything changes, so a bad value leaves the element as it was. @@ -852,17 +858,14 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { if let Some((_, Some(name))) = &new_sections { say_section_not_drawn(s, li, id, name); } - // A frame moved or resized takes its profiles with it (#2863); a profile's own box is its frame's. - let profile = s.project.layouts.get(li).and_then(|l| l.element(id)).filter(|e| e.kind.is_profile()).map(|e| e.name.clone()); + // A frame moved or resized takes its profiles with it, and a section line renamed its + // profiles (#2863). if let Some(l) = s.project.layouts.get_mut(li) { + if let (Some((_, Some(new))), Some(old)) = (&new_sections, p.get("section").and_then(|v| ps(v, "name"))) { + profiles_follow_section(l, id, old.trim(), new); + } l.fit_profiles(); } - if let Some(name) = profile.filter(|_| given(&["x", "y", "w", "h"])) { - s.notify( - format!("Element Properties: the profile '{name}' keeps beside its frame, whose side is its box: x, y, w and h are not used"), - false, - ); - } say_held(s, "Element Properties", held); if let Some(w) = font_told { return Ok(json!({"warning": w})); diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index ffe90780cb..2f862514db 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -559,12 +559,20 @@ fn command_uses_section(id: &str, params: &Value) -> bool { } } -/// A layout command that adds a profile beside a map frame or brings one in (#2863 part 2): an -/// older reader refuses the kind `profile` of `layout.addElement` and the kind `Profile` of a -/// layout file. +/// The keys of `layout.update` only a profile reads (#2863 part 2), besides a `section` given as a +/// name, which a map frame takes as an object. +const PROFILE_ONLY_KEYS: &[&str] = &["band", "side", "gap", "thickness", "unit", "lineColor", "lineWidth", "guides", "min"]; + +/// A layout command that adds, changes or brings in a profile beside a map frame (#2863 part 2): an +/// older reader refuses the kind `profile` of `layout.addElement`, the keys of `layout.update` only +/// a profile reads, and the kind `Profile` of a layout file. fn command_uses_profile(id: &str, params: &Value) -> bool { match id { "layout.addElement" => params.get("kind").and_then(Value::as_str).is_some_and(|k| k.trim().eq_ignore_ascii_case("profile")), + "layout.update" => { + PROFILE_ONLY_KEYS.iter().any(|k| params.get(*k).is_some_and(|v| !v.is_null())) + || params.get("section").is_some_and(Value::is_string) + } // A layout file, read as `layout.import` reads it, which `report.existingTemplate` also does. "layout.import" | "report.existingTemplate" => imported_layout_uses(params, &["\"Profile\""], |e| e.kind.is_profile()), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_profile)), @@ -1755,6 +1763,7 @@ mod tests { (&["layout-section"], "layout.update", json!({"element": 1, "section": {"name": "A", "y": 0}})), (&["layout-profile"], "layout.import", json!({"text": profile_layout})), (&["layout-profile"], "layout.addElement", json!({"kind": "profile"})), + (&["layout-profile"], "layout.update", json!({"element": 2, "thickness": 20})), (&["layout-text-size"], "layout.update", json!({"element": 1, "textSize": 12})), (&["layout-legend-fit"], "layout.update", json!({"element": 1, "fit": "adjustSize"})), (&["layout-legend-class-labels"], "layout.update", json!({"element": 1, "classLabels": {"a": {"x": "X"}}})), diff --git a/crates/engine/src/tests/layout_profiles.rs b/crates/engine/src/tests/layout_profiles.rs index f58b9d1379..7d3780add5 100644 --- a/crates/engine/src/tests/layout_profiles.rs +++ b/crates/engine/src/tests/layout_profiles.rs @@ -2,10 +2,11 @@ //! profile agrees with `profile.create`. use crate::{Session, sample}; -use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; +use rustgis_data::raster::Crs; use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as Data}; use rustgis_geom::Coord; use rustgis_map::layout::{ElementKind, Profile, ProfileSide}; +use rustgis_render::testing::{grid, mantiqueira}; use serde_json::{Value, json}; /// A profile put beside the first frame of the session's first layout, and its id. @@ -21,10 +22,7 @@ fn put_profile(s: &mut Session, frame: u32, side: ProfileSide) -> u32 { /// metres of latitude over it, and the frame's id. fn with_dem() -> (Session, u32) { let mut s = Session::new(sample::world_project()); - let (n, cell) = (400usize, 0.05); - let data = (0..n * n).map(|i| ((60.0 - ((i / n) as f64 + 0.5) * cell) * 100.0) as f32).collect(); - let gt = GeoTransform { origin_x: 0.0, origin_y: 60.0, pixel_width: cell, pixel_height: -cell }; - let r = Raster::new("dem", n as u32, n as u32, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let r = grid(Crs::LonLat, (0.0, 60.0), 0.05, (400, 400), |_, lat| lat * 100.0); s.map_mut().add_raster("DEM", rustgis_map::RasterLayer::from_path(r, "dem.tif")); s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); let frame = s.project.layouts[0].first_frame().unwrap(); @@ -47,23 +45,24 @@ fn a_profiles_copy_keeps_beside_its_frame_and_says_so() { assert!(said.iter().any(|t| t.contains("beside its frame") && t.contains("offset")), "{said:?}"); } -/// A box given to a profile is its frame's side again, and said; the frame's own move is not. +/// A box given to a profile sets its gap and thickness, along its frame it keeping the frame's; the +/// frame's own move takes it along and says nothing. #[test] -fn a_box_given_to_a_profile_is_said_not_kept() { +fn a_box_given_to_a_profile_sets_its_gap_and_thickness() { let mut s = Session::new(sample::world_project()); s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); let frame = s.project.layouts[0].first_frame().unwrap(); let id = put_profile(&mut s, frame, ProfileSide::Bottom); let box_of = |s: &Session| s.project.layouts[0].element(id).map(|e| (e.x, e.y, e.w, e.h)); - let at = box_of(&s); - let mark = s.notice_mark(); + let (x, y, w, _) = box_of(&s).unwrap(); s.run("layout.update", &json!({"element": id, "x": 5, "h": 50})).unwrap(); - assert_eq!(box_of(&s), at); - let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert!(said.iter().any(|t| t.contains("Profile") && t.contains("beside its frame")), "{said:?}"); + assert_eq!(box_of(&s), Some((x, y, w, 50.0))); + let err = s.run("layout.update", &json!({"element": id, "y": "far"})).unwrap_err(); + assert!(err.contains("y is a number of mm"), "{err}"); let mark = s.notice_mark(); s.run("layout.update", &json!({"element": frame, "x": 20})).unwrap(); assert!(s.notices_since(mark).is_empty(), "the frame takes its profile along"); + assert_eq!(box_of(&s).map(|b| b.0), Some(20.0)); } fn said(s: &Session, mark: u64) -> Vec { @@ -140,6 +139,40 @@ fn a_profile_is_added_follows_its_frame_and_is_undone() { assert!(notes.len() == 1 && notes[0].contains("1 profile(s) not drawn") && notes[0].contains("tilted"), "{notes:?}"); } +/// A profile is changed with `layout.update`: dragged along its frame and away from it, only its +/// gap follows, and resized, its thickness; a value past its limits is held there and said; it +/// follows its section line and its layer when they are renamed. +#[test] +fn a_profile_is_changed_and_follows_its_names() { + let (mut s, frame) = with_dem(); + s.run("layout.addElement", &json!({"kind": "section", "at": [10, 50]})).unwrap(); + let id = s.run("layout.addElement", &json!({"kind": "profile"})).unwrap()["element"].as_u64().unwrap(); + let (_, at) = profile(&s, id); + s.run("layout.update", &json!({"element": id, "x": 60, "y": at[1] + 4.0, "h": 40})).unwrap(); + let (p, moved) = profile(&s, id); + assert_eq!((moved[0], p.gap, p.thickness), (at[0], 7.0, 40.0)); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "thickness": 1000, "fill": null, "lineColor": "#1F5C84", "min": 0})).unwrap(); + assert!(said(&s, mark).iter().any(|n| n.contains("thickness 1000 held to 300")), "{:?}", said(&s, mark)); + let (p, _) = profile(&s, id); + assert_eq!((p.thickness, p.fill, p.line_color.hex(), p.min), (300.0, None, "#1F5C84".to_string(), Some(0.0))); + s.run("layout.update", &json!({"element": id, "min": null})).unwrap(); + assert_eq!(profile(&s, id).0.min, None, "null gives back the samples' own"); + for (bad, says) in [ + (json!({"element": id, "gap": 2, "y": 9}), "not both"), + (json!({"element": id, "rows": 3}), "a profile takes no \"rows\""), + (json!({"element": id, "side": "right"}), "goes bottom or top of its frame"), + ] { + let err = s.run("layout.update", &bad).unwrap_err(); + assert!(err.contains(says), "{bad}: {err}"); + } + // Its section line and its layer renamed: it follows them. + s.run("layout.update", &json!({"element": frame, "section": {"name": "a", "newName": "Serra"}})).unwrap(); + s.run("layer.rename", &json!({"layer": "DEM", "name": "Relevo"})).unwrap(); + let (p, _) = profile(&s, id); + assert_eq!((p.section.as_str(), p.layer.as_str()), ("Serra", "Relevo")); +} + /// A profile its page can't draw says so when the page is drawn: beside a tilted frame, one notice /// naming it and why, from a PNG, a PDF and the picture `view_map` draws alike, and from a report /// with its layout named. @@ -195,16 +228,9 @@ fn a_profile_not_drawn_is_said() { fn the_mantiqueira_profile_agrees_with_profile_create() { let mut s = Session::new(sample::world_project()); s.run("map.projection", &json!({"type": "EPSG:31983"})).unwrap(); - let crs = Crs::from_epsg(31983).unwrap(); - let to = crs.transformer().unwrap(); - let mid = to.from_lonlat(Coord::new(-44.715, -22.412)).unwrap(); - let (cols, rows, cell) = (1600usize, 1000usize, 30.0); - let (x0, y0) = (((mid.x - 24_000.0) / cell).round() * cell, ((mid.y + 15_000.0) / cell).round() * cell); // Ridges and valleys a few kilometres across, some 2,000 m of relief, as the Mantiqueira's. let z = |e: f64, n: f64| 1500.0 + 600.0 * (e / 2_300.0).sin() * (n / 1_700.0).cos() + 300.0 * ((e + n) / 900.0).sin(); - let data = (0..rows * cols).map(|i| z(x0 + ((i % cols) as f64 + 0.5) * cell, y0 - ((i / cols) as f64 + 0.5) * cell) as f32).collect(); - let gt = GeoTransform { origin_x: x0, origin_y: y0, pixel_width: cell, pixel_height: -cell }; - let r = Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").unwrap(); + let r = mantiqueira(z); s.map_mut().add_raster("DEM", rustgis_map::RasterLayer::from_path(r, "dem.tif")); s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "blank"})).unwrap(); s.run("layout.addFrame", &json!({})).unwrap(); diff --git a/crates/map/src/layout/elements.rs b/crates/map/src/layout/elements.rs index 4859489789..e76251fb28 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -551,12 +551,14 @@ impl ElementKind { /// Whether `key` given as null changes an element of this kind, giving it back its default: /// an ink's `color`, a chart's `title` (the title it is given), `barColor`, `max` (its bars' /// own scale) and `barOutline` (none), a legend's or scale bar's `textSize` (#2581), and a - /// scale bar's `unitLabel` (its unit's abbreviation). + /// scale bar's `unitLabel` (its unit's abbreviation), and a profile's `fill` (none), `min` and + /// `max` (its samples' own). pub fn null_resets(&self, key: &str) -> bool { (self.takes_ink() && key == "color") || (matches!(self, ElementKind::Chart { .. }) && matches!(key, "title" | "barColor" | "max" | "barOutline")) || (matches!(self, ElementKind::Legend { .. } | ElementKind::ScaleBar { .. }) && key == "textSize") || (matches!(self, ElementKind::ScaleBar { .. }) && key == "unitLabel") + || (self.is_profile() && matches!(key, "fill" | "min" | "max")) } /// Its ink, when it [takes one](ElementKind::takes_ink) and has one; `None` draws in [`INK`]. diff --git a/crates/map/src/layout/profile.rs b/crates/map/src/layout/profile.rs index 8b060f95db..162113304b 100644 --- a/crates/map/src/layout/profile.rs +++ b/crates/map/src/layout/profile.rs @@ -181,6 +181,23 @@ impl Profile { } } + /// The gap and thickness that put it at `rect` (x, y, w, h in mm), beside a frame whose box is + /// `frame`, as far as they can: what is along the frame stays the frame's ([`Profile::rect`]). + /// Whether either was held to its limits. + pub fn take_rect(&mut self, (fx, fy, fw, fh): (f64, f64, f64, f64), (x, y, w, h): (f64, f64, f64, f64)) -> bool { + let (gap, thickness) = match self.side { + ProfileSide::Bottom => (y - (fy + fh), h), + ProfileSide::Top => (fy - (y + h), h), + ProfileSide::Right => (x - (fx + fw), w), + ProfileSide::Left => (fx - (x + w), w), + }; + self.gap = finite_or(gap, self.gap); + self.thickness = finite_or(thickness, self.thickness); + let (g, t) = (self.gap, self.thickness); + self.clamp(); + (g, t) != (self.gap, self.thickness) + } + /// Its numbers and texts brought into range (a layout file is hostile input). Whether a text was /// cut. pub(super) fn clamp(&mut self) -> bool { @@ -191,9 +208,7 @@ impl Profile { self.min = self.min.filter(|v| v.is_finite()); self.max = self.max.filter(|v| v.is_finite()); // Ends that cross can't be an axis: the samples' own range, counted as a repair. - if matches!((self.min, self.max), (Some(lo), Some(hi)) if lo >= hi) { - (self.min, self.max) = (None, None); - } + (self.min, self.max) = self.given_range(); let mut cut = false; for (text, most) in [(&mut self.title, MAX_PROFILE_TEXT), (&mut self.unit, MAX_PROFILE_TEXT), (&mut self.section, MAX_SECTION_NAME)] { diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index 96573c789d..d4d0028053 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -2047,7 +2047,8 @@ fn legend_class_labels_save_only_when_set_and_load_into_range() { } /// A profile beside its frame (#2863 part 2): its box is the frame's side, which it takes back after -/// the frame moves or is resized; saved with only what isn't its default, read back as saved; a hostile file's brought into range and counted, +/// the frame moves or is resized, a box asked of it read as its gap and thickness; saved with only +/// what isn't its default, read back as saved; a hostile file's brought into range and counted, /// and one saved elsewhere than its frame's side put back there. #[test] fn a_profile_keeps_to_its_frames_side() { @@ -2058,8 +2059,22 @@ fn a_profile_keeps_to_its_frames_side() { (ProfileSide::Right, (219.0, 34.0, 30.0, 112.0)), (ProfileSide::Left, (-3.0, 34.0, 30.0, 112.0)), ] { - let p = Profile::new(1, "A".into(), "DEM".into(), side); + let mut p = Profile::new(1, "A".into(), "DEM".into(), side); assert_eq!(p.rect(frame), rect, "{side:?}"); + // Dragged off along the frame, 5 mm further from it and 4 mm thicker: only the gap and + // thickness follow. + let (x, y, w, h) = rect; + let moved = match side { + ProfileSide::Bottom => (x + 40.0, y + 5.0, w, h + 4.0), + ProfileSide::Top => (x + 40.0, y - 9.0, w, h + 4.0), + ProfileSide::Right => (x + 5.0, y + 40.0, w + 4.0, h), + ProfileSide::Left => (x - 9.0, y + 40.0, w + 4.0, h), + }; + assert!(!p.take_rect(frame, moved)); + assert_eq!((p.gap, p.thickness), (8.0, 34.0), "{side:?}"); + // Into the frame, or too thin: held. + assert!(p.take_rect(frame, if side.is_horizontal() { (x, 60.0, w, 2.0) } else { (100.0, y, 2.0, h) })); + assert_eq!((p.gap, p.thickness), (PROFILE_GAPS.0, PROFILE_THICKNESSES.0), "{side:?}"); } assert!(ProfileSide::Bottom.suits(SectionLine::Horizontal(Coord::new(0.0, 0.0)))); assert!(!ProfileSide::Left.suits(SectionLine::Horizontal(Coord::new(0.0, 0.0)))); diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 431c747cf0..24e3719028 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -8,6 +8,10 @@ description = "RustGIS L3: CPU map renderer (tiny-skia), label placement, PNG ex [lints] workspace = true +[features] +# Test rasters for the tests of the crates over this one (`testing`). +testing = [] + [dependencies] rustgis-geom = { workspace = true } rustgis-data = { workspace = true } diff --git a/crates/render/src/layout/profile_tests.rs b/crates/render/src/layout/profile_tests.rs index 4c03df8803..f22a2a6eaa 100644 --- a/crates/render/src/layout/profile_tests.rs +++ b/crates/render/src/layout/profile_tests.rs @@ -1,8 +1,9 @@ -use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; +use rustgis_data::raster::Crs; use rustgis_map::Projection; use rustgis_map::layout::{FRAME_BORDER_COLOR, FRAME_BORDER_WIDTH, INDICATOR_COLOR, INDICATOR_WIDTH, ProfileSide}; use super::*; +use crate::testing::{grid, mantiqueira}; /// The Mantiqueira frame of #2863: 186 × 112 mm at 1:200,000 round the Agulhas Negras, in UTM 23S. const CENTER: Coord = Coord::new(-44.715, -22.412); @@ -11,18 +12,6 @@ const PEDRA_DA_MINA: Coord = Coord::new(-44.8429, -22.4282); const UTM: &str = "EPSG:31983"; const FRAME_MM: (f64, f64, f64, f64) = (30.0, 34.0, 186.0, 112.0); -/// A 30 m grid in UTM 23S over the frame and round it, each cell `z` of its centre's easting and -/// northing. -fn dem(z: impl Fn(f64, f64) -> f64) -> Raster { - let crs = Crs::from_epsg(31983).unwrap(); - let mid = crs.transformer().unwrap().from_lonlat(CENTER).unwrap(); - let (cols, rows, cell) = (1600usize, 1000usize, 30.0); - let (x0, y0) = (((mid.x - 24_000.0) / cell).round() * cell, ((mid.y + 15_000.0) / cell).round() * cell); - let data = (0..rows * cols).map(|i| z(x0 + ((i % cols) as f64 + 0.5) * cell, y0 - ((i / cols) as f64 + 0.5) * cell) as f32).collect(); - let gt = GeoTransform { origin_x: x0, origin_y: y0, pixel_width: cell, pixel_height: -cell }; - Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").unwrap() -} - /// A map in UTM 23S with `dem` as its layer "DEM". fn utm_map(dem: Raster) -> Map { let mut map = Map::new("m"); @@ -78,7 +67,7 @@ fn a_profile_is_read_along_the_line_on_the_page() { (SectionLine::Horizontal(AGULHAS_NEGRAS), (|_, n| n - 7_500_000.0) as fn(f64, f64) -> f64, ProfileSide::Bottom), (SectionLine::Vertical(PEDRA_DA_MINA), |e, _| e - 500_000.0, ProfileSide::Right), ] { - let maps = vec![utm_map(dem(z))]; + let maps = vec![utm_map(mantiqueira(z))]; let (l, id) = page(line, side, (0.0, 0.0)); let (s, section) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); assert_eq!(section.name, "A"); @@ -97,7 +86,7 @@ fn a_profile_is_read_along_the_line_on_the_page() { // A turned frame reads the line the page shows: turned a quarter, its horizontal runs north to // south, its northings falling a metre a metre of ground where the grid (30 km from north to // south) has them. - let maps = vec![utm_map(dem(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n))]; let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (90.0, 0.0)); let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); let read: Vec<(f64, f64)> = s.metres.iter().zip(&s.values).filter_map(|(m, v)| Some((*m, (*v)?))).collect(); @@ -113,7 +102,7 @@ fn a_profile_is_read_along_the_line_on_the_page() { /// latitude strays metres off the line on the page, which a profile doesn't (#2863). #[test] fn the_page_line_is_not_a_straight_line_of_longitude_and_latitude() { - let maps = vec![utm_map(dem(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n))]; let (l, id) = page(SectionLine::Horizontal(AGULHAS_NEGRAS), ProfileSide::Bottom, (0.0, 0.0)); let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); let map = maps.first().unwrap(); @@ -154,7 +143,7 @@ fn a_profiles_peak_is_drawn_straight_across_from_its_place() { (SectionLine::Vertical(AGULHAS_NEGRAS), ProfileSide::Right, 0.0), (SectionLine::Vertical(AGULHAS_NEGRAS), ProfileSide::Left, -15.0), ] { - let mut maps = vec![utm_map(dem(peak))]; + let mut maps = vec![utm_map(mantiqueira(peak))]; let (mut l, id) = page(line, side, (bearing, 0.0)); if let Some(ElementKind::Profile(p)) = l.element_mut(id).map(|e| &mut e.kind) { (p.guides, p.fill) = (false, None); @@ -200,7 +189,7 @@ fn a_profile_not_drawn_says_why() { let n = profiles_not_drawn(l, maps); profiles_notice(&n.into_iter().map(|n| (n, 1)).collect(), 1) }; - let maps = vec![utm_map(dem(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n))]; let (l, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); assert!(notes(&l, &maps).is_empty(), "{:?}", notes(&l, &maps)); let (tilted, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 40.0)); @@ -218,12 +207,12 @@ fn a_profile_not_drawn_says_why() { assert!(change(&|p| p.band = 2).contains("its layer 'DEM' has no band 2 (it has 1)")); assert!(change(&|p| p.section = "B".into()).contains("its frame has no section line 'B'")); assert!(change(&|p| p.layer = "Other".into()).contains("the frame's map has no raster layer 'Other'")); - let mut in_place = utm_map(dem(|_, n| n)); + let mut in_place = utm_map(mantiqueira(|_, n| n)); if let Some(r) = in_place.layers.first_mut().and_then(|l| l.raster.as_mut()) { r.in_place = true; } assert!(notes(&l, &[in_place]).join("").contains("is read in place, a part at a time, not held whole")); - let empty = vec![utm_map(dem(|_, _| f64::NAN))]; + let empty = vec![utm_map(mantiqueira(|_, _| f64::NAN))]; assert!(notes(&l, &empty).join("").contains("has no data along section line 'A'")); // Drawn, it draws its placeholder otherwise. let mut maps = maps; @@ -253,7 +242,7 @@ fn a_profiles_value_axis_is_round_or_given() { #[test] fn a_gap_in_the_data_is_a_gap_in_the_samples() { let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; - let maps = vec![utm_map(dem(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }))]; + let maps = vec![utm_map(mantiqueira(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }))]; let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); let runs = s.values.windows(2).filter(|w| w[0].is_some() != w[1].is_some()).count(); @@ -263,7 +252,7 @@ fn a_gap_in_the_data_is_a_gap_in_the_samples() { /// A band of 0 is no band: refused, not read as the first (#2863). #[test] fn a_band_of_0_is_refused() { - let maps = vec![utm_map(dem(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n))]; let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let p = Profile { band: 0, ..profile_of(&l, id).clone() }; let why = profile_samples(&l, &maps, &p).err().unwrap_or_default(); @@ -275,8 +264,7 @@ fn a_band_of_0_is_refused() { /// from wherever the ground begins (#2863). #[test] fn a_line_off_the_ground_is_refused() { - let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 1.0, pixel_height: -1.0 }; - let world = Raster::new("w", 360, 180, vec![vec![1.0; 360 * 180]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let world = grid(Crs::LonLat, (-180.0, 90.0), 1.0, (360, 180), |_, _| 1.0); let mut map = Map::new("m"); map.projection = Projection::Custom("ESRI:54008".into()); map.add_raster("DEM", rustgis_map::RasterLayer::from_path(world, "w.tif")); @@ -295,8 +283,7 @@ fn a_line_off_the_ground_is_refused() { /// stored from 179° to 181° crosses about eight cells, read one a cell (#2863). #[test] fn a_line_across_the_antimeridian_counts_the_cells_it_crosses() { - let gt = GeoTransform { origin_x: 179.0, origin_y: -16.0, pixel_width: 0.05, pixel_height: -0.05 }; - let fiji = Raster::new("f", 40, 40, vec![vec![1.0; 40 * 40]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let fiji = grid(Crs::LonLat, (179.0, -16.0), 0.05, (40, 40), |_, _| 1.0); let mut map = Map::new("m"); map.projection = Projection::Custom("EPSG:32760".into()); map.add_raster("DEM", rustgis_map::RasterLayer::from_path(fiji, "f.tif")); @@ -317,7 +304,7 @@ fn a_line_across_the_antimeridian_counts_the_cells_it_crosses() { #[test] fn a_profile_with_gaps_says_how_many_samples_have_no_value() { let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; - let gap = vec![utm_map(dem(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }))]; + let gap = vec![utm_map(mantiqueira(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }))]; let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let said = |maps: &[Map]| profiles_notice(&profiles_not_drawn(&l, maps).into_iter().map(|n| (n, 1)).collect(), 1); let (s, _) = profile_samples(&l, &gap, profile_of(&l, id)).unwrap(); @@ -329,7 +316,7 @@ fn a_profile_with_gaps_says_how_many_samples_have_no_value() { ); assert_eq!(said(&gap), vec![want]); // A line read whole says nothing. - assert!(said(&[utm_map(dem(|_, _| 100.0))]).is_empty()); + assert!(said(&[utm_map(mantiqueira(|_, _| 100.0))]).is_empty()); } /// Over several pages, a profile read thinned or with gaps says on how many of them, as one not @@ -360,7 +347,7 @@ fn a_thinned_or_gapped_profile_says_on_how_many_pages() { fn a_drawn_page_says_what_its_profiles_read() { let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; // Drawn with a gap, and not drawn on a tilted frame. - let mut maps = vec![utm_map(dem(move |e, n| if (e - mid).abs() < 2_000.0 { f64::NAN } else { n }))]; + let mut maps = vec![utm_map(mantiqueira(move |e, n| if (e - mid).abs() < 2_000.0 { f64::NAN } else { n }))]; for (bearing, pitch) in [(0.0, 0.0), (0.0, 40.0)] { let (l, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (bearing, pitch)); let (_, pending) = render_pending(&l, &mut maps, 30.0, &PageInfo::default()).unwrap(); @@ -374,7 +361,7 @@ fn a_drawn_page_says_what_its_profiles_read() { #[test] fn a_profile_cut_by_its_given_ends_says_how_many_samples_are_past_them() { let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; - let maps = vec![utm_map(dem(move |e, _| e - mid))]; + let maps = vec![utm_map(mantiqueira(move |e, _| e - mid))]; let (mut l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let said = |l: &Layout| profiles_notice(&profiles_not_drawn(l, &maps).into_iter().map(|n| (n, 1)).collect(), 1); assert!(said(&l).is_empty(), "{:?}", said(&l)); @@ -464,7 +451,7 @@ fn a_lone_sample_between_gaps_is_drawn() { /// one that fits says nothing (#2863). #[test] fn a_profile_too_thin_for_its_axes_says_so() { - let maps = vec![utm_map(dem(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n))]; let (mut l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let said = |l: &Layout| profiles_notice(&profiles_not_drawn(l, &maps).into_iter().map(|n| (n, 1)).collect(), 1); assert!(said(&l).is_empty(), "{:?}", said(&l)); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 7a090bb8d7..b26d08ed37 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -42,6 +42,9 @@ mod square_labels; mod stroke_paths; pub mod svg; pub mod terrain; +/// Test rasters, for this crate's tests and, with the `testing` feature, those over it. +#[cfg(any(test, feature = "testing"))] +pub mod testing; mod text; pub use text::CALLOUT_WIDTH; mod frame_cache; diff --git a/crates/render/src/testing.rs b/crates/render/src/testing.rs new file mode 100644 index 0000000000..0252fd94c4 --- /dev/null +++ b/crates/render/src/testing.rs @@ -0,0 +1,23 @@ +//! Rasters the tests of this crate, and of the crates over it, draw and read layouts from (#2863). +#![allow(clippy::expect_used, reason = "a test grid that fails to build is a broken test, said at once")] + +use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; +use rustgis_geom::Coord; + +/// A one-band grid in `crs` of `cols` × `rows` square cells of `cell`, its top-left corner at +/// `(x0, y0)`, each cell `z` of its centre's x and y. +pub fn grid(crs: Crs, (x0, y0): (f64, f64), cell: f64, (cols, rows): (usize, usize), z: impl Fn(f64, f64) -> f64) -> Raster { + let data = (0..rows * cols).map(|i| z(x0 + ((i % cols) as f64 + 0.5) * cell, y0 - ((i / cols) as f64 + 0.5) * cell) as f32).collect(); + let gt = GeoTransform { origin_x: x0, origin_y: y0, pixel_width: cell, pixel_height: -cell }; + Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").expect("a grid") +} + +/// The Mantiqueira's [`grid`] of #2863: 30 m in UTM 23S, 48 × 30 km round (-44.715, -22.412), +/// where a 186 × 112 mm frame at 1:200,000 shows the Agulhas Negras; `z` of easting and northing. +pub fn mantiqueira(z: impl Fn(f64, f64) -> f64) -> Raster { + let crs = Crs::from_epsg(31983).expect("UTM 23S"); + let mid = crs.transformer().expect("UTM 23S").from_lonlat(Coord::new(-44.715, -22.412)).expect("the centre"); + let cell = 30.0; + let (x0, y0) = (((mid.x - 24_000.0) / cell).round() * cell, ((mid.y + 15_000.0) / cell).round() * cell); + grid(crs, (x0, y0), cell, (1600, 1000), z) +} diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index fa590268e9..c42d870ef7 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -1241,6 +1241,23 @@ pub fn paint(painter: &Painter, r: Rect, name: &str, ink: Color32, accent: Color p.line(&[(12.0, y), (18.0, y)], 1.1, ink); } } + // A ridge's profile over its base and distance ticks, a dashed section line above it. + "layout_profile" => { + let ridge = [(3.0, 15.0), (6.0, 12.0), (9.0, 13.0), (12.5, 7.0), (15.5, 10.0), (18.0, 9.0), (21.0, 14.0)]; + for w in ridge.windows(2) { + if let [a, b] = w { + p.fill(&[(a.0, 17.0), *a, *b, (b.0, 17.0)], p.tint(60)); + } + } + p.line(&ridge, 1.4, ink); + p.line(&[(3.0, 17.0), (21.0, 17.0)], 1.2, ink); + for x in [3.0, 9.0, 15.0, 21.0] { + p.line(&[(x, 17.0), (x, 19.5)], 1.0, ink); + } + for x in [3.0, 8.0, 13.0, 18.0] { + p.line(&[(x, 4.0), (x + 3.0, 4.0)], 1.3, accent); + } + } // A gradient bar over its tick marks. "colorbar" => { for i in 0..9 { @@ -1363,6 +1380,7 @@ pub const ALL: &[&str] = &[ "stats", "chart", "colorbar", + "layout_profile", "count", "calc_geom", "table", diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 5f69e2710c..a94eee06da 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -3626,6 +3626,12 @@ fn layout_groups(app: &mut RustGisApp, ui: &mut Ui) { } }); }); + col(ui, |ui| { + let desc = "Add a raster's profile beside the map frame, along one of its section lines."; + if small(ui, app, "layout_profile", "Profile", desc, "ui.menu", Value::Null, false).clicked() { + add(app, json!({"kind": "profile"})); + } + }); }); group(ui, "Shapes", |ui| { // In the middle of the page, ready to be moved and sized. diff --git a/docs/maintaining.md b/docs/maintaining.md index 365d6f858f..273d102ea0 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -300,8 +300,10 @@ has such a frame requires it as well. Projects with a profile beside a map frame (an element of kind `Profile`) require `layout-profile`, so an older reader refuses them instead of dropping the element (#2863 part 2). A saved -`layout.addElement` of a profile requires it too. A saved `layout.import` whose `text` has one -requires it as well. +`layout.addElement` of a profile requires it too, and so does a `layout.update` with a key only a +profile reads (`band`, `side`, `gap`, `thickness`, `unit`, `lineColor`, `lineWidth`, `guides`, +`min`, or a `section` given as a name). A saved `layout.import` whose `text` has one requires it as +well. Projects with a legend, a scale bar or a grid whose text isn't its default size (`text_size` on a legend, 9 points by default, or on a scale bar, 8; `label_size` on a frame's grid, 8) require diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index f186e040eb..4eea2e87be 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -338,6 +338,31 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu (the name defaults to the first free letter, the place to the frame's centre), then `layout.update={"element":1,"section":{"name":"A","at":[-44.7,-22.4],"color":"#1F5C84"}}` (`"newName"` renames it, and `"remove": true` removes it). +- **Profiles**: **Profile** in *Publish › Map Surrounds* draws, beside a frame, the profile of a + raster along one of its section lines (#2863): under or over the frame for a horizontal line, + right or left of it for a vertical one. It is lined up with the map: each sample is read at its + point of the line on the page, taken back through the frame's projection to the ground, so each + point of the curve is straight across from the place it comes from, whatever the projection or + the frame's bearing. That line is neither a parallel nor a straight line between the longitudes + and latitudes of its ends, which `profile.create` follows: on a map in UTM 37 km wide the two + part by metres. The profile takes the frame's side along its length, and keeps to it when the + frame is moved or resized; dragged, it moves away from the frame or nearer, and resized, it grows + thicker or thinner. It reads one band of any raster held whole (not one read in place, such as a + web address's cloud-optimised GeoTIFF, which gives only the overview the view draws), bilinearly, + a sample a cell up to 10,000, nothing smoothed; where the raster has no data the curve breaks. + The curve can be filled under it in one colour; its value axis has round numbers on guide lines + (or the **min** and **max** given, so that two profiles share a scale), with a unit after them; + its distance axis counts along the ground from the line's A end in the units a scale bar takes; + and the section's names stand at its ends. A tilted frame or one on the globe takes no profile + (a line straight on the page there isn't a section of the ground), nor does a section line + running the other way: the profile draws its placeholder, and the layout view, its command and + exports say why. It follows its section line and layer when they are renamed, and goes with its + frame. From a command: + `layout.addElement={"kind":"profile","frame":1,"section":"A","layer":"DEM","side":"bottom","unit":"m"}` + (the section defaults to the frame's first, the layer to the top raster shown, the title to the + layer's name; `"band"`, `"gap"`, `"thickness"`, `"lineColor"`, `"lineWidth"`, `"fill"` (null for + none), `"min"`, `"max"`, `"units"`, `"guides"` and `"color"`, its ink, are its options), then + `layout.update` with the same keys. - **Measured grids**: a grid's **Type** is a **Graticule** (latitudes and longitudes, as above) or a **Measured grid**, as ArcGIS Pro has them: eastings and northings in a projected coordinate system, for maps read with UTM or national grid coordinates (a hiking map at 1:25,000 with a From 24fb8839681fceb1b2b8a30a714efcfbf0495c35 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 09:32:48 -0300 Subject: [PATCH 2/5] fix(layout): the render profile tests import Raster for their map (#2863 part 2f) Co-Authored-By: Claude Opus 5.5 --- crates/render/src/layout/profile_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/render/src/layout/profile_tests.rs b/crates/render/src/layout/profile_tests.rs index f22a2a6eaa..530e192d74 100644 --- a/crates/render/src/layout/profile_tests.rs +++ b/crates/render/src/layout/profile_tests.rs @@ -1,4 +1,4 @@ -use rustgis_data::raster::Crs; +use rustgis_data::raster::{Crs, Raster}; use rustgis_map::Projection; use rustgis_map::layout::{FRAME_BORDER_COLOR, FRAME_BORDER_WIDTH, INDICATOR_COLOR, INDICATOR_WIDTH, ProfileSide}; From 24b21cd36557258e057ab322b03582562d0ce682 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 10:28:27 -0300 Subject: [PATCH 3/5] fix(layout): a profile moved to another side keeps its thickness when given part of a box (#2863 part 2f) layout.update of a profile with a section line or side that moves it to another side and only some of x, y, w and h took the ones left out from its box on the old side: moved from the bottom to the right with only x, its thickness became the frame's width. What isn't given is now where it would sit on its new side, its gap and thickness kept. The user guide says a profile's default layer passes over one read in place, and its layout.update example gives no frame. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout/profile.rs | 4 +++- crates/engine/src/tests/layout_profiles.rs | 8 ++++++++ docs/user-guide/layouts.md | 9 +++++---- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layout/profile.rs b/crates/engine/src/cmd/layout/profile.rs index ae36659a6f..d961079e91 100644 --- a/crates/engine/src/cmd/layout/profile.rs +++ b/crates/engine/src/cmd/layout/profile.rs @@ -263,8 +263,10 @@ pub(in crate::cmd::layout) fn update_profile(s: &mut Session, p: &Value, li: usi let (mut new, mut held) = profile_params(s, l, p, current.clone())?; let (_, _, frame_box) = frame_parts(s, l, new.frame)?; if boxed { + // What isn't given is where it would sit now, on its side after this change. + let (x, y, w, h) = new.rect(frame_box); let at = |k: &str, now: f64| given_num(p, k, "a number of mm").map(|v| v.unwrap_or(now)); - let rect = (at("x", e.x)?, at("y", e.y)?, at("w", e.w)?, at("h", e.h)?); + let rect = (at("x", x)?, at("y", y)?, at("w", w)?, at("h", h)?); if new.take_rect(frame_box, rect) { let ((g0, g1), (t0, t1)) = (PROFILE_GAPS, PROFILE_THICKNESSES); held.push(format!("its gap held to {} ({g0} to {g1} mm) and thickness to {} ({t0} to {t1} mm)", new.gap, new.thickness)); diff --git a/crates/engine/src/tests/layout_profiles.rs b/crates/engine/src/tests/layout_profiles.rs index 7d3780add5..5b838a64c4 100644 --- a/crates/engine/src/tests/layout_profiles.rs +++ b/crates/engine/src/tests/layout_profiles.rs @@ -151,6 +151,14 @@ fn a_profile_is_changed_and_follows_its_names() { s.run("layout.update", &json!({"element": id, "x": 60, "y": at[1] + 4.0, "h": 40})).unwrap(); let (p, moved) = profile(&s, id); assert_eq!((moved[0], p.gap, p.thickness), (at[0], 7.0, 40.0)); + // Moved to a vertical line with only x given: it goes to the right side, 8 mm off, keeping its + // thickness, not taking the frame's width it had along the bottom. + s.run("layout.addElement", &json!({"kind": "section", "name": "B", "at": [10, 50], "direction": "vertical"})).unwrap(); + let [fx, _, fw, _] = frame_box(&s, frame); + s.run("layout.update", &json!({"element": id, "section": "B", "x": fx + fw + 8.0})).unwrap(); + let (p, _) = profile(&s, id); + assert_eq!((p.side, p.gap, p.thickness), (ProfileSide::Right, 8.0, 40.0)); + s.run("layout.update", &json!({"element": id, "section": "A"})).unwrap(); let mark = s.notice_mark(); s.run("layout.update", &json!({"element": id, "thickness": 1000, "fill": null, "lineColor": "#1F5C84", "min": 0})).unwrap(); assert!(said(&s, mark).iter().any(|n| n.contains("thickness 1000 held to 300")), "{:?}", said(&s, mark)); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 7e00238aed..0dee2715ae 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -365,10 +365,11 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu exports say why. It follows its section line and layer when they are renamed, and goes with its frame. From a command: `layout.addElement={"kind":"profile","frame":1,"section":"A","layer":"DEM","side":"bottom","unit":"m"}` - (the section defaults to the frame's first, the layer to the top raster shown, the title to the - layer's name; `"band"`, `"gap"`, `"thickness"`, `"lineColor"`, `"lineWidth"`, `"fill"` (null for - none), `"min"`, `"max"`, `"units"`, `"guides"` and `"color"`, its ink, are its options), then - `layout.update` with the same keys. + (the section defaults to the frame's first, the layer to the top raster shown that it can read, + passing over one read in place, the title to the layer's name; `"band"`, `"gap"`, `"thickness"`, + `"lineColor"`, `"lineWidth"`, `"fill"` (null for none), `"min"`, `"max"`, `"units"`, `"guides"` + and `"color"`, its ink, are its options). `layout.update` changes them, the frame aside: + `layout.update={"element":7,"section":"B","thickness":40,"min":null}`. - **Measured grids**: a grid's **Type** is a **Graticule** (latitudes and longitudes, as above) or a **Measured grid**, as ArcGIS Pro has them: eastings and northings in a projected coordinate system, for maps read with UTM or national grid coordinates (a hiking map at 1:25,000 with a From ac9f318fe23603a132b441fb9d0e0e8c8c130b7e Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 11:34:40 -0300 Subject: [PATCH 4/5] fix(layout): a profile's box says what it doesn't use, holds only past its limits, and a lost band blocks no rename (#2863 part 2f) - layout.update of a profile with an x, y, w or h along its frame that isn't the frame's says it isn't used (the notice 2a gave, now only for what is dropped). - take_rect no longer reports a gap at its limit as held when reading it back off the frame's edges rounds past it. - A profile left on a band its raster no longer has is still renamed, hidden and locked; the band count is checked only when a band or layer is given. - rustgis_render::testing's grids return a Result instead of expecting (no expect outside tests, as AGENTS.md asks). - The user guide says the raster must be georeferenced, and that a raster of classes makes no curve worth reading. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout/profile.rs | 10 ++++++- crates/engine/src/tests/layout_profiles.rs | 26 ++++++++++++++++-- crates/map/src/layout/profile.rs | 3 +- crates/map/src/layout/tests.rs | 6 ++++ crates/render/src/layout/profile_tests.rs | 32 +++++++++++----------- crates/render/src/testing.rs | 20 +++++++++----- docs/user-guide/layouts.md | 8 ++++-- 7 files changed, 75 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/layout/profile.rs b/crates/engine/src/cmd/layout/profile.rs index d961079e91..ce492a8740 100644 --- a/crates/engine/src/cmd/layout/profile.rs +++ b/crates/engine/src/cmd/layout/profile.rs @@ -130,7 +130,8 @@ fn profile_params(s: &Session, l: &Layout, p: &Value, mut base: Profile) -> Resu } base.band = v as u32; } - if let Some(n) = bands_of(map, &base.layer).filter(|n| base.band as usize > *n) { + // Only a band or layer given is checked: one left on a band its raster lost still takes the rest. + if let Some(n) = bands_of(map, &base.layer).filter(|n| base.band as usize > *n && (gives(p, "band") || gives(p, "layer"))) { return Err(format!("'{}' has {n} band(s): band is 1 to {n}", base.layer)); } let mut mm = |k: &str, range: (f64, f64), v: &mut f64| -> Result<(), String> { @@ -271,6 +272,13 @@ pub(in crate::cmd::layout) fn update_profile(s: &mut Session, p: &Value, li: usi let ((g0, g1), (t0, t1)) = (PROFILE_GAPS, PROFILE_THICKNESSES); held.push(format!("its gap held to {} ({g0} to {g1} mm) and thickness to {} ({t0} to {t1} mm)", new.gap, new.thickness)); } + // Along its frame it keeps the frame's: what was given there and isn't that, said. + let along = if new.side.is_horizontal() { [("x", x), ("w", w)] } else { [("y", y), ("h", h)] }; + for (k, kept) in along { + if let Some(v) = f(p, k).filter(|v| (v - kept).abs() > 1e-9) { + held.push(format!("{k} {v} not used: along its frame a profile keeps the frame's ({kept})")); + } + } } let reread = ["section", "layer", "band", "side"].iter().any(|k| gives(p, k)); let l = s.project.layouts.get_mut(li).ok_or("no layout")?; diff --git a/crates/engine/src/tests/layout_profiles.rs b/crates/engine/src/tests/layout_profiles.rs index 5b838a64c4..c4e6c1664e 100644 --- a/crates/engine/src/tests/layout_profiles.rs +++ b/crates/engine/src/tests/layout_profiles.rs @@ -22,7 +22,7 @@ fn put_profile(s: &mut Session, frame: u32, side: ProfileSide) -> u32 { /// metres of latitude over it, and the frame's id. fn with_dem() -> (Session, u32) { let mut s = Session::new(sample::world_project()); - let r = grid(Crs::LonLat, (0.0, 60.0), 0.05, (400, 400), |_, lat| lat * 100.0); + let r = grid(Crs::LonLat, (0.0, 60.0), 0.05, (400, 400), |_, lat| lat * 100.0).unwrap(); s.map_mut().add_raster("DEM", rustgis_map::RasterLayer::from_path(r, "dem.tif")); s.run("layout.new", &json!({"page": "a4", "template": "map"})).unwrap(); let frame = s.project.layouts[0].first_frame().unwrap(); @@ -55,8 +55,14 @@ fn a_box_given_to_a_profile_sets_its_gap_and_thickness() { let id = put_profile(&mut s, frame, ProfileSide::Bottom); let box_of = |s: &Session| s.project.layouts[0].element(id).map(|e| (e.x, e.y, e.w, e.h)); let (x, y, w, _) = box_of(&s).unwrap(); + let mark = s.notice_mark(); s.run("layout.update", &json!({"element": id, "x": 5, "h": 50})).unwrap(); assert_eq!(box_of(&s), Some((x, y, w, 50.0))); + let notes: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(notes.iter().any(|n| n.contains("x 5 not used")), "the frame's x kept, said: {notes:?}"); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "x": x, "h": 45})).unwrap(); + assert!(s.notices_since(mark).is_empty(), "its own x is no change"); let err = s.run("layout.update", &json!({"element": id, "y": "far"})).unwrap_err(); assert!(err.contains("y is a number of mm"), "{err}"); let mark = s.notice_mark(); @@ -139,6 +145,22 @@ fn a_profile_is_added_follows_its_frame_and_is_undone() { assert!(notes.len() == 1 && notes[0].contains("1 profile(s) not drawn") && notes[0].contains("tilted"), "{notes:?}"); } +/// A profile left on a band its raster no longer has (a one-band file put in its place) is still +/// renamed, hidden and locked; only a band or layer given is checked against the raster. +#[test] +fn a_profile_on_a_lost_band_still_takes_its_name_and_visibility() { + let (mut s, frame) = with_dem(); + let id = put_profile(&mut s, frame, ProfileSide::Bottom); + if let Some(ElementKind::Profile(p)) = s.project.layouts[0].element_mut(id).map(|e| &mut e.kind) { + p.band = 2; + } + s.run("layout.update", &json!({"element": id, "name": "Perfil", "visible": false, "locked": true})).unwrap(); + let e = s.project.layouts[0].element(id).unwrap(); + assert_eq!((e.name.as_str(), e.visible, e.locked), ("Perfil", false, true)); + let err = s.run("layout.update", &json!({"element": id, "locked": false, "band": 2})).unwrap_err(); + assert!(err.contains("'DEM' has 1 band(s)"), "{err}"); +} + /// A profile is changed with `layout.update`: dragged along its frame and away from it, only its /// gap follows, and resized, its thickness; a value past its limits is held there and said; it /// follows its section line and its layer when they are renamed. @@ -238,7 +260,7 @@ fn the_mantiqueira_profile_agrees_with_profile_create() { s.run("map.projection", &json!({"type": "EPSG:31983"})).unwrap(); // Ridges and valleys a few kilometres across, some 2,000 m of relief, as the Mantiqueira's. let z = |e: f64, n: f64| 1500.0 + 600.0 * (e / 2_300.0).sin() * (n / 1_700.0).cos() + 300.0 * ((e + n) / 900.0).sin(); - let r = mantiqueira(z); + let r = mantiqueira(z).unwrap(); s.map_mut().add_raster("DEM", rustgis_map::RasterLayer::from_path(r, "dem.tif")); s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "blank"})).unwrap(); s.run("layout.addFrame", &json!({})).unwrap(); diff --git a/crates/map/src/layout/profile.rs b/crates/map/src/layout/profile.rs index 162113304b..5daf26f984 100644 --- a/crates/map/src/layout/profile.rs +++ b/crates/map/src/layout/profile.rs @@ -195,7 +195,8 @@ impl Profile { self.thickness = finite_or(thickness, self.thickness); let (g, t) = (self.gap, self.thickness); self.clamp(); - (g, t) != (self.gap, self.thickness) + // Read back off the frame's edges, a gap at its limit can be a rounding past it: no hold. + (g - self.gap).abs() > 1e-9 || (t - self.thickness).abs() > 1e-9 } /// Its numbers and texts brought into range (a layout file is hostile input). Whether a text was diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index d4d0028053..b927e570c3 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -2075,6 +2075,12 @@ fn a_profile_keeps_to_its_frames_side() { // Into the frame, or too thin: held. assert!(p.take_rect(frame, if side.is_horizontal() { (x, 60.0, w, 2.0) } else { (100.0, y, 2.0, h) })); assert_eq!((p.gap, p.thickness), (PROFILE_GAPS.0, PROFILE_THICKNESSES.0), "{side:?}"); + // At a limit already, given back its own box off a frame whose edges aren't round: nothing held. + let odd = (30.1, 0.1, 186.3, 112.7); + for gap in [PROFILE_GAPS.0, PROFILE_GAPS.1] { + p.gap = gap; + assert!(!p.take_rect(odd, p.rect(odd)), "{side:?} at gap {gap}"); + } } assert!(ProfileSide::Bottom.suits(SectionLine::Horizontal(Coord::new(0.0, 0.0)))); assert!(!ProfileSide::Left.suits(SectionLine::Horizontal(Coord::new(0.0, 0.0)))); diff --git a/crates/render/src/layout/profile_tests.rs b/crates/render/src/layout/profile_tests.rs index 530e192d74..966246b7e6 100644 --- a/crates/render/src/layout/profile_tests.rs +++ b/crates/render/src/layout/profile_tests.rs @@ -67,7 +67,7 @@ fn a_profile_is_read_along_the_line_on_the_page() { (SectionLine::Horizontal(AGULHAS_NEGRAS), (|_, n| n - 7_500_000.0) as fn(f64, f64) -> f64, ProfileSide::Bottom), (SectionLine::Vertical(PEDRA_DA_MINA), |e, _| e - 500_000.0, ProfileSide::Right), ] { - let maps = vec![utm_map(mantiqueira(z))]; + let maps = vec![utm_map(mantiqueira(z).unwrap())]; let (l, id) = page(line, side, (0.0, 0.0)); let (s, section) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); assert_eq!(section.name, "A"); @@ -86,7 +86,7 @@ fn a_profile_is_read_along_the_line_on_the_page() { // A turned frame reads the line the page shows: turned a quarter, its horizontal runs north to // south, its northings falling a metre a metre of ground where the grid (30 km from north to // south) has them. - let maps = vec![utm_map(mantiqueira(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n).unwrap())]; let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (90.0, 0.0)); let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); let read: Vec<(f64, f64)> = s.metres.iter().zip(&s.values).filter_map(|(m, v)| Some((*m, (*v)?))).collect(); @@ -102,7 +102,7 @@ fn a_profile_is_read_along_the_line_on_the_page() { /// latitude strays metres off the line on the page, which a profile doesn't (#2863). #[test] fn the_page_line_is_not_a_straight_line_of_longitude_and_latitude() { - let maps = vec![utm_map(mantiqueira(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n).unwrap())]; let (l, id) = page(SectionLine::Horizontal(AGULHAS_NEGRAS), ProfileSide::Bottom, (0.0, 0.0)); let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); let map = maps.first().unwrap(); @@ -143,7 +143,7 @@ fn a_profiles_peak_is_drawn_straight_across_from_its_place() { (SectionLine::Vertical(AGULHAS_NEGRAS), ProfileSide::Right, 0.0), (SectionLine::Vertical(AGULHAS_NEGRAS), ProfileSide::Left, -15.0), ] { - let mut maps = vec![utm_map(mantiqueira(peak))]; + let mut maps = vec![utm_map(mantiqueira(peak).unwrap())]; let (mut l, id) = page(line, side, (bearing, 0.0)); if let Some(ElementKind::Profile(p)) = l.element_mut(id).map(|e| &mut e.kind) { (p.guides, p.fill) = (false, None); @@ -189,7 +189,7 @@ fn a_profile_not_drawn_says_why() { let n = profiles_not_drawn(l, maps); profiles_notice(&n.into_iter().map(|n| (n, 1)).collect(), 1) }; - let maps = vec![utm_map(mantiqueira(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n).unwrap())]; let (l, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); assert!(notes(&l, &maps).is_empty(), "{:?}", notes(&l, &maps)); let (tilted, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 40.0)); @@ -207,12 +207,12 @@ fn a_profile_not_drawn_says_why() { assert!(change(&|p| p.band = 2).contains("its layer 'DEM' has no band 2 (it has 1)")); assert!(change(&|p| p.section = "B".into()).contains("its frame has no section line 'B'")); assert!(change(&|p| p.layer = "Other".into()).contains("the frame's map has no raster layer 'Other'")); - let mut in_place = utm_map(mantiqueira(|_, n| n)); + let mut in_place = utm_map(mantiqueira(|_, n| n).unwrap()); if let Some(r) = in_place.layers.first_mut().and_then(|l| l.raster.as_mut()) { r.in_place = true; } assert!(notes(&l, &[in_place]).join("").contains("is read in place, a part at a time, not held whole")); - let empty = vec![utm_map(mantiqueira(|_, _| f64::NAN))]; + let empty = vec![utm_map(mantiqueira(|_, _| f64::NAN).unwrap())]; assert!(notes(&l, &empty).join("").contains("has no data along section line 'A'")); // Drawn, it draws its placeholder otherwise. let mut maps = maps; @@ -242,7 +242,7 @@ fn a_profiles_value_axis_is_round_or_given() { #[test] fn a_gap_in_the_data_is_a_gap_in_the_samples() { let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; - let maps = vec![utm_map(mantiqueira(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }))]; + let maps = vec![utm_map(mantiqueira(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }).unwrap())]; let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let (s, _) = profile_samples(&l, &maps, profile_of(&l, id)).unwrap(); let runs = s.values.windows(2).filter(|w| w[0].is_some() != w[1].is_some()).count(); @@ -252,7 +252,7 @@ fn a_gap_in_the_data_is_a_gap_in_the_samples() { /// A band of 0 is no band: refused, not read as the first (#2863). #[test] fn a_band_of_0_is_refused() { - let maps = vec![utm_map(mantiqueira(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n).unwrap())]; let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let p = Profile { band: 0, ..profile_of(&l, id).clone() }; let why = profile_samples(&l, &maps, &p).err().unwrap_or_default(); @@ -264,7 +264,7 @@ fn a_band_of_0_is_refused() { /// from wherever the ground begins (#2863). #[test] fn a_line_off_the_ground_is_refused() { - let world = grid(Crs::LonLat, (-180.0, 90.0), 1.0, (360, 180), |_, _| 1.0); + let world = grid(Crs::LonLat, (-180.0, 90.0), 1.0, (360, 180), |_, _| 1.0).unwrap(); let mut map = Map::new("m"); map.projection = Projection::Custom("ESRI:54008".into()); map.add_raster("DEM", rustgis_map::RasterLayer::from_path(world, "w.tif")); @@ -283,7 +283,7 @@ fn a_line_off_the_ground_is_refused() { /// stored from 179° to 181° crosses about eight cells, read one a cell (#2863). #[test] fn a_line_across_the_antimeridian_counts_the_cells_it_crosses() { - let fiji = grid(Crs::LonLat, (179.0, -16.0), 0.05, (40, 40), |_, _| 1.0); + let fiji = grid(Crs::LonLat, (179.0, -16.0), 0.05, (40, 40), |_, _| 1.0).unwrap(); let mut map = Map::new("m"); map.projection = Projection::Custom("EPSG:32760".into()); map.add_raster("DEM", rustgis_map::RasterLayer::from_path(fiji, "f.tif")); @@ -304,7 +304,7 @@ fn a_line_across_the_antimeridian_counts_the_cells_it_crosses() { #[test] fn a_profile_with_gaps_says_how_many_samples_have_no_value() { let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; - let gap = vec![utm_map(mantiqueira(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }))]; + let gap = vec![utm_map(mantiqueira(move |e, _| if (e - mid).abs() < 2_000.0 { f64::NAN } else { 100.0 }).unwrap())]; let (l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let said = |maps: &[Map]| profiles_notice(&profiles_not_drawn(&l, maps).into_iter().map(|n| (n, 1)).collect(), 1); let (s, _) = profile_samples(&l, &gap, profile_of(&l, id)).unwrap(); @@ -316,7 +316,7 @@ fn a_profile_with_gaps_says_how_many_samples_have_no_value() { ); assert_eq!(said(&gap), vec![want]); // A line read whole says nothing. - assert!(said(&[utm_map(mantiqueira(|_, _| 100.0))]).is_empty()); + assert!(said(&[utm_map(mantiqueira(|_, _| 100.0).unwrap())]).is_empty()); } /// Over several pages, a profile read thinned or with gaps says on how many of them, as one not @@ -347,7 +347,7 @@ fn a_thinned_or_gapped_profile_says_on_how_many_pages() { fn a_drawn_page_says_what_its_profiles_read() { let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; // Drawn with a gap, and not drawn on a tilted frame. - let mut maps = vec![utm_map(mantiqueira(move |e, n| if (e - mid).abs() < 2_000.0 { f64::NAN } else { n }))]; + let mut maps = vec![utm_map(mantiqueira(move |e, n| if (e - mid).abs() < 2_000.0 { f64::NAN } else { n }).unwrap())]; for (bearing, pitch) in [(0.0, 0.0), (0.0, 40.0)] { let (l, _) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (bearing, pitch)); let (_, pending) = render_pending(&l, &mut maps, 30.0, &PageInfo::default()).unwrap(); @@ -361,7 +361,7 @@ fn a_drawn_page_says_what_its_profiles_read() { #[test] fn a_profile_cut_by_its_given_ends_says_how_many_samples_are_past_them() { let mid = Crs::from_epsg(31983).unwrap().transformer().unwrap().from_lonlat(CENTER).unwrap().x; - let maps = vec![utm_map(mantiqueira(move |e, _| e - mid))]; + let maps = vec![utm_map(mantiqueira(move |e, _| e - mid).unwrap())]; let (mut l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let said = |l: &Layout| profiles_notice(&profiles_not_drawn(l, &maps).into_iter().map(|n| (n, 1)).collect(), 1); assert!(said(&l).is_empty(), "{:?}", said(&l)); @@ -451,7 +451,7 @@ fn a_lone_sample_between_gaps_is_drawn() { /// one that fits says nothing (#2863). #[test] fn a_profile_too_thin_for_its_axes_says_so() { - let maps = vec![utm_map(mantiqueira(|_, n| n))]; + let maps = vec![utm_map(mantiqueira(|_, n| n).unwrap())]; let (mut l, id) = page(SectionLine::Horizontal(CENTER), ProfileSide::Bottom, (0.0, 0.0)); let said = |l: &Layout| profiles_notice(&profiles_not_drawn(l, &maps).into_iter().map(|n| (n, 1)).collect(), 1); assert!(said(&l).is_empty(), "{:?}", said(&l)); diff --git a/crates/render/src/testing.rs b/crates/render/src/testing.rs index 0252fd94c4..4555c2362d 100644 --- a/crates/render/src/testing.rs +++ b/crates/render/src/testing.rs @@ -1,22 +1,28 @@ //! Rasters the tests of this crate, and of the crates over it, draw and read layouts from (#2863). -#![allow(clippy::expect_used, reason = "a test grid that fails to build is a broken test, said at once")] use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; use rustgis_geom::Coord; /// A one-band grid in `crs` of `cols` × `rows` square cells of `cell`, its top-left corner at -/// `(x0, y0)`, each cell `z` of its centre's x and y. -pub fn grid(crs: Crs, (x0, y0): (f64, f64), cell: f64, (cols, rows): (usize, usize), z: impl Fn(f64, f64) -> f64) -> Raster { +/// `(x0, y0)`, each cell `z` of its centre's x and y; why not, when it can't be made. +pub fn grid( + crs: Crs, + (x0, y0): (f64, f64), + cell: f64, + (cols, rows): (usize, usize), + z: impl Fn(f64, f64) -> f64, +) -> Result { let data = (0..rows * cols).map(|i| z(x0 + ((i % cols) as f64 + 0.5) * cell, y0 - ((i / cols) as f64 + 0.5) * cell) as f32).collect(); let gt = GeoTransform { origin_x: x0, origin_y: y0, pixel_width: cell, pixel_height: -cell }; - Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").expect("a grid") + Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").map_err(|e| e.to_string()) } /// The Mantiqueira's [`grid`] of #2863: 30 m in UTM 23S, 48 × 30 km round (-44.715, -22.412), /// where a 186 × 112 mm frame at 1:200,000 shows the Agulhas Negras; `z` of easting and northing. -pub fn mantiqueira(z: impl Fn(f64, f64) -> f64) -> Raster { - let crs = Crs::from_epsg(31983).expect("UTM 23S"); - let mid = crs.transformer().expect("UTM 23S").from_lonlat(Coord::new(-44.715, -22.412)).expect("the centre"); +pub fn mantiqueira(z: impl Fn(f64, f64) -> f64) -> Result { + let crs = Crs::from_epsg(31983).ok_or("no UTM 23S")?; + let to = crs.transformer().map_err(|e| e.to_string())?; + let mid = to.from_lonlat(Coord::new(-44.715, -22.412)).ok_or("the centre off UTM 23S")?; let cell = 30.0; let (x0, y0) = (((mid.x - 24_000.0) / cell).round() * cell, ((mid.y + 15_000.0) / cell).round() * cell); grid(crs, (x0, y0), cell, (1600, 1000), z) diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 0dee2715ae..aeb443fcd5 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -353,9 +353,11 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu and latitudes of its ends, which `profile.create` follows: on a map in UTM 37 km wide the two part by metres. The profile takes the frame's side along its length, and keeps to it when the frame is moved or resized; dragged, it moves away from the frame or nearer, and resized, it grows - thicker or thinner. It reads one band of any raster held whole (not one read in place, such as a - web address's cloud-optimised GeoTIFF, which gives only the overview the view draws), bilinearly, - a sample a cell up to 10,000, nothing smoothed; where the raster has no data the curve breaks. + thicker or thinner. It reads one band of any georeferenced raster held whole (not one read in + place, such as a web address's cloud-optimised GeoTIFF, which gives only the overview the view + draws), bilinearly, a sample a cell up to 10,000, nothing smoothed; where the raster has no data + the curve breaks. Read bilinearly, a raster of classes (land cover, soil types) gives values + between its codes, so it makes no curve worth reading: a profile is for a measured surface. The curve can be filled under it in one colour; its value axis has round numbers on guide lines (or the **min** and **max** given, so that two profiles share a scale), with a unit after them; its distance axis counts along the ground from the line's A end in the units a scale bar takes; From 389d0a5a5646985497b98bd76d629b52b1d3fcd5 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 29 Nov 2026 12:53:19 -0300 Subject: [PATCH 5/5] fix(layout): a profile whose frame's map was deleted is still unlocked, renamed and shown (#2863 part 2f) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit layout.update of a profile read its frame and map for every change, so once the frame's map was deleted, unlocking, renaming or showing it was refused with "no map '…'", which the general update path allowed. A change of only its name, visibility, lock or background now reads neither. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout/profile.rs | 41 +++++++++++++--------- crates/engine/src/tests/layout_profiles.rs | 7 ++++ 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/layout/profile.rs b/crates/engine/src/cmd/layout/profile.rs index ce492a8740..cf4e6ce5c8 100644 --- a/crates/engine/src/cmd/layout/profile.rs +++ b/crates/engine/src/cmd/layout/profile.rs @@ -261,25 +261,32 @@ pub(in crate::cmd::layout) fn update_profile(s: &mut Session, p: &Value, li: usi if boxed && (gives(p, "gap") || gives(p, "thickness")) { return Err("give a profile a gap and thickness, or x, y, w and h, not both".into()); } - let (mut new, mut held) = profile_params(s, l, p, current.clone())?; - let (_, _, frame_box) = frame_parts(s, l, new.frame)?; - if boxed { - // What isn't given is where it would sit now, on its side after this change. - let (x, y, w, h) = new.rect(frame_box); - let at = |k: &str, now: f64| given_num(p, k, "a number of mm").map(|v| v.unwrap_or(now)); - let rect = (at("x", x)?, at("y", y)?, at("w", w)?, at("h", h)?); - if new.take_rect(frame_box, rect) { - let ((g0, g1), (t0, t1)) = (PROFILE_GAPS, PROFILE_THICKNESSES); - held.push(format!("its gap held to {} ({g0} to {g1} mm) and thickness to {} ({t0} to {t1} mm)", new.gap, new.thickness)); - } - // Along its frame it keeps the frame's: what was given there and isn't that, said. - let along = if new.side.is_horizontal() { [("x", x), ("w", w)] } else { [("y", y), ("h", h)] }; - for (k, kept) in along { - if let Some(v) = f(p, k).filter(|v| (v - kept).abs() > 1e-9) { - held.push(format!("{k} {v} not used: along its frame a profile keeps the frame's ({kept})")); + // Only its name, visibility, lock or background: its frame and map aren't read, so one whose + // map was deleted can still be unlocked, renamed or shown. + let (new, held) = if boxed || PROFILE_KEYS.iter().any(|k| p.get(*k).is_some()) { + let (mut new, mut held) = profile_params(s, l, p, current.clone())?; + let (_, _, frame_box) = frame_parts(s, l, new.frame)?; + if boxed { + // What isn't given is where it would sit now, on its side after this change. + let (x, y, w, h) = new.rect(frame_box); + let at = |k: &str, now: f64| given_num(p, k, "a number of mm").map(|v| v.unwrap_or(now)); + let rect = (at("x", x)?, at("y", y)?, at("w", w)?, at("h", h)?); + if new.take_rect(frame_box, rect) { + let ((g0, g1), (t0, t1)) = (PROFILE_GAPS, PROFILE_THICKNESSES); + held.push(format!("its gap held to {} ({g0} to {g1} mm) and thickness to {} ({t0} to {t1} mm)", new.gap, new.thickness)); + } + // Along its frame it keeps the frame's: what was given there and isn't that, said. + let along = if new.side.is_horizontal() { [("x", x), ("w", w)] } else { [("y", y), ("h", h)] }; + for (k, kept) in along { + if let Some(v) = f(p, k).filter(|v| (v - kept).abs() > 1e-9) { + held.push(format!("{k} {v} not used: along its frame a profile keeps the frame's ({kept})")); + } } } - } + (new, held) + } else { + (current.clone(), Vec::new()) + }; let reread = ["section", "layer", "band", "side"].iter().any(|k| gives(p, k)); let l = s.project.layouts.get_mut(li).ok_or("no layout")?; let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?; diff --git a/crates/engine/src/tests/layout_profiles.rs b/crates/engine/src/tests/layout_profiles.rs index c4e6c1664e..5543ecaffe 100644 --- a/crates/engine/src/tests/layout_profiles.rs +++ b/crates/engine/src/tests/layout_profiles.rs @@ -159,6 +159,13 @@ fn a_profile_on_a_lost_band_still_takes_its_name_and_visibility() { assert_eq!((e.name.as_str(), e.visible, e.locked), ("Perfil", false, true)); let err = s.run("layout.update", &json!({"element": id, "locked": false, "band": 2})).unwrap_err(); assert!(err.contains("'DEM' has 1 band(s)"), "{err}"); + // Its frame's map deleted, the layout kept: it is still unlocked, renamed and shown. + if let Some(ElementKind::MapFrame { map, .. }) = s.project.layouts[0].element_mut(frame).map(|e| &mut e.kind) { + *map = "Gone".into(); + } + s.run("layout.update", &json!({"element": id, "locked": false, "name": "Perfil A", "visible": true})).unwrap(); + let e = s.project.layouts[0].element(id).unwrap(); + assert_eq!((e.name.as_str(), e.visible, e.locked), ("Perfil A", true, false)); } /// A profile is changed with `layout.update`: dragged along its frame and away from it, only its