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
118 changes: 82 additions & 36 deletions crates/engine/src/cmd/layout.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ pub const CAPABILITIES: &[&str] = &[
"blank-paper",
"layout-frame-border",
NATIVE_COORDINATES,
"layout-legend-text",
"label-guide",
];
/// A layer or table saved in a coordinate system of its own, not longitude/latitude
Expand Down
83 changes: 83 additions & 0 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ impl Project {
{
required.push("layout-frame-border");
}
if !required.contains(&"layout-legend-text")
&& self.layouts.iter().any(|l| l.elements.iter().any(|e| e.kind.has_custom_legend_text()))
{
required.push("layout-legend-text");
}
// A coordinate system whose PROJ definition, which an older reader reads, doesn't place
// points as its WKT does (angles in grads, a datum transformation the definition can't
// hold).
Expand Down Expand Up @@ -141,6 +146,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("layout-chart-stack", command_uses_chart_stack),
("blank-paper", command_uses_blank_paper),
("layout-frame-border", command_uses_frame_border),
("layout-legend-text", command_uses_legend_text),
];

/// A saved `map.graticule` that switches to the MGRS grid, its type read as the command reads it:
Expand Down Expand Up @@ -179,6 +185,24 @@ fn command_colors_graticule(id: &str, params: &Value) -> bool {
}
}

/// A layout command that gives a legend a text size other than the default (#2581): an older
/// reader warns that it ignores `textSize` and draws the legend at 9 points. `null` or 9 only give
/// the default, which an older reader's legends always have. A saved `layout.update` isn't told
/// which element it changes, so one this release refuses (on another kind) requires it too, as for
/// the other layout keys.
fn command_uses_legend_text(id: &str, params: &Value) -> bool {
let sized = || params.get("textSize").is_some_and(|v| !v.is_null() && v.as_f64() != Some(rustgis_map::layout::LEGEND_TEXT_PT));
match id {
"layout.addElement" => {
params.get("kind").and_then(Value::as_str).is_some_and(|k| k.trim().eq_ignore_ascii_case("legend")) && sized()
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}
"layout.update" => sized(),
"layout.import" => imported_layout_uses(params, "\"text_size\"", |e| e.kind.has_custom_legend_text()),
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_legend_text)),
_ => false,
}
}

/// A layout command that changes a map frame's border (#2557): an older reader warns that it
/// ignores `border` and draws the default one. `null` only gives the default back, which an older
/// reader's frames always have.
Expand Down Expand Up @@ -1461,6 +1485,65 @@ mod tests {
assert!(Project::from_json(&unknown.to_string()).unwrap_err().contains("future-border"));
}

/// A legend's text size other than the default (#2581) is required where it is saved, so an
/// older reader refuses the project instead of drawing the legend at 9 points and saving it so.
/// The default size is not written and needs nothing.
#[test]
fn legend_text_capability_follows_saved_layouts_and_commands() {
let fixture = Project::from_json(include_str!("../../../schema/fixtures/layout_legend_text.rgis")).unwrap();
let saved = serde_json::to_value(&fixture).unwrap();
assert_eq!(saved["requires"], json!(["layout-legend-text"]));
let elements = &saved["layouts"][0]["elements"];
assert!(elements[1]["kind"]["Legend"].get("text_size").is_none());
assert_eq!(elements[2]["kind"]["Legend"]["text_size"], json!(18.0));
let reopened = Project::from_json(&saved.to_string()).unwrap();
assert_eq!(reopened.layouts, fixture.layouts);
let mut clean = fixture;
for e in &mut clean.layouts[0].elements {
if let rustgis_map::layout::ElementKind::Legend { text_size, .. } = &mut e.kind {
*text_size = rustgis_map::layout::LEGEND_TEXT_PT;
}
}
let base = serde_json::to_value(&clean).unwrap();
assert!(base.get("requires").is_none(), "default sizes need nothing");
// A saved command that sizes a legend's text needs it; null or 9 only give the default.
for (id, params, required) in [
("layout.update", json!({"element": 2, "textSize": 18}), true),
("layout.update", json!({"element": 2, "textSize": null}), false),
("layout.update", json!({"element": 2, "textSize": 9}), false),
("layout.update", json!({"element": 2, "title": "Key"}), false),
("layout.addElement", json!({"kind": "legend", "textSize": 6}), true),
("layout.addElement", json!({"kind": "legend"}), false),
("layout.addElement", json!({"kind": "text", "text": "textSize", "size": 18}), false),
] {
let script = format!("{id} {params}");
for value in [
json!([{"name": "Task", "steps": [{"title": "Size", "command": id, "params": params}]}]),
json!([{"name": "Script", "steps": [{"title": "Size", "command": "script.run", "params": {"script": script}}]}]),
] {
let mut document = base.clone();
document["tasks"] = value;
let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap();
if required {
assert_eq!(saved["requires"], json!(["layout-legend-text"]), "{id} {params}");
} else {
assert!(saved.get("requires").is_none(), "{id} {params}");
}
}
}
// An imported layout's text with a sized legend needs it; with the default, none.
for (layout, required) in [(&saved["layouts"][0], true), (&base["layouts"][0], false)] {
let params = json!({"text": layout.to_string()});
let mut document = base.clone();
document["tasks"] = json!([{"name": "Task", "steps": [{"title": "Import", "command": "layout.import", "params": params}]}]);
let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap();
assert_eq!(saved.get("requires").is_some(), required, "{layout}");
}
let mut unknown = saved;
unknown["requires"] = json!(["layout-legend-text", "future-legend"]);
assert!(Project::from_json(&unknown.to_string()).unwrap_err().contains("future-legend"));
}

/// Nondefault relief effects survive project, map and layer files; ordinary relief needs none.
#[test]
fn relief_headers_cover_each_effect_and_clean_controls() {
Expand Down
109 changes: 109 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13262,6 +13262,115 @@ fn a_legend_takes_columns_from_one_to_three() {
}
}

/// `"textSize"` on a legend (#2581): given and changed, 4 to 100 points, null giving the default
/// back, refused out of that range, as anything but a number and on any other element (where
/// null is let through, as for `showNoData`); undone as any change; a size its box no longer
/// holds, or a box that no longer holds its size, says what it loses.
#[test]
fn a_legend_takes_a_text_size() {
use rustgis_map::layout::{ElementKind, LEGEND_TEXT_PT};
let dir = std::env::temp_dir().join(format!("rustgis-legend-text-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("a.geojson");
std::fs::write(
&path,
r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[4,4],[6,4],[6,6],[4,6],[4,4]]]}}]}"#,
)
.unwrap();
let mut s = Session::new(Project::default());
for _ in 0..4 {
s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap();
}
s.run("layout.new", &json!({"template": "map"})).unwrap();
let size = |s: &Session, id: u64| match s.project.layouts[0].element(id as u32).map(|e| &e.kind) {
Some(ElementKind::Legend { text_size, .. }) => *text_size,
other => panic!("{other:?}"),
};
let said = |s: &Session, mark: u64| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::<Vec<_>>().join(" | ");
let mark = s.notice_mark();
let added = s.run("layout.addElement", &json!({"kind": "legend", "x": 10, "y": 10, "w": 150, "h": 150})).unwrap();
let id = added["element"].as_u64().unwrap();
assert_eq!(size(&s, id), LEGEND_TEXT_PT);
let big = s.run("layout.addElement", &json!({"kind": "legend", "textSize": 18, "x": 10, "y": 10, "w": 150, "h": 150})).unwrap();
assert_eq!(size(&s, big["element"].as_u64().unwrap()), 18.0);
assert_eq!(said(&s, mark), "", "a box that holds it says nothing");
s.run("layout.update", &json!({"element": id, "textSize": 12.5})).unwrap();
assert_eq!(size(&s, id), 12.5);
s.run("layout.update", &json!({"element": id, "title": "Key"})).unwrap();
assert_eq!(size(&s, id), 12.5, "another change leaves it");
for edge in [4.0, 100.0] {
s.run("layout.update", &json!({"element": id, "textSize": edge})).unwrap();
assert_eq!(size(&s, id), edge);
}
s.run("layout.update", &json!({"element": id, "textSize": null})).unwrap();
assert_eq!(size(&s, id), LEGEND_TEXT_PT, "null gives the default back");
// Out of the range, or no number, it is refused, not drawn at another size, and the legend
// keeps its own.
for bad in [json!(3.9), json!(100.5), json!(1e6), json!("12"), json!(true), json!([9])] {
let err = s.run("layout.update", &json!({"element": id, "textSize": bad})).unwrap_err();
assert!(err.contains("textSize is a number of points, 4 to 100"), "{bad}: {err}");
assert_eq!(size(&s, id), LEGEND_TEXT_PT, "{bad}");
let err = s.run("layout.addElement", &json!({"kind": "legend", "textSize": bad})).unwrap_err();
assert!(err.contains("textSize is a number of points, 4 to 100"), "{bad}: {err}");
}
s.run("layout.update", &json!({"element": id, "textSize": 20})).unwrap();
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(size(&s, id), LEGEND_TEXT_PT, "undone");
let arrow = s.run("layout.addElement", &json!({"kind": "northArrow"})).unwrap();
let err = s.run("layout.addElement", &json!({"kind": "northArrow", "textSize": 12})).unwrap_err();
assert!(err.contains("only legends take textSize"), "{err}");
let err = s.run("layout.update", &json!({"element": arrow["element"], "textSize": 12})).unwrap_err();
assert!(err.contains("only legends take textSize"), "{err}");
// A null there is let through, as for showNoData: it asks for nothing.
s.run("layout.addElement", &json!({"kind": "northArrow", "textSize": null})).unwrap();
s.run("layout.update", &json!({"element": arrow["element"], "textSize": null})).unwrap();
// A locked legend takes no size, and null counts as a change there too.
s.run("layout.update", &json!({"element": id, "locked": true})).unwrap();
assert!(s.run("layout.update", &json!({"element": id, "textSize": null})).is_err());
s.run("layout.update", &json!({"element": id, "locked": false})).unwrap();
// Grown past what its box holds, in one column, it says what it loses; and the measure is the
// one it draws at: the same box holds the rows at 9 points.
s.run("layout.update", &json!({"element": id, "w": 40, "h": 40})).unwrap();
let mark = s.notice_mark();
s.run("layout.update", &json!({"element": id, "textSize": 40})).unwrap();
assert!(said(&s, mark).contains("its last rows or the ends of long labels are left out"), "{}", said(&s, mark));
let mark = s.notice_mark();
s.run("layout.update", &json!({"element": id, "textSize": 9})).unwrap();
assert_eq!(said(&s, mark), "");
// Added in a box too small for it: told whenever a text size is given, 9 included, as
// `"columns"` is; given nothing, it says nothing, as before.
for pt in [40, 9] {
let mark = s.notice_mark();
s.run("layout.addElement", &json!({"kind": "legend", "textSize": pt, "x": 10, "y": 10, "w": 5, "h": 5})).unwrap();
assert!(said(&s, mark).contains("are left out"), "{pt} pt: {}", said(&s, mark));
}
let mark = s.notice_mark();
s.run("layout.addElement", &json!({"kind": "legend", "x": 10, "y": 10, "w": 5, "h": 5})).unwrap();
assert_eq!(said(&s, mark), "", "nothing given, nothing said");
// With a size of its own, a box made too small for it says so too, in one column; at the
// default size a resize says nothing, as before.
s.run("layout.update", &json!({"element": id, "w": 150, "h": 150})).unwrap();
s.run("layout.update", &json!({"element": id, "textSize": 40})).unwrap();
let mark = s.notice_mark();
s.run("layout.update", &json!({"element": id, "w": 40, "h": 40})).unwrap();
assert!(said(&s, mark).contains("its last rows or the ends of long labels are left out"), "{}", said(&s, mark));
s.run("layout.update", &json!({"element": id, "textSize": null, "w": 150, "h": 150})).unwrap();
let mark = s.notice_mark();
s.run("layout.update", &json!({"element": id, "w": 40, "h": 40})).unwrap();
assert_eq!(said(&s, mark), "", "a default legend is told on a resize only in columns");
// `null` columns or missing-value row changes nothing and says nothing; a `null` text size gives
// 9 points back and is told, as a new size is.
let mark = s.notice_mark();
s.run("layout.update", &json!({"element": id, "columns": null, "showNoData": null})).unwrap();
assert_eq!(said(&s, mark), "", "nothing changed, nothing said");
s.run("layout.update", &json!({"element": id, "textSize": 40, "w": 150, "h": 150})).unwrap();
s.run("layout.update", &json!({"element": id, "w": 5, "h": 5})).unwrap();
let mark = s.notice_mark();
s.run("layout.update", &json!({"element": id, "textSize": null})).unwrap();
assert!(said(&s, mark).contains("are left out"), "{}", said(&s, mark));
let _ = std::fs::remove_dir_all(&dir);
}

/// A legend given `"columns"` says when its box doesn't hold them, and only then.
#[test]
fn a_legends_columns_say_when_its_box_is_too_small() {
Expand Down
69 changes: 66 additions & 3 deletions crates/map/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,26 @@ fn is_one_column(columns: &usize) -> bool {
*columns == 1
}

/// A legend's text size until it is set (#2581), in points: its layers' names and classes'
/// labels, as legends have always drawn them.
pub const LEGEND_TEXT_PT: f64 = 9.0;
/// The sizes a legend's text takes, in points.
pub const LEGEND_TEXT_SIZE: std::ops::RangeInclusive<f64> = 4.0..=100.0;

/// A legend's text size kept within [`LEGEND_TEXT_SIZE`], [`LEGEND_TEXT_PT`] when it is no number:
/// what a layout opened and the drawing take, so they agree (a command refuses one out of range).
pub fn legend_text_in_range(pt: f64) -> f64 {
finite_or(pt, LEGEND_TEXT_PT).clamp(*LEGEND_TEXT_SIZE.start(), *LEGEND_TEXT_SIZE.end())
}

fn legend_text_pt() -> f64 {
LEGEND_TEXT_PT
}

fn is_legend_text_pt(size: &f64) -> bool {
*size == LEGEND_TEXT_PT
}

/// The dark grey a scale bar draws in by default, and a legend, colorbar, table or chart without
/// an ink of its own ([`ElementKind::ink`]).
pub const INK: Rgba = Rgba::rgb(0x22, 0x22, 0x22);
Expand Down Expand Up @@ -989,6 +1009,12 @@ pub enum ElementKind {
/// when none, so layouts saved before keep their bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
color: Option<Rgba>,
/// The size of its layers' names and its classes' labels, in points, within
/// [`LEGEND_TEXT_SIZE`] (#2581): its title, rows, swatches and gaps follow in proportion,
/// a point symbol keeping the size the map draws it at. [`LEGEND_TEXT_PT`] unless set,
/// and left out then, so layouts saved before keep their bytes.
#[serde(default = "legend_text_pt", skip_serializing_if = "is_legend_text_pt")]
text_size: f64,
},
/// The colour scale of a raster layer in a frame's map: a gradient bar for a stretch, steps
/// for classes, a block per value for unique values and colour tables (#326).
Expand Down Expand Up @@ -1417,9 +1443,12 @@ impl ElementKind {
}

/// Whether `key` given as null changes an element of this kind, giving it back its default:
/// an ink's `color`, and a chart's `title` (the title it is given) and `barColor`.
/// an ink's `color`, a chart's `title` (the title it is given) and `barColor`, and a legend's
/// `textSize` (#2581).
pub fn null_resets(&self, key: &str) -> bool {
(self.takes_ink() && key == "color") || (matches!(self, ElementKind::Chart { .. }) && matches!(key, "title" | "barColor"))
(self.takes_ink() && key == "color")
|| (matches!(self, ElementKind::Chart { .. }) && matches!(key, "title" | "barColor"))
|| (matches!(self, ElementKind::Legend { .. }) && key == "textSize")
}

/// Its ink, when it [takes one](ElementKind::takes_ink) and has one; `None` draws in [`INK`].
Expand All @@ -1444,6 +1473,11 @@ impl ElementKind {
}
}

/// Whether it is a legend whose text isn't the default size (#2581).
pub fn has_custom_legend_text(&self) -> bool {
matches!(self, ElementKind::Legend { text_size, .. } if !is_legend_text_pt(text_size))
}

/// Whether it is a map frame whose border isn't the default one (#2557).
pub fn has_custom_border(&self) -> bool {
matches!(self, ElementKind::MapFrame { border_color, border_width, .. }
Expand Down Expand Up @@ -2481,7 +2515,8 @@ impl Layout {
g.width = finite_or(g.width, grid_width()).clamp(0.0, MAX_GRID_WIDTH);
}
}
ElementKind::Legend { exclude, columns, labels, .. } => {
ElementKind::Legend { exclude, columns, labels, text_size, .. } => {
*text_size = legend_text_in_range(*text_size);
// Names stay whole: a layer's own name isn't cut, and a cut one would no
// longer match it.
cut |= exclude.len() > MAX_LEGEND_EXCLUDED;
Expand Down Expand Up @@ -3545,6 +3580,34 @@ mod tests {
assert!(l.element(t).is_some());
}

/// A legend's text size (#2581): 9 points unless set, and left out then, so a layout saved
/// before keeps its bytes; one past its range is brought into it, and counted.
#[test]
fn a_legends_text_size_defaults_and_is_kept_in_range() {
let page = |legend: &str| {
format!(
r#"{{"name":"x","width":297,"height":210,"elements":[
{{"id":1,"name":"f","x":0,"y":0,"w":100,"h":100,"kind":{{"MapFrame":{{"map":"M","center":{{"x":0,"y":0}},"scale":1e6}}}}}},
{{"id":2,"name":"l","x":0,"y":0,"w":50,"h":50,"kind":{{"Legend":{legend}}}}}]}}"#
)
};
let size = |l: &Layout| match &l.elements[1].kind {
ElementKind::Legend { text_size, .. } => *text_size,
_ => panic!("legend expected"),
};
let old: Layout = serde_json::from_str(&page(r#"{"frame":1,"title":"L"}"#)).unwrap();
assert_eq!(size(&old), LEGEND_TEXT_PT);
assert!(!old.elements[1].kind.has_custom_legend_text());
assert!(!serde_json::to_string(&old).unwrap().contains("text_size"), "the default isn't written");
let mut big: Layout = serde_json::from_str(&page(r#"{"frame":1,"title":"L","text_size":1e9}"#)).unwrap();
assert_eq!(big.clamp().elements_adjusted, 1);
assert_eq!(size(&big), *LEGEND_TEXT_SIZE.end());
assert!(big.elements[1].kind.has_custom_legend_text());
let saved = serde_json::to_string(&big).unwrap();
assert!(saved.contains(r#""text_size":100.0"#), "{saved}");
assert_eq!(serde_json::from_str::<Layout>(&saved).unwrap(), big);
}

#[test]
fn hostile_layouts_are_repaired() {
let text = r#"{"name":"x","width":1e300,"height":-5,"elements":[
Expand Down
Loading
Loading