diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 2499fb3030..74d1bc35bb 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -282,7 +282,7 @@ layer.transparency layer? value layer.visibility layer? visible? layer.zoomTo layer? layout.activate name layout -layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? layerOrder? columns? textSize? classLabels? showCounts? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? +layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? layerOrder? columns? textSize? classLabels? showCounts? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? section? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? layout.addFrame layout? shape? points? map? x? y? w? h? layout.arrange layout? element to layout.arrangement favourite? save? arrangement? remove? diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 692d50b4b0..d74c40bec5 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -44,6 +44,8 @@ use legend::*; pub(crate) use legend::{legend_columns_param, legend_counts_param, legend_fit_param, legend_names_param}; mod page; use page::*; +mod profile; +use profile::*; mod publication; pub use publication::*; mod series; @@ -183,12 +185,12 @@ pub fn commands() -> Vec { C::new("layout.addElement", "Add Element", "Publish › Map Surrounds", add_element).inputs(element_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( concat!( r##"{"layout"?, "##, - r##""kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid"|"section" (a section line over a map frame, named at both ends, A and A', up to 26 a frame; as a grid or an extentIndicator, it adds no element: the reply's "element" is its frame, the one layout.update changes it on with "section", and "section" its name), "##, + r##""kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid"|"section" (a section line over a map frame, named at both ends, A and A', up to 26 a frame; as a grid or an extentIndicator, it adds no element: the reply's "element" is its frame, the one layout.update changes it on with "section", and "section" its name)|"profile" (a raster's profile along a section line of the frame, beside the frame on the side the line runs along, lined up with it: each sample is read at its point of the page line, through the frame's projection, so the curve is straight across from the place it comes from; its box is the frame's side, which it follows when the frame is moved or resized; a tilted frame, one on the globe, or a raster read in place draws none, which a notice and exports say), "##, r##""frame"?: element id (default: the first map frame), "##, r##""of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "##, 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"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; section, default #A8431F; scaleBar; legend, colorbar, table, chart: the ink of its text and lines, default #222222, a chart's bars and a colorbar's colours keeping theirs, and a table drawn without its white cells; refused for other kinds), "##, + r##""color"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; section, default #A8431F; scaleBar; legend, colorbar, table, chart, profile: the ink of its text and lines, default #222222, a chart's bars and a colorbar's colours keeping theirs, and a table drawn without its white cells; refused for other kinds), "##, r##""bold"?: bool (text), "##, r##""italic"?: bool, "##, r##""align"?: "left"|"center"|"right", "##, @@ -200,7 +202,7 @@ pub fn commands() -> Vec { r##""case"?: "none"|"upper"|"lower" (text, dynamicText: drawn in upper or lower case once its dynamic text is filled in, its text kept as typed; default none; refused for other kinds), "##, r##""font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "##, r##""fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "##, - r##""title"?: legend title (default "Legend"); chart: its own title ("" for none; default: its field, or the statistic of its field by the group), "##, + r##""title"?: legend title (default "Legend"); chart: its own title ("" for none; default: its field, or the statistic of its field by the group); profile: written over its curve ("" for none; default its layer's name), "##, r##""allClasses"?: bool (legend: every class, not only those the frame draws), "##, r##""hideOther"?: bool (legend: leave out ), "##, r##""showNoData"?: bool (legend: include Graduated Colors’ missing-value symbol; default false), "##, @@ -215,7 +217,7 @@ pub fn commands() -> Vec { r##""ticks"?: 2..21 (colorbar: labelled values, ends included), "##, r##""tickSide"?: "below"|"above"|"right"|"left" (colorbar), "##, r##""reverse"?: bool (colorbar: high values first), "##, - r##""fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white; refused for other kinds), "##, + r##""fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white; profile: under its curve, default #D8C8A8, null for none; refused for other kinds), "##, r##""width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid; section, 0.1 to 20, default 1.5), "##, r##""radius"?: mm, 0 to 50 (rectangle: rounded corners), "##, r##""dash"?: [points, …] (line, arrow, section, and a rectangle's, ellipse's or circle's outline: dash, gap, … in turn, as layer.lineStrokes takes it, at most 8, each 0 to 500; an arrow's heads stay solid; [] or null for solid; refused, null too, for other kinds), "##, @@ -225,7 +227,7 @@ pub fn commands() -> Vec { r##""length"?: mm (line, arrow), "##, r##""image"?: base64, "##, r##""path"?: picture file, "##, - r##""layer"?: (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists), "##, + r##""layer"?: (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists; profile: a raster layer held whole, not read in place, default the top one shown), "##, r##""field"?: (chart: a numeric field, default the layer's first; any field when it groups and counts, default then the field it groups by), "##, r##""label"?: a field (chart: each bar's label when not grouped), "##, r##""group"?: a field (chart: a bar per value of this field, its statistic of field over that value's features; blank values make one "(blank)" bar; default none, a bar per feature), "##, @@ -240,7 +242,7 @@ pub fn commands() -> Vec { r##""classes"?: bool (chart: each bar in the colour its features have on the map, by the layer's symbology classes: a bar per feature its feature's, a grouped bar the colour its features share; a bar whose features have several, which a warning counts, and an Other bar keep barColor; default false), "##, r##""labelAlign"?: "left" (the default)|"right" (chart: bars running across have their labels at the left of their column, or at its right against the bars), "##, r##""mirror"?: bool (chart: drawn as its mirror image, its text reading as ever: bars running across from the right, their labels at the right, or columns hanging from the top, their labels over them; beside a chart drawn the usual way the two face each other; default false), "##, - r##""max"?: a number above 0|"auto" (chart: the value at the far end of its bars' room, so charts given the same one share a scale; a bar past it runs to that end, which a warning counts; default "auto", its bars' own), "##, + r##""max"?: a number above 0|"auto" (chart: the value at the far end of its bars' room, so charts given the same one share a scale; a bar past it runs to that end, which a warning counts; default "auto", its bars' own; profile: any number, the value at its top, above "min"; default the samples' most, rounded up), "##, r##""hideLabels"?: bool (chart: its labels left out, their room given to the bars; default false), "##, r##""barOutline"?: {"color"?: "#RRGGBB"|"#RRGGBBAA" (default #222222), "width"?: points, 0 to 5 (default 0.5; 0 for none)} (chart: a line round each bar, or each stretch of a stacked one; default none) (label, group, statistic, order, bars, other, stack, values, decimals, barColor, classes, labelAlign, mirror, max, hideLabels and barOutline refused for other kinds unless null, as showNoData is, a scaleBar's decimals aside), "##, r##""rows"?, "##, @@ -261,8 +263,18 @@ pub fn commands() -> Vec { r##""name"?: a section's name, up to 20 characters, its frame's only one of that name (section, default the first free letter; a grid and an extent indicator refuse it, other kinds say they ignore it), "##, r##""direction"?: "horizontal" (the default)|"vertical" (section: across the whole frame, straight on the page, named at its left and right ends or its top and bottom ones; refused for other kinds), "##, r##""at"?: [longitude, latitude] (section: the place the line runs through and keeps to when the frame is moved, turned or rescaled, default the frame's centre; a line whose place is outside the frame isn't drawn, which a notice and exports say; refused for other kinds), "##, + r##""section"?: a section line's name (profile: the line it follows, default the frame's first; refused for other kinds), "##, + r##""band"?: 1-based (profile: the band read, default 1, its value whatever the raster holds), "##, + r##""side"?: "bottom"|"top" (profile of a horizontal section line, default bottom)|"left"|"right" (of a vertical one, default right), "##, + r##""gap"?: mm, 0 to 100 (profile: between the frame and it, default 3), "##, + r##""thickness"?: mm, 10 to 300 (profile: across it, default 30), "##, + r##""unit"?: text, one line, up to 100 characters (profile: after its value axis' numbers, such as "m"; default none), "##, + r##""lineColor"?: "#RRGGBB"|"#RRGGBBAA" (profile: its curve, default #3C3228), "##, + r##""lineWidth"?: points, 0.1 to 10 (profile: its curve, default 1), "##, + r##""min"?: number (profile: the value at its base; with "max", which must be above it, two profiles share a scale; default the samples' least, rounded down), "##, + r##""guides"?: bool (profile: lines at its value axis' numbers, default true), "##, r##""outline"?: "#RRGGBB" (northArrow, or a rectangle's, ellipse's or circle's outline instead of color; refused for other kinds), "##, - r##""units"?: "auto"|"kilometers"|"meters"|"miles"|"feet", "##, + r##""units"?: "auto"|"kilometers"|"meters"|"miles"|"feet" (scaleBar; profile: its distance axis, from the section line's A end along the ground), "##, r##""divisions"?: 1..10, at most 10 with divisionsBeforeZero together, more refused (scaleBar, whose "color" is its lines, dark divisions and labels, default #222222), "##, r##""subdivisions"?: 0..10 (scaleBar: parts the first division after zero is cut into, not labelled; 0 or 1 leaves it whole), "##, r##""divisionsBeforeZero"?: 0..2 (scaleBar: whole divisions left of zero, labelled with negatives, counted toward the ten in all with "divisions", more refused), "##, diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 1b671ab642..59ba6cd4a4 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -267,6 +267,10 @@ pub(crate) fn color(p: &Value, k: &str, d: Rgba) -> Result { pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResult { let kind = ps(p, "kind").ok_or("kind is required")?; + // A profile reads its own keys (#2863 part 2), several of them other kinds' too. + if kind == "profile" { + return add_profile(s, p); + } if kind != "legend" && kind != "scaleBar" && p.get("textSize").is_some_and(|v| !v.is_null()) { return Err(ONLY_LAYOUT_TEXT_SIZE.into()); } diff --git a/crates/engine/src/cmd/layout/inputs.rs b/crates/engine/src/cmd/layout/inputs.rs index 4a30ae108f..443305f5c1 100644 --- a/crates/engine/src/cmd/layout/inputs.rs +++ b/crates/engine/src/cmd/layout/inputs.rs @@ -81,6 +81,17 @@ pub(in crate::cmd::layout) fn series_page_inputs(input: &crate::cmd::InputContex pub(in crate::cmd::layout) fn element_inputs(input: &crate::cmd::InputContext<'_>, p: &Value) -> Result { let s = input; let kind = ps(p, "kind").ok_or("kind is required")?; + // A profile reads the raster it draws (#2863 part 2). + if kind == "profile" { + let layout = s.project.layouts.get(index(input, p)?).ok_or("no layout")?; + let frame = frame_of(layout, p)?; + let map = frame_map(input, layout, frame)?; + let name = added_profile_layer(map, p)?; + let mut inputs = crate::cmd::Inputs::named(map, [name.as_str()])?; + inputs.maps.push(map.instance_id()); + inputs.state = json!({"layout":index(input,p)?,"frame":frame}); + return Ok(inputs); + } if !matches!(kind, "table" | "chart" | "colorbar" | "legend") { let mut inputs = object_inputs(input, p)?; if matches!(kind, "northArrow" | "scaleBar" | "extentIndicator" | "grid" | "section") { diff --git a/crates/engine/src/cmd/layout/profile.rs b/crates/engine/src/cmd/layout/profile.rs new file mode 100644 index 0000000000..afbc7e3a61 --- /dev/null +++ b/crates/engine/src/cmd/layout/profile.rs @@ -0,0 +1,240 @@ +//! A raster's profile beside its map frame (#2863 part 2): what `layout.addElement` and +//! `layout.update` read for one, and what they say of it. + +use rustgis_map::layout::{ + MAX_PROFILE_BAND, MAX_PROFILE_TEXT, PROFILE_GAPS, PROFILE_LINE_WIDTHS, PROFILE_THICKNESSES, Profile, ProfileSide, +}; + +use super::*; + +/// The keys of a profile's own, which `layout.addElement` reads. +const PROFILE_KEYS: &[&str] = &[ + "section", + "layer", + "band", + "side", + "gap", + "thickness", + "title", + "unit", + "lineColor", + "lineWidth", + "fill", + "min", + "max", + "units", + "guides", + "color", +]; +/// What `layout.addElement` reads for a profile, besides [`PROFILE_KEYS`]. +const ADD_PROFILE_KEYS: &[&str] = &["layout", "kind", "frame", "background"]; + +/// 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> { + let e = l.element(frame).ok_or_else(|| format!("no element {frame}"))?; + let ElementKind::MapFrame { map, sections, .. } = &e.kind else { + return Err(format!("element {frame} isn't a map frame")); + }; + let m = s.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)).ok_or_else(|| format!("no map '{map}'"))?; + Ok((m, sections, (e.x, e.y, e.w, e.h))) +} + +/// Why `layer` can't be profiled, if it can't: a profile reads a raster held whole, as a remote or +/// tiled one read in place gives only the overview drawn, which changes with the scale. +fn not_held_whole(layer: &rustgis_map::Layer) -> Option { + let rl = layer.raster.as_ref()?; + let why = if rl.in_place || rl.tiled { + "is read in place, a part at a time" + } else if rl.data.as_ref().is_some_and(|r| r.overview.is_some()) { + "holds only an overview of its file" + } else { + return None; + }; + Some(format!("'{}' {why}: a profile reads a raster held whole", layer.name)) +} + +/// The raster layer of `map` named `name` (any case), as the map spells it, if a profile can read it. +fn profile_layer(map: &Map, name: &str) -> Result { + let layer = + map.layer_by_name(name).filter(|l| l.is_raster()).ok_or_else(|| format!("no raster layer '{}' in {}", name.trim(), map.name))?; + match not_held_whole(layer) { + Some(why) => Err(why), + None => Ok(layer.name.clone()), + } +} + +/// The top raster the map shows that a profile can read: a new profile's layer unless given one. +fn first_profile_layer(map: &Map) -> Result { + let found = map.layers.iter().filter(|l| l.is_raster() && map.shows(l)).find(|l| not_held_whole(l).is_none()); + found.map(|l| l.name.clone()).ok_or_else(|| format!("{} shows no raster a profile can read: give a layer", map.name)) +} + +/// The bands of `map`'s layer `name` when its pixels are read. +fn bands_of(map: &Map, name: &str) -> Option { + map.layer_by_name(name).and_then(|l| l.raster.as_ref()).and_then(|r| r.data.as_ref()).map(|r| r.bands.len()) +} + +/// A number given as `k`, or null for none, when `p` has it: `Some(None)` for null. +fn number_or_null(p: &Value, k: &str) -> Result>, String> { + match p.get(k) { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(v) => v.as_f64().filter(|v| v.is_finite()).map(|v| Some(Some(v))).ok_or_else(|| format!("{k} is a number, or null")), + } +} + +/// A profile with the options in `p` over `base`'s, in layout `l`, and what was held to its limits; +/// a bad value is an error, leaving nothing changed. +fn profile_params(s: &Session, l: &Layout, p: &Value, mut base: Profile) -> Result<(Profile, Vec), String> { + let (map, sections, _) = frame_parts(s, l, base.frame)?; + let mut held = Vec::new(); + if let Some(n) = given_name(p, "section", "a section line's name")? { + let found = Section::find(sections, n).and_then(|i| sections.get(i)); + base.section = found.map(|s| s.name.clone()).ok_or_else(|| format!("the frame has no section line '{}'", n.trim()))?; + } + let line = Section::find(sections, &base.section).and_then(|i| sections.get(i)).map(|s| s.line); + match given_name(p, "side", "bottom, top, left or right")? { + Some(v) => { + let side = ProfileSide::from_name(v).ok_or_else(|| format!("unknown side '{v}' (bottom, top, left or right)"))?; + if let Some(line) = line.filter(|line| !side.suits(*line)) { + let sides = if side.is_horizontal() { "left or right" } else { "bottom or top" }; + return Err(format!("a profile of a {} section line goes {sides} of its frame", line.code())); + } + base.side = side; + } + // Moved to a line running the other way, it goes to that line's side. + None => { + if let Some(line) = line.filter(|line| !base.side.suits(*line)) { + base.side = ProfileSide::default_for(line); + } + } + } + if let Some(n) = given_name(p, "layer", "a raster layer's name")? { + base.layer = profile_layer(map, n)?; + } + if let Some(v) = given_num(p, "band", "a band number from 1")? { + if v.fract() != 0.0 || v < 1.0 || v > f64::from(MAX_PROFILE_BAND) { + return Err(format!("band is a whole number from 1 to {MAX_PROFILE_BAND}")); + } + base.band = v as u32; + } + if let Some(n) = bands_of(map, &base.layer).filter(|n| base.band as usize > *n) { + 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> { + if let Some(n) = given_num(p, k, "a number of mm")? { + let kept = n.clamp(range.0, range.1); + if kept != n { + held.push(format!("{k} {n} held to {kept} ({} to {} mm)", range.0, range.1)); + } + *v = kept; + } + Ok(()) + }; + mm("gap", PROFILE_GAPS, &mut base.gap)?; + mm("thickness", PROFILE_THICKNESSES, &mut base.thickness)?; + for (k, text) in [("title", &mut base.title), ("unit", &mut base.unit)] { + if let Some(t) = given_name(p, k, "text")? { + let t = crate::cmd::within(k, "a profile's title or unit", t, MAX_PROFILE_TEXT)?; + if t.contains(['\n', '\r']) { + return Err(format!("{k} is one line")); + } + *text = t.trim().to_string(); + } + } + base.line_color = color(p, "lineColor", base.line_color)?; + if let Some(w) = given_num(p, "lineWidth", "a number of points")? { + let kept = w.clamp(PROFILE_LINE_WIDTHS.0, PROFILE_LINE_WIDTHS.1); + if kept != w { + held.push(format!("lineWidth {w} held to {kept} ({} to {} points)", PROFILE_LINE_WIDTHS.0, PROFILE_LINE_WIDTHS.1)); + } + base.line_width = kept; + } + match p.get("fill") { + None => {} + Some(Value::Null) => base.fill = None, + Some(_) => base.fill = Some(color(p, "fill", base.line_color)?), + } + if let Some(v) = number_or_null(p, "min")? { + base.min = v; + } + if let Some(v) = number_or_null(p, "max")? { + base.max = v; + } + if let (Some(lo), Some(hi)) = (base.min, base.max) + && lo >= hi + { + return Err(format!("min ({lo}) isn't below max ({hi}): the value axis runs from min at its base up to max")); + } + if let Some(v) = given_name(p, "units", "auto, kilometers, meters, miles or feet")? { + base.units = ScaleUnits::from_name(v).ok_or_else(|| format!("unknown units '{v}' (auto, kilometers, meters, miles or feet)"))?; + } + match p.get("guides").filter(|v| !v.is_null()) { + Some(Value::Bool(v)) => base.guides = *v, + Some(_) => return Err("guides is true or false".into()), + None => {} + } + if p.get("color").is_some() { + base.color = given_color(p, "color")?; + } + Ok((base, held)) +} + +/// `layout.addElement` for a profile (#2863 part 2): along a section line of its frame (its first +/// unless named), of a raster of the frame's map (the top one shown unless named), on the side the +/// line runs along, its box the frame's side ([`Profile::rect`]). +pub(in crate::cmd::layout) fn add_profile(s: &mut Session, p: &Value) -> CmdResult { + let keys: Vec<&str> = ADD_PROFILE_KEYS.iter().chain(PROFILE_KEYS).copied().collect(); + if ["x", "y", "w", "h"].iter().any(|k| gives(p, k)) { + return Err("a profile's box is its frame's side: give it a gap and a thickness (mm), not x, y, w or h".into()); + } + only_add_keys(p, "a profile", &keys, &["name"])?; + let background = match element_background(p, None)? { + BackgroundParam::Set(b) => Some(b), + BackgroundParam::Absent | BackgroundParam::Remove => None, + }; + let li = index(s, p)?; + let l = s.project.layouts.get(li).ok_or("no layout")?; + let frame = frame_of(l, p)?; + let (map, sections, frame_box) = frame_parts(s, l, frame)?; + let first = sections.first().ok_or("the frame has no section line: add one first (layout.addElement with kind section)")?; + let layer = if gives(p, "layer") { String::new() } else { first_profile_layer(map)? }; + let base = Profile::new(frame, first.name.clone(), layer, ProfileSide::default_for(first.line)); + let (mut new, held) = profile_params(s, l, p, base)?; + // Titled with its layer's name unless given one ("" for none), as a colorbar is. + if p.get("title").is_none_or(Value::is_null) { + new.title = new.layer.chars().take(MAX_PROFILE_TEXT).collect(); + } + let rect = new.rect(frame_box); + let l = s.project.layouts.get_mut(li).ok_or("no layout")?; + let id = l.add("Profile", rect, ElementKind::Profile(new)); + if let Some(e) = l.element_mut(id) { + e.background = background; + } + say_held(s, "Add Element", held); + if gives(p, "name") { + s.notify("Add Element ignores \"name\" for a profile: only a section takes one (layout.update names an element)", false); + } + say_profile_drawn(s, li, id); + Ok(json!({"element": id})) +} + +/// 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) { + let Some(l) = s.project.layouts.get(li) else { return }; + let notes = rustgis_render::layout::profiles_not_drawn(l, &s.project.maps); + let notes = notes.into_iter().filter(|n| n.element == id).map(|n| (n, 1)).collect(); + for note in rustgis_render::layout::profiles_notice(¬es, 1) { + s.warn(note); + } +} + +/// 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 { + match given_name(p, "layer", "a raster layer's name")? { + Some(n) => profile_layer(map, n), + None => first_profile_layer(map), + } +} diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 853a66410c..f4972b7e27 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -559,10 +559,12 @@ fn command_uses_section(id: &str, params: &Value) -> bool { } } -/// A layout command that brings in a profile beside a map frame (#2863 part 2): an older reader -/// refuses the kind `Profile` of a layout file. +/// 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. 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")), // 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)), @@ -1741,6 +1743,7 @@ mod tests { (&["layout-frame-border"], "layout.update", json!({"element": 1, "border": {}})), (&["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-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 4955fa910c..f58b9d1379 100644 --- a/crates/engine/src/tests/layout_profiles.rs +++ b/crates/engine/src/tests/layout_profiles.rs @@ -6,7 +6,7 @@ use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as Data}; use rustgis_geom::Coord; use rustgis_map::layout::{ElementKind, Profile, ProfileSide}; -use serde_json::json; +use serde_json::{Value, json}; /// A profile put beside the first frame of the session's first layout, and its id. fn put_profile(s: &mut Session, frame: u32, side: ProfileSide) -> u32 { @@ -70,6 +70,76 @@ fn said(s: &Session, mark: u64) -> Vec { s.notices_since(mark).iter().map(|n| n.text.clone()).collect() } +/// Profile `id` of the first layout, and its box (x, y, w, h). +fn profile(s: &Session, id: u64) -> (Profile, [f64; 4]) { + let e = s.project.layouts[0].element(id as u32).expect("the element"); + match &e.kind { + ElementKind::Profile(p) => (p.clone(), [e.x, e.y, e.w, e.h]), + _ => panic!("a profile"), + } +} + +/// Element `frame`'s box (x, y, w, h) in the first layout. +fn frame_box(s: &Session, frame: u32) -> [f64; 4] { + let e = s.project.layouts[0].element(frame).expect("the frame"); + [e.x, e.y, e.w, e.h] +} + +/// A profile is added along a section line of its frame (its first unless named), of the top +/// raster shown unless named, beside the frame on the side the line runs along; it follows the +/// frame when moved or resized, and goes with it; and all of it is undone. +#[test] +fn a_profile_is_added_follows_its_frame_and_is_undone() { + let (mut s, frame) = with_dem(); + let err = s.run("layout.addElement", &json!({"kind": "profile"})).unwrap_err(); + assert!(err.contains("the frame has no section line"), "{err}"); + // At 1:5,000,000 the line lies on the DEM end to end, so the profile has nothing to say. + s.run("layout.update", &json!({"element": frame, "scale": 5e6})).unwrap(); + s.run("layout.addElement", &json!({"kind": "section", "at": [10, 50]})).unwrap(); + let mark = s.notice_mark(); + let id = s.run("layout.addElement", &json!({"kind": "profile", "unit": "m", "layout": 0, "text": null})).unwrap()["element"] + .as_u64() + .unwrap(); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + let (p, at) = profile(&s, id); + assert_eq!( + (p.section.as_str(), p.layer.as_str(), p.side, p.title.as_str(), p.unit.as_str()), + ("A", "DEM", ProfileSide::Bottom, "DEM", "m") + ); + let [fx, fy, fw, fh] = frame_box(&s, frame); + assert_eq!(at, [fx, fy + fh + p.gap, fw, p.thickness]); + // Refused, nothing changed: a side across its line, a key it doesn't read, a box of its own. + for (bad, says) in [ + (json!({"kind": "profile", "side": "left"}), "goes bottom or top of its frame"), + (json!({"kind": "profile", "rows": 5}), "a profile takes no \"rows\""), + (json!({"kind": "profile", "x": 5}), "a profile's box is its frame's side"), + (json!({"kind": "profile", "layer": "Countries"}), "no raster layer 'Countries'"), + (json!({"kind": "profile", "band": 2}), "'DEM' has 1 band(s)"), + (json!({"kind": "profile", "band": 0}), "band is a whole number from 1"), + (json!({"kind": "profile", "min": 9, "max": 1}), "min (9) isn't below max (1)"), + (json!({"kind": "profile", "min": 5, "max": 5}), "min (5) isn't below max (5)"), + ] { + let err = s.run("layout.addElement", &bad).unwrap_err(); + assert!(err.contains(says), "{bad}: {err}"); + } + assert_eq!(s.project.layouts[0].elements.iter().filter(|e| e.kind.is_profile()).count(), 1); + // The frame moved and resized: the profile with it. + s.run("layout.update", &json!({"element": frame, "x": 20, "y": 30, "w": 120})).unwrap(); + let (p, at) = profile(&s, id); + assert_eq!(at, [20.0, 30.0 + fh + p.gap, 120.0, p.thickness]); + // Its frame removed, it goes with it; undone, both are back. + s.run("layout.removeElement", &json!({"element": frame})).unwrap(); + assert!(s.project.layouts[0].element(id as u32).is_none()); + s.run("edit.undo", &Value::Null).unwrap(); + assert!(s.project.layouts[0].element(id as u32).is_some()); + // Added beside a tilted frame, it says it isn't drawn, and why. + s.run("layout.update", &json!({"element": frame, "pitch": 40})).unwrap(); + let mark = s.notice_mark(); + s.run("layout.addElement", &json!({"kind": "profile"})).unwrap(); + let notes = said(&s, mark); + assert!(notes.len() == 1 && notes[0].contains("1 profile(s) not drawn") && notes[0].contains("tilted"), "{notes:?}"); +} + /// 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. diff --git a/docs/maintaining.md b/docs/maintaining.md index c10fe17765..00f90439fe 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -299,7 +299,8 @@ 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.import` whose `text` has one requires it as well. +`layout.addElement` of a profile requires it too. 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