Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions crates/engine/src/cmd/layout/chart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,21 @@ pub(in crate::cmd::layout) fn given_count(p: &Value, k: &str, hi: usize) -> Resu
}
}

/// A choice given as `k` by name, when it's given (and not null): an error when it isn't one of
/// `names`.
pub(in crate::cmd::layout) fn given_choice<T>(p: &Value, k: &str, from: fn(&str) -> Option<T>, names: &str) -> Result<Option<T>, String> {
/// The name given as `k`, when it's given (and not null): an error when it's not text. The caller
/// says which name it doesn't know, in its own words.
pub(in crate::cmd::layout) fn given_name<'a>(p: &'a Value, k: &str, names: &str) -> Result<Option<&'a str>, String> {
match p.get(k).filter(|v| !v.is_null()) {
Some(v) => v.as_str().and_then(from).map(Some).ok_or_else(|| format!("{k} is {names}")),
Some(v) => v.as_str().map(Some).ok_or_else(|| format!("{k} is {names}")),
None => Ok(None),
}
}

/// A choice given as `k` by name, when it's given (and not null): an error when it isn't one of
/// `names`.
pub(in crate::cmd::layout) fn given_choice<T>(p: &Value, k: &str, from: fn(&str) -> Option<T>, names: &str) -> Result<Option<T>, String> {
given_name(p, k, names)?.map(|v| from(v).ok_or_else(|| format!("{k} is {names}"))).transpose()
}

/// A chart's options beyond its layer and field ([`ElementKind::Chart`], #2487).
pub(in crate::cmd::layout) struct ChartOptions {
pub(in crate::cmd::layout) label: Option<String>,
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/layout/elements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ pub(in crate::cmd::layout) fn orientation(p: &Value) -> Result<Option<Orientatio
}

pub(in crate::cmd::layout) fn orientation_of(p: &Value, key: &str) -> Result<Option<Orientation>, String> {
match ps(p, key).map(|o| o.trim().to_ascii_lowercase()) {
match given_name(p, key, "horizontal or vertical")?.map(|o| o.trim().to_ascii_lowercase()) {
None => Ok(None),
Some(o) if o == "horizontal" => Ok(Some(Orientation::Horizontal)),
Some(o) if o == "vertical" => Ok(Some(Orientation::Vertical)),
Expand Down
12 changes: 6 additions & 6 deletions crates/engine/src/cmd/layout/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub(in crate::cmd::layout) fn grid_params(p: &Value, base: Grid) -> Result<Grid,
let mut g = base;
// A graticule or a measured grid; a change of type without a step picks one, as degrees and
// metres don't carry over.
if let Some(v) = ps(p, "type") {
if let Some(v) = given_name(p, "type", "graticule or measured")? {
let kind = GridKind::from_name(v).ok_or_else(|| format!("unknown grid type '{v}' (graticule or measured)"))?;
if kind != g.kind {
g.kind = kind;
Expand Down Expand Up @@ -116,7 +116,7 @@ pub(in crate::cmd::layout) fn grid_params(p: &Value, base: Grid) -> Result<Grid,
rustgis_map::graticule::short_crs(c)
));
}
if let Some(v) = f(p, "step") {
if let Some(v) = given_num(p, "step", "a number of degrees or metres")? {
g.step = match g.kind {
GridKind::Graticule => v.clamp(0.0, rustgis_map::layout::MAX_GRATICULE_STEP),
// (0 picks one; a step below a metre is a metre.)
Expand All @@ -128,16 +128,16 @@ pub(in crate::cmd::layout) fn grid_params(p: &Value, base: Grid) -> Result<Grid,
if let Some(v) = b(p, "labels") {
g.labels = v;
}
if let Some(v) = ps(p, "style") {
if let Some(v) = given_name(p, "style", "lines, ticks or linesAndTicks")? {
g.style = GridStyle::from_name(v).ok_or_else(|| format!("unknown grid style '{v}' (lines, ticks or linesAndTicks)"))?;
}
if let Some(v) = f(p, "tickLength") {
if let Some(v) = given_num(p, "tickLength", "a number of mm")? {
g.tick_length = v.clamp(0.0, MAX_TICK_MM);
}
if let Some(v) = f(p, "width") {
if let Some(v) = given_num(p, "width", "a number of points")? {
g.width = v.clamp(0.0, MAX_GRID_WIDTH);
}
if let Some(v) = ps(p, "format") {
if let Some(v) = given_name(p, "format", "decimal or dms")? {
g.format = CoordFormat::from_name(v).ok_or_else(|| format!("unknown format '{v}' (decimal or dms)"))?;
}
if let Some(v) = b(p, "hemisphere") {
Expand Down
12 changes: 5 additions & 7 deletions crates/engine/src/cmd/layout/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result<O
if ["style", "fill", "outline"].iter().all(|k| p.get(k).is_none()) {
return Ok(None);
}
let style = match ps(p, "style") {
let style = match given_name(p, "style", "classic, compass, triangle or star")? {
Some(v) => ArrowStyle::from_name(v)
.ok_or_else(|| format!("unknown north arrow style '{v}' (classic, compass, triangle or star)"))?,
None => *style,
Expand Down Expand Up @@ -44,22 +44,20 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result<O
if SCALE_BAR_LOOK_KEYS.iter().chain(SCALE_BAR_KEYS.iter()).all(|k| p.get(k).is_none()) {
return Ok(None);
}
let style = match ps(p, "style") {
let style = match given_name(p, "style", "alternating, stepped or line")? {
Some(v) => {
ScaleBarStyle::from_name(v).ok_or_else(|| format!("unknown scale bar style '{v}' (alternating, stepped or line)"))?
}
None => *style,
};
let units = match ps(p, "units") {
let units = match given_name(p, "units", "auto, kilometers, meters, miles or feet")? {
Some(v) => {
ScaleUnits::from_name(v).ok_or_else(|| format!("unknown units '{v}' (auto, kilometers, meters, miles or feet)"))?
}
None => *units,
};
let divisions = match p.get("divisions") {
Some(_) => f(p, "divisions").ok_or("divisions is a number")?.round().clamp(1.0, MAX_SCALE_DIVISIONS as f64) as usize,
None => *divisions,
};
let divisions =
given_num(p, "divisions", "a number")?.map_or(*divisions, |n| n.round().clamp(1.0, MAX_SCALE_DIVISIONS as f64) as usize);
let (color, fill) = (color(p, "color", *c)?, color(p, "fill", *fill)?);
let text_size = text_size_param(p, "textSize", SCALE_BAR_TEXT_PT)?.unwrap_or(*text_size);
// Its details, each read before any is set: one part is the division whole.
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ mod layout_edge;
#[path = "tests/layout_publication_parts.rs"]
mod layout_publication_parts;

#[path = "tests/layout_typed_values.rs"]
mod layout_typed_values;

#[path = "tests/sde_connections.rs"]
mod sde_connections;

Expand Down
144 changes: 144 additions & 0 deletions crates/engine/src/tests/layout_typed_values.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
//! A grid, scale bar or north arrow value of the wrong type is refused, not ignored (#3110).

use super::*;
use rustgis_map::layout::{Element, ElementKind, Grid};

/// A layout with a map frame, a grid on it, a scale bar and a north arrow.
fn laid_out() -> Session {
let mut s = world();
s.run("layout.new", &json!({"template": "map"})).unwrap();
for kind in ["grid", "scaleBar", "northArrow"] {
s.run("layout.addElement", &json!({"kind": kind})).unwrap();
}
s
}

fn elements(s: &Session) -> &[Element] {
&s.project.layouts[0].elements
}

/// The id of the last element of the kind `is` picks.
fn id(s: &Session, is: fn(&ElementKind) -> bool) -> u64 {
elements(s).iter().rev().find(|e| is(&e.kind)).unwrap().id.into()
}

fn frame(s: &Session) -> u64 {
id(s, |k| matches!(k, ElementKind::MapFrame { .. }))
}

fn grid(s: &Session) -> Grid {
elements(s)
.iter()
.find_map(|e| match &e.kind {
ElementKind::MapFrame { grid, .. } => grid.clone(),
_ => None,
})
.unwrap()
}

/// Runs `command` with `params` and expects it refused naming `said`, with nothing changed and no
/// undo step.
fn refused(s: &mut Session, command: &str, params: Value, said: &str) {
let before = serde_json::to_value(&s.project).unwrap();
let undo = s.undo_label();
let err = s.run(command, &params).expect_err(&params.to_string());
assert!(err.contains(said), "{params}: {err}");
assert_eq!(serde_json::to_value(&s.project).unwrap(), before, "{params}");
assert_eq!(s.undo_label(), undo, "{params}");
}

fn wrong() -> [Value; 4] {
[json!(17), json!(true), json!([]), json!({})]
}

#[test]
fn a_grid_name_of_the_wrong_type_is_refused() {
let mut s = laid_out();
let frame = frame(&s);
for key in ["type", "style", "format", "labelOrientation"] {
for v in wrong() {
let mut add = json!({"kind": "grid"});
add[key] = v.clone();
refused(&mut s, "layout.addElement", add, &format!("{key} is "));
let mut options = json!({});
options[key] = v;
refused(&mut s, "layout.update", json!({"element": frame, "grid": options}), &format!("{key} is "));
}
}
}

#[test]
fn a_grid_number_of_the_wrong_type_is_refused() {
let mut s = laid_out();
let frame = frame(&s);
for key in ["step", "tickLength", "width"] {
for v in [json!("bad"), json!(""), json!(true), json!([]), json!({})] {
let mut add = json!({"kind": "grid"});
add[key] = v.clone();
refused(&mut s, "layout.addElement", add, &format!("{key} is "));
let mut options = json!({});
options[key] = v;
refused(&mut s, "layout.update", json!({"element": frame, "grid": options}), &format!("{key} is "));
}
}
}

#[test]
fn a_scale_bar_or_north_arrow_value_of_the_wrong_type_is_refused() {
let mut s = laid_out();
let bar = id(&s, |k| matches!(k, ElementKind::ScaleBar { .. }));
let arrow = id(&s, |k| matches!(k, ElementKind::NorthArrow { .. }));
for v in wrong() {
for (kind, element, key) in [("scaleBar", bar, "style"), ("scaleBar", bar, "units"), ("northArrow", arrow, "style")] {
let mut add = json!({"kind": kind});
add[key] = v.clone();
refused(&mut s, "layout.addElement", add, &format!("{key} is "));
let mut update = json!({"element": element});
update[key] = v.clone();
refused(&mut s, "layout.update", update, &format!("{key} is "));
}
}
}

#[test]
fn a_publication_part_value_of_the_wrong_type_is_refused_and_nothing_is_made() {
for (part, key) in [("grid", "type"), ("grid", "step"), ("scaleBar", "units"), ("scaleBar", "style"), ("northArrow", "style")] {
let mut s = world();
let mut options = json!({});
options[key] = json!([17]);
let mut p = json!({"profile": "a4-portrait", "extent": [-30.0, -30.0, -20.0, -22.0]});
p[part] = options;
refused(&mut s, "layout.publication", p, &format!("{key} is "));
}
}

#[test]
fn a_null_value_is_not_given() {
let mut s = laid_out();
let (frame, before) = (frame(&s), grid(&s));
let nulls =
json!({"type": null, "style": null, "format": null, "labelOrientation": null, "step": null, "tickLength": null, "width": null});
s.run("layout.update", &json!({"element": frame, "grid": nulls})).unwrap();
assert_eq!(grid(&s), before);
let bar = id(&s, |k| matches!(k, ElementKind::ScaleBar { .. }));
let kept = serde_json::to_value(elements(&s)).unwrap();
s.run("layout.update", &json!({"element": bar, "style": null, "units": null, "divisions": null})).unwrap();
assert_eq!(serde_json::to_value(elements(&s)).unwrap(), kept);
}

#[test]
fn a_number_given_as_text_and_a_known_name_are_read_as_before() {
let mut s = laid_out();
let frame = frame(&s);
s.run("layout.update", &json!({"element": frame, "grid": {"step": " 5 ", "style": "ticks", "tickLength": "3"}})).unwrap();
let g = grid(&s);
assert_eq!((g.step, g.tick_length, g.style.code()), (5.0, 3.0, "ticks"));
let mut s = laid_out();
refused(&mut s, "layout.addElement", json!({"kind": "grid", "style": "wavy"}), "unknown grid style 'wavy'");
}

#[test]
fn a_colorbar_orientation_of_the_wrong_type_is_refused() {
let mut s = laid_out();
refused(&mut s, "layout.addElement", json!({"kind": "colorbar", "orientation": 17}), "orientation is ");
}
Loading