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
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ layout.guides layout? x? y? clear?
layout.import path? text?
layout.move name? layout? to
layout.new name? page? orientation? width? height? template?
layout.page layout? page? orientation? width? height? decimal?
layout.page layout? page? orientation? width? height? decimal? color?
layout.publication profile? extent? name? title? subtitle? sources? reference? note? author? headings? locator? decimal? colorbar? veil? contextInLegend? northArrow? legendBox? style? accent? arrangement? coverage?
layout.remove name? layout?
layout.removeElement layout? element
Expand Down
10 changes: 8 additions & 2 deletions crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub fn commands() -> Vec<C> {
}).inputs(named_object_inputs).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"name"?: string, "layout"?: name|index (instead of name; default: the open layout), "newName"?: string (default: "<layout> copy")}"#),
C::new("layout.page", "Page Size", "Publish › Page Setup", page).inputs(object_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params(
r#"{"layout"?, "page"?: page id, "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "decimal"?: "."|"," (the decimal mark of the numbers its surrounds print)}"#,
r##"{"layout"?, "page"?: page id, "orientation"?: "landscape"|"portrait", "width"?: mm, "height"?: mm, "decimal"?: "."|"," (the decimal mark of the numbers its surrounds print), "color"?: "#RRGGBB" (the page's colour, painted under every element in the view and every export; opaque only; null or #FFFFFF: white, the default; left out: as it was)}"##,
),
C::new("layout.addFrame", "Map Frame", "Publish › Map Frames", add_frame).inputs(add_frame_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params(
r#"{"layout"?, "shape"?: "rectangle"|"circle"|"ellipse"|"polygon"|"lasso", "points"?: [[u, v], …] (polygon/lasso, 0..1 across the frame), "map"?: name, "x"?, "y"?, "w"?, "h"?: mm}"#,
Expand Down Expand Up @@ -3087,13 +3087,19 @@ fn page(s: &mut Session, p: &Value) -> CmdResult {
let cur = s.project.layouts.get(i).map(|l| (l.width, l.height));
let (w, h) = page_size(p, cur)?;
let comma = decimal_mark(p)?;
// The page's colour (#2855): absent keeps it, null or white gives the white page back.
let paper = super::opaque_color(p, "color")?;
let l = s.project.layouts.get_mut(i).ok_or("no layout")?;
l.width = w;
l.height = h;
if let Some(comma) = comma {
l.decimal_comma = comma;
}
Ok(json!({"width": w, "height": h, "decimal": if l.decimal_comma { "," } else { "." }}))
if let Some(paper) = paper {
l.paper = paper.filter(|c| *c != Rgba::rgb(0xFF, 0xFF, 0xFF));
}
let color = l.paper.map(Rgba::hex);
Ok(json!({"width": w, "height": h, "decimal": if l.decimal_comma { "," } else { "." }, "color": color}))
}

/// A sheet's footer of two columns, its right one moved to start where a legend at the right of the
Expand Down
18 changes: 18 additions & 0 deletions crates/engine/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,24 @@ pub(crate) fn saved_target(layer: &str, table: &str) -> String {
if layer == table { layer.to_string() } else { format!("{layer}: {table}") }
}

/// An opaque colour under `k`: absent `None`, null `Some(None)`, `"#RRGGBB"` `Some(Some(colour))`;
/// anything else, a translucent `#RRGGBBAA` included, refused. Six hex digits exactly: `from_hex`
/// alone would take a sign in a pair ("#+F0000").
pub(crate) fn opaque_color(p: &Value, k: &str) -> Result<Option<Option<rustgis_map::Rgba>>, String> {
match p.get(k) {
None => Ok(None),
Some(Value::Null) => Ok(Some(None)),
Some(Value::String(c)) => c
.trim()
.strip_prefix('#')
.filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))
.and_then(rustgis_map::Rgba::from_hex)
.map(|rgba| Some(Some(rgba)))
.ok_or_else(|| format!("{k} must be \"#RRGGBB\" (opaque), not '{c}'")),
Some(_) => Err(format!("{k} must be \"#RRGGBB\" or null")),
}
}

pub(crate) fn ps<'a>(p: &'a Value, k: &str) -> Option<&'a str> {
p.get(k).and_then(Value::as_str)
}
Expand Down
16 changes: 1 addition & 15 deletions crates/engine/src/cmd/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1307,21 +1307,7 @@ fn basemap(s: &mut Session, p: &Value) -> CmdResult {
let n = s_name(p)?;
let basemap = Basemap::from_code(n).ok_or_else(|| format!("unknown basemap '{n}'"))?;
// The blank basemap's paper (#2532): absent keeps it, null takes it off (white).
let paper = match p.get("color") {
None => None,
Some(Value::Null) => Some(None),
// Six hex digits: `from_hex` alone would take a sign in a pair ("#+F0000").
Some(Value::String(c)) => match c
.trim()
.strip_prefix('#')
.filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))
.and_then(rustgis_map::Rgba::from_hex)
{
Some(rgba) => Some(Some(rgba)),
None => return Err(format!("color must be \"#RRGGBB\" (opaque), not '{c}'")),
},
Some(_) => return Err("color must be \"#RRGGBB\" or null".into()),
};
let paper = super::opaque_color(p, "color")?;
let m = s.map_mut();
m.basemap = basemap;
// A built-in basemap takes the place of the web basemaps (tile overlays stay).
Expand Down
3 changes: 2 additions & 1 deletion crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ pub const CAPABILITIES: &[&str] = &[
"svg-markers",
"label-duplicates",
"tile-resampling",
"layout-page-color",
];
/// An offline area keeping the versions that lost a sync or a Bring Back
/// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them.
Expand Down Expand Up @@ -2795,7 +2796,7 @@ pub(crate) fn layout_notices(
let pages = total(|r| r.page_adjusted);
if pages > 0 {
notices.push(format!(
"{name}: the page size, guides or map series margin of {pages} layout(s) adjusted {when} (in {})",
"{name}: the page size, guides, page colour or map series margin of {pages} layout(s) adjusted {when} (in {})",
layout_names(repairs, |r| r.page_adjusted)
));
}
Expand Down
68 changes: 67 additions & 1 deletion crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("label-clearance", command_clears_labels),
("label-duplicates", command_removes_duplicate_labels),
("tile-resampling", command_resamples_tiles),
("layout-page-color", command_colours_the_page),
];

/// A saved `labels.placement` that has a class remove duplicates, read as the command reads it
Expand Down Expand Up @@ -289,6 +290,22 @@ fn command_uses_frame_border(id: &str, params: &Value) -> bool {
}
}

/// A `layout.page` command that gives the page a colour other than white (#2855), read as the
/// command reads it: an older reader ignores `color` and opens the page white. A `layout.import`
/// whose layout has one needs it too.
fn command_colours_the_page(id: &str, params: &Value) -> bool {
match id {
"layout.page" => crate::cmd::opaque_color(params, "color")
.is_ok_and(|c| c.flatten().is_some_and(|c| c != rustgis_map::Rgba::rgb(0xFF, 0xFF, 0xFF))),
"layout.import" => imported_layout(params, &["\"paper\""]).is_some_and(|mut l| {
l.clamp();
l.paper.is_some()
}),
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_colours_the_page)),
_ => false,
}
}

/// A `map.basemap` command that gives the blank basemap a paper colour (#2532): an older reader
/// ignores `color` and draws white. White, `null` or another basemap leaves no paper to keep.
fn command_uses_blank_paper(id: &str, params: &Value) -> bool {
Expand Down Expand Up @@ -557,12 +574,17 @@ fn command_uses_chart_outline(id: &str, params: &Value) -> bool {
/// backslash: JSON may spell a key with escapes (`"\u0063olor"`). It is read once, whatever its
/// keys.
fn imported_layout_uses(params: &Value, keys: &[&str], uses: fn(&rustgis_map::layout::Element) -> bool) -> bool {
imported_layout(params, keys).is_some_and(|l| l.elements.iter().any(uses))
}

/// A `layout.import`'s layout, read only when its text names one of `keys` (or escapes, which
/// could hide one).
fn imported_layout(params: &Value, keys: &[&str]) -> Option<rustgis_map::layout::Layout> {
params
.get("text")
.and_then(Value::as_str)
.filter(|t| keys.iter().any(|key| t.contains(key)) || t.contains('\\'))
.and_then(|t| serde_json::from_str::<rustgis_map::layout::Layout>(t).ok())
.is_some_and(|l| l.elements.iter().any(uses))
}

/// Require only executable payloads being saved: graph files omit steps, web tools omit graphs.
Expand Down Expand Up @@ -928,6 +950,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static
(elements().any(|e| e.kind.has_custom_border()), "layout-frame-border"),
(elements().any(|e| e.kind.has_custom_text_size()), "layout-text-size"),
(elements().any(bar_details), "layout-scale-bar-details"),
(layouts.iter().any(|l| l.paper.is_some()), "layout-page-color"),
]
.into_iter()
.filter_map(|(used, name)| used.then_some(name))
Expand Down Expand Up @@ -1225,6 +1248,7 @@ mod tests {
(&["label-clearance"], "labels.placement", json!({"clearance": 9})),
(&["label-duplicates"], "labels.placement", json!({"removeDuplicates": 20})),
(&["tile-resampling"], "map.addTiles", json!({"resampling": "nearest"})),
(&["layout-page-color"], "layout.page", json!({"color": "#0B1B2B"})),
// An SVG image is a picture marker as well, in a node as in a saved command.
(&["picture-markers", "svg-markers"], "layer.marker", json!({"image": svg})),
(&[], "buffer", json!({"input": "Cities", "distance": 1})),
Expand Down Expand Up @@ -2458,6 +2482,48 @@ mod tests {
assert!(Project::from_json(&unknown.to_string()).unwrap_err().contains("future-border"));
}

/// A layout's page colour (#2855) is required where it is saved, so an older reader refuses
/// the project instead of opening the page white and saving it so. A white page is not
/// written and needs nothing; neither do a saved layout.page that gives white or null.
#[test]
fn page_color_capability_follows_saved_layouts_and_commands() {
let fixture = Project::from_json(include_str!("../../../schema/fixtures/layout_page_color.rgis")).unwrap();
let saved = serde_json::to_value(&fixture).unwrap();
assert_eq!(saved["requires"], json!(["layout-page-color"]));
assert_eq!(saved["layouts"][0]["paper"], json!([11, 27, 43, 255]));
let mut clean = fixture;
clean.layouts[0].paper = None;
let base = serde_json::to_value(&clean).unwrap();
assert!(base.get("requires").is_none() && base["layouts"][0].get("paper").is_none(), "a white page needs nothing");
for (params, required) in [
(json!({"color": "#0B1B2B"}), true),
(json!({"color": " #0b1b2b "}), true),
(json!({"color": "#FFFFFF"}), false),
(json!({"color": "#ffffff"}), false),
(json!({"color": null}), false),
(json!({"orientation": "portrait"}), false),
] {
let script = format!("layout.page {params}");
for value in [
json!([{"name": "Task", "steps": [{"title": "Page", "command": "layout.page", "params": params}]}]),
json!([{"name": "Script", "steps": [{"title": "Page", "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();
let expected = if required { json!(["layout-page-color"]) } else { Value::Null };
assert_eq!(saved.get("requires").cloned().unwrap_or(Value::Null), expected, "{params}");
}
}
// An imported layout's text with a page colour needs it; a white one, none.
for (layout, required) in [(&saved["layouts"][0], true), (&base["layouts"][0], false)] {
let mut document = base.clone();
document["tasks"] = json!([{"name": "Task", "steps": [{"title": "Import", "command": "layout.import", "params": {"text": layout.to_string()}}]}]);
let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap();
assert_eq!(saved.get("requires").is_some(), required, "{layout}");
}
}

/// A legend's, scale bar's or grid's text size other than its default (#2581) is required
/// where it is saved, so an older reader refuses the project instead of drawing it at the
/// default and saving it so. Default sizes are not written and need nothing.
Expand Down
49 changes: 49 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19206,6 +19206,55 @@ fn a_globe_locator_keeps_the_blank_paper() {
assert_eq!(m.blank_paper(), Some(rustgis_map::Rgba::rgb(0xF1, 0xEA, 0xDF)));
}

/// A layout's page colour (#2855): set by layout.page, opaque #RRGGBB only, white or null giving
/// the white page back; painted under every element in the PNG and SVG exports, kept by
/// duplicate, undone in one step, and written only when it isn't white.
#[test]
fn a_layouts_page_takes_a_colour() {
let navy = rustgis_map::Rgba::rgb(0x0B, 0x1B, 0x2B);
let mut s = Session::new(Project::default());
s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "blank"})).unwrap();
let paper = |s: &Session| s.project.layouts.last().and_then(|l| l.paper);
assert_eq!(s.run("layout.page", &json!({})).unwrap()["color"], Value::Null, "white unless given");
let r = s.run("layout.page", &json!({"color": "#0B1B2B"})).unwrap();
assert_eq!((r["color"].clone(), paper(&s)), (json!("#0B1B2B"), Some(navy)));
s.run("layout.page", &json!({"orientation": "portrait"})).unwrap();
assert_eq!(paper(&s), Some(navy), "a page change without color keeps it");
// Painted under everything: a corner of the PNG and the SVG's page.
let dir = std::env::temp_dir().join(format!("rustgis-page-colour-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let png = dir.join("page.png");
s.run("layout.export", &json!({"path": png.display().to_string(), "dpi": 72})).unwrap();
let pm = crate::render::decode_png(&std::fs::read(&png).unwrap()).unwrap();
let corner = pm.pixel(3, 3).unwrap();
assert_eq!((corner.red(), corner.green(), corner.blue()), (0x0B, 0x1B, 0x2B));
let svg = dir.join("page.svg");
s.run("layout.export", &json!({"path": svg.display().to_string()})).unwrap();
let text = std::fs::read_to_string(&svg).unwrap();
let _ = std::fs::remove_dir_all(&dir);
assert!(text.contains(r##"fill="#0b1b2b"/>"##) && !text.contains(r##"fill="#ffffff"/>"##), "{text}");
// Saved with the layout, and kept by a duplicate.
let saved = serde_json::to_value(&s.project).unwrap();
assert_eq!(saved["layouts"][0]["paper"], json!([0x0B, 0x1B, 0x2B, 255]));
s.run("layout.duplicate", &json!({})).unwrap();
assert_eq!(paper(&s), Some(navy));
// Bad colours are refused and change nothing; translucent ones too (a page has nothing under it).
for bad in [json!("#0B1B2B80"), json!("0B1B2B"), json!("#+B1B2B"), json!("navy"), json!(3)] {
let e = s.run("layout.page", &json!({"color": bad})).unwrap_err();
assert!(e.contains("#RRGGBB"), "{bad}: {e}");
assert_eq!(paper(&s), Some(navy), "{bad}");
}
// White and null give the white page back, written as before (no key).
s.run("layout.page", &json!({"color": "#ffffff"})).unwrap();
assert_eq!(paper(&s), None, "white is the page's own");
s.run("edit.undo", &Value::Null).unwrap();
assert_eq!(paper(&s), Some(navy), "undone in one step");
s.run("layout.page", &json!({"color": null})).unwrap();
assert_eq!(paper(&s), None);
let saved = serde_json::to_value(&s.project).unwrap();
assert!(saved["layouts"].as_array().unwrap().last().unwrap().get("paper").is_none());
}

/// A blank basemap's paper colour (#2532): kept until null or another basemap, opaque #RRGGBB only,
/// a warning (not an error) when given with another basemap, and drawn in a layout's map frame.
#[test]
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/tests/layout_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ fn a_saved_layout_file_requires_what_its_elements_use_and_reads_back_the_same()
("border", include_str!("../../../../schema/fixtures/layout_frame_border.rgis")),
("legend-text", include_str!("../../../../schema/fixtures/layout_legend_text.rgis")),
("scale-grid-text", include_str!("../../../../schema/fixtures/layout_scale_grid_text.rgis")),
("page-color", include_str!("../../../../schema/fixtures/layout_page_color.rgis")),
("plain", include_str!("../../../../schema/fixtures/layout_no_data.rgis")),
] {
let project = Project::from_json(fixture).unwrap();
Expand Down
Loading
Loading