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 6f482b51be..77e928e6e0 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -305,7 +305,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? subtitle? 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? subtitle? 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 d48c0cf5bb..614ec75abb 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7570,6 +7570,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, @@ -7731,10 +7732,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; @@ -7752,6 +7753,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 88a808c7f9..5147169456 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -303,7 +303,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"?, "##, @@ -374,7 +374,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..cf4e6ce5c8 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> { @@ -118,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> { @@ -219,6 +232,85 @@ 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()); + } + // 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}"))?; + 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 +322,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 cf27dd6ad1..c641c97a78 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. @@ -860,17 +866,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 24f2dbf430..1fec72c952 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -578,12 +578,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)), @@ -1775,6 +1783,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..5543ecaffe 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).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(); @@ -47,23 +45,30 @@ 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 (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), 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 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(); 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 +145,71 @@ 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}"); + // 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 +/// 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)); + // 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)); + 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 +265,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).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/elements.rs b/crates/map/src/layout/elements.rs index d49ff916dd..67722baaa6 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -561,12 +561,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..5daf26f984 100644 --- a/crates/map/src/layout/profile.rs +++ b/crates/map/src/layout/profile.rs @@ -181,6 +181,24 @@ 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(); + // 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 /// cut. pub(super) fn clamp(&mut self) -> bool { @@ -191,9 +209,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..b927e570c3 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,28 @@ 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:?}"); + // 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/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..966246b7e6 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, Raster}; 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).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"); @@ -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).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(); @@ -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).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(); @@ -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).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); @@ -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).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)); @@ -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).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(dem(|_, _| 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; @@ -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 }).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(); @@ -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).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(); @@ -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).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")); @@ -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).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")); @@ -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 }).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(); @@ -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).unwrap())]).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 }).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(); @@ -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).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)); @@ -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).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/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..4555c2362d --- /dev/null +++ b/crates/render/src/testing.rs @@ -0,0 +1,29 @@ +//! Rasters the tests of this crate, and of the crates over it, draw and read layouts from (#2863). + +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; 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").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) -> 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/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 08f40da8b0..fdbda532cf 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 b46d0b27df..aeb443fcd5 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -344,6 +344,34 @@ 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 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; + 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 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