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
7 changes: 5 additions & 2 deletions apps/rustgis-python/python/rustgis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -681,13 +681,16 @@ def bounds(self) -> Tuple[float, float, float, float]:
"""What the map shows, as ``(west, south, east, north)`` in degrees."""
return tuple(self.info()["extent"]) # type: ignore[return-value]

def set_basemap(self, name: str) -> Any:
def set_basemap(self, name: str, color: Optional[str] = None) -> Any:
"""Sets the map's basemap.

Args:
name: ``"paper"``, ``"midnight"``, ``"ocean"``, ``"atlas"`` or ``"blank"``.
color: The blank basemap's paper colour, ``"#RRGGBB"`` (left as it was when not given).
"""
return self.run("map.basemap", name=name)
if color is None:
return self.run("map.basemap", name=name)
return self.run("map.basemap", name=name, color=color)

def set_center(
self,
Expand Down
7 changes: 7 additions & 0 deletions apps/rustgis-python/tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,13 @@ def test_the_view(sample):
assert abs(sample.info()["center"]["lon"] - 114.17) < 0.01
sample.set_basemap("paper")
assert sample.info()["basemap"] == "paper"
# The blank basemap's paper colour (#2532); with another basemap it is a warning.
sample.set_basemap("blank", color="#F1EADF")
assert sample.info()["basemap"] == "blank"
assert "blank basemap only" in sample.set_basemap("paper", color="#F1EADF")["warning"]
assert sample.info()["basemap"] == "paper"
with pytest.raises(rustgis.RustGISError, match="RRGGBB"):
sample.set_basemap("blank", color="cream")



Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1953,7 +1953,7 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult {
// Not its web tiles (fetched and drawn over the basemap on the disc), swipe, time
// slider, layer groups (their hidden layers left out here), bookmarks or animation.
let mut m = rustgis_map::Map::new(name);
m.basemap = src.basemap;
(m.basemap, m.paper) = (src.basemap, src.paper);
m.graticule = src.graticule;
m.body = src.body.clone();
m.set_projection(rustgis_map::Projection::Globe);
Expand Down
35 changes: 32 additions & 3 deletions crates/engine/src/cmd/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub fn commands() -> Vec<C> {
.view()
.params(r#"{"scale": number}"#),
C::new("map.basemap", "Basemap", "Home › Add", basemap).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"name": "paper"|"midnight"|"ocean"|"atlas"|"blank", "keepTiles"?: bool (keeps the web tile basemaps over it)}"#),
.params(r##"{"name": "paper"|"midnight"|"ocean"|"atlas"|"blank", "keepTiles"?: bool (keeps the web tile basemaps over it), "color"?: "#RRGGBB" (blank: the paper's colour, drawn where a blank map draws white, the tilted view's sky included; null or #FFFFFF: white; default: as it was. Another basemap takes the paper off and keeps its own colours; a color given with it is said as a warning)}"##),
C::new("map.graticule", "Graticule", "View › Display", graticule).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"on"?: bool (toggles when omitted, on when a type or crs is given), "type"?: "degrees"|"measured"|"utm", "crs"?: a projected system for the measured grid (EPSG:2056, WKT or a PROJ string; "" or null: the map's own when projected, else the UTM zone at the view's centre)}"#),
C::new("map.reloadWebLayers", "Reload Web Layers", "View › Display", |_, _| {
Expand Down Expand Up @@ -924,12 +924,41 @@ fn graticule(s: &mut Session, p: &Value) -> CmdResult {

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 m = s.map_mut();
m.basemap = Basemap::from_code(n).ok_or_else(|| format!("unknown basemap '{n}'"))?;
m.basemap = basemap;
// A built-in basemap takes the place of the web basemaps (tile overlays stay).
if !super::b(p, "keepTiles").unwrap_or(false) {
m.tiles.retain(|t| t.overlay);
}
if basemap != Basemap::Blank {
// Another basemap draws its own colours: the paper goes, not to be saved unseen.
m.paper = None;
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
if paper.is_some_and(|c| c.is_some()) {
let warning = format!("color is for the blank basemap only: {} keeps its own colours", basemap.label());
s.warn(&warning);
return Ok(json!({"warning": warning}));
}
} else if let Some(paper) = paper {
// White is the blank basemap's own paper: nothing to keep, or to require of a reader.
m.paper = paper.filter(|c| *c != rustgis_map::Rgba::rgb(0xFF, 0xFF, 0xFF));
}
Ok(Value::Null)
}

Expand Down Expand Up @@ -1180,7 +1209,7 @@ fn new_map(s: &mut Session, p: &Value) -> CmdResult {
name = format!("{base}{i}");
}
let mut m = Map::new(name.clone());
m.basemap = s.map().basemap;
(m.basemap, m.paper) = (s.map().basemap, s.map().paper);
s.project.maps.push(m);
s.project.active_map = s.project.maps.len() - 1;
s.active_layer = None;
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ pub const CAPABILITIES: &[&str] = &[
"offline-map-area-id",
"crs-wkt",
"zarr-window",
"blank-paper",
];
/// Independent marker sizes alongside classified point colours (`Layer::size_by`).
pub(crate) const SIZE_BY_CAPABILITY: &str = "classified-point-size";
Expand Down
67 changes: 66 additions & 1 deletion crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,22 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("layout-element-wrap", command_uses_element_wrap),
("layout-chart-data", command_uses_chart_data),
("layout-chart-look", command_uses_chart_look),
("blank-paper", command_uses_blank_paper),
];

/// 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 {
match id {
"map.basemap" => {
params.get("name").and_then(Value::as_str).is_some_and(|n| n.trim().eq_ignore_ascii_case("blank"))
&& params.get("color").and_then(Value::as_str).is_some_and(|c| !c.trim().eq_ignore_ascii_case("#FFFFFF"))
}
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_blank_paper)),
_ => false,
}
}

/// A layout command that gives an element a background: an older reader warns that it ignores
/// the key and makes the element without one. `null` only takes a background away, which an
/// older reader's elements never have.
Expand Down Expand Up @@ -374,9 +388,11 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
mut pictures,
mut zarr,
) = (false, false, false, false, false, false, false, false, false, false, false);
let mut offline_area_id = false;
let (mut offline_area_id, mut paper) = (false, false);
for map in maps {
offline_area_id |= map.offline_area_id.is_some();
// A blank basemap's paper colour (#2532), which an older reader would draw and save white.
paper |= map.paper.is_some();
if let Some(t) = &map.view.terrain {
block |= t.block.is_some();
// A round block (#2318), which an older reader would draw and save as a box.
Expand Down Expand Up @@ -409,6 +425,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
(pictures, "picture-markers"),
(zarr, "zarr-window"),
(offline_area_id, "offline-map-area-id"),
(paper, "blank-paper"),
]
.into_iter()
.filter_map(|(used, name)| used.then_some(name))
Expand Down Expand Up @@ -1078,6 +1095,54 @@ mod tests {
assert!(Project::from_json(&unknown.to_string()).unwrap_err().contains("future-zarr"));
}

/// A blank basemap's paper colour (#2532) is required by name in a project and a map file: an
/// older reader would draw the paper white and save the colour away. White paper needs nothing.
#[test]
fn a_blank_paper_colour_is_required_where_it_is_saved() {
let mut p = Project::from_json(include_str!("../../../schema/fixtures/blank_paper.rgis")).unwrap();
assert_eq!(p.map().blank_paper(), Some(rustgis_map::Rgba::rgb(241, 234, 223)));
let saved = serde_json::to_value(&p).unwrap();
assert_eq!(saved["requires"], json!(["blank-paper"]));
assert_eq!(saved["maps"][0]["paper"], json!([241, 234, 223, 255]));
assert_eq!(json_bytes(&map_file_bytes(p.map()).unwrap())["requires"], saved["requires"]);
p.maps[0].paper = None;
let clean = serde_json::to_value(&p).unwrap();
assert!(clean.get("requires").is_none());
assert!(clean["maps"][0].get("paper").is_none());
// A saved command that gives the blank basemap a colour needs it too; white, null or
// another basemap doesn't.
for (params, required) in [
(json!({"name": "blank", "color": "#F1EADF"}), true),
(json!({"name": "Blank", "color": "#101820"}), true),
(json!({"name": "blank", "color": "#ffffff"}), false),
(json!({"name": "blank", "color": null}), false),
(json!({"name": "blank"}), false),
(json!({"name": "paper", "color": "#F1EADF"}), false),
] {
let script = format!("# Paper\nmap.basemap= {params}");
for (field, value) in [
("tasks", json!([{"name": "Task", "steps": [{"title": "Paper", "command": "map.basemap", "params": params}]}])),
(
"tasks",
json!([{"name": "Script", "steps": [{"title": "Paper", "command": "script.run", "params": {"script": script}}]}]),
),
("notebooks", json!([{"name": "Notebook", "cells": [{"kind": "code", "source": script}]}])),
] {
let mut document = clean.clone();
document[field] = value;
let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap();
if required {
assert_eq!(saved["requires"], json!(["blank-paper"]), "{field} {params}");
} else {
assert!(saved.get("requires").is_none(), "{field} {params}");
}
}
}
let mut unknown = saved;
unknown["requires"] = json!(["blank-paper", "future-paper"]);
assert!(Project::from_json(&unknown.to_string()).unwrap_err().contains("future-paper"));
}

/// 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
64 changes: 64 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15472,6 +15472,70 @@ fn the_globe_has_stars_that_turn_off() {
assert!(corner(&mut s) == starry);
}

/// A publication's globe locator keeps the map's blank paper (#2532), so the space around its
/// disc is the page's colour too.
#[test]
fn a_globe_locator_keeps_the_blank_paper() {
let mut s = world();
s.run("map.basemap", &json!({"name": "blank", "color": "#F1EADF"})).unwrap();
let r = s.run("layout.publication", &json!({"extent": [-46.8, -11.6, -38.5, -2.2]})).unwrap();
let globe = r["locator"].as_str().unwrap().to_string();
let m = s.project.maps.iter().find(|m| m.name == globe).unwrap();
assert_eq!(m.blank_paper(), Some(rustgis_map::Rgba::rgb(0xF1, 0xEA, 0xDF)));
}

/// 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]
fn a_blank_basemap_takes_a_paper_colour() {
let cream = rustgis_map::Rgba::rgb(0xF1, 0xEA, 0xDF);
let mut s = Session::new(Project::default());
s.map_mut().graticule = false;
assert_eq!(s.run("map.basemap", &json!({"name": "blank", "color": "#F1EADF"})).unwrap(), Value::Null);
assert_eq!(s.map().paper, Some(cream));
assert_eq!(s.map().palette().0, cream);
s.run("map.basemap", &json!({"name": "blank"})).unwrap();
assert_eq!(s.map().paper, Some(cream), "no color keeps it");
for bad in [json!("#F1EADF80"), json!("F1EADF"), json!("#F1EA"), json!("#+F0000"), json!("cream"), json!(3)] {
let e = s.run("map.basemap", &json!({"name": "blank", "color": bad})).unwrap_err();
assert!(e.contains("#RRGGBB"), "{e}");
assert_eq!(s.map().paper, Some(cream), "a refused colour changes nothing");
}
// A new map starts on the same basemap, its paper included.
let first = s.project.active_map;
s.run("map.new", &json!({"name": "Second"})).unwrap();
assert_eq!((s.map().basemap, s.map().paper), (rustgis_map::Basemap::Blank, Some(cream)));
s.project.active_map = first;
// A layout's map frame on a cream page draws the cream paper, not a white box.
s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "blank"})).unwrap();
s.run("layout.addFrame", &json!({"x": 20, "y": 20, "w": 150, "h": 100})).unwrap();
let dir = std::env::temp_dir().join(format!("rustgis-blank-paper-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("paper.png");
s.run("layout.export", &json!({"path": path.display().to_string(), "dpi": 72})).unwrap();
let pm = crate::render::decode_png(&std::fs::read(&path).unwrap()).unwrap();
let _ = std::fs::remove_dir_all(&dir);
// 72 dpi: a point a pixel; 25 mm in from the page's corner lies inside the frame.
let inside = pm.pixel(71, 71).unwrap();
assert_eq!((inside.red(), inside.green(), inside.blue()), (0xF1, 0xEA, 0xDF));
s.run("map.basemap", &json!({"name": "blank", "color": "#ffffff"})).unwrap();
assert_eq!(s.map().paper, None, "white is the blank basemap's own paper");
s.run("map.basemap", &json!({"name": "blank", "color": "#F1EADF"})).unwrap();
s.run("map.basemap", &json!({"name": "blank", "color": null})).unwrap();
assert_eq!(s.map().paper, None, "null: white again");
s.run("map.basemap", &json!({"name": "blank", "color": "#F1EADF"})).unwrap();
// Another basemap: no error, a warning, and the paper goes.
let mark = s.notice_mark();
let v = s.run("map.basemap", &json!({"name": "paper", "color": "#F1EADF"})).unwrap();
assert!(v["warning"].as_str().is_some_and(|w| w.contains("blank basemap only")), "{v}");
assert!(s.notices_since(mark).iter().any(|n| n.text.contains("blank basemap only")));
assert_eq!(s.map().basemap, rustgis_map::Basemap::Paper);
assert_eq!(s.map().paper, None);
s.run("map.basemap", &json!({"name": "blank"})).unwrap();
assert_eq!(s.map().palette().0, rustgis_map::Rgba::rgb(0xFF, 0xFF, 0xFF), "back on blank: white");
assert_eq!(s.run("map.basemap", &json!({"name": "ocean"})).unwrap(), Value::Null, "no color, no warning");
}

#[test]
fn exports_draw_the_globe_in_light_space() {
// #352: the dark, starry space is the interactive view's; exports and layouts print a light
Expand Down
1 change: 1 addition & 0 deletions crates/engine/tests/project_save_roundtrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ fn step() -> impl Strategy<Value = (&'static str, Value)> {
(prop::sample::select(vec!["legend", "scaleBar", "northArrow", "text", "rectangle", "grid", "colorbar"]), name())
.prop_map(|(k, t)| ("layout.addElement", json!({"kind": k, "text": t}))),
prop::sample::select(vec!["paper", "midnight", "ocean", "atlas", "blank"]).prop_map(|n| ("map.basemap", json!({"name": n}))),
prop::sample::select(vec!["#F1EADF", "#101820"]).prop_map(|c| ("map.basemap", json!({"name": "blank", "color": c}))),
prop::sample::select(vec!["Albers Equal Area Conic +lat_1=29.5 +lat_2=45.5", "EPSG:3857", "EPSG:4326"])
.prop_map(|t| ("map.projection", json!({"type": t}))),
(-180.0..180.0f64).prop_map(|b| ("map.setBearing", json!({"bearing": b}))),
Expand Down
19 changes: 18 additions & 1 deletion crates/map/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1659,6 +1659,11 @@ pub struct Map {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub groups: Vec<LayerGroup>,
pub basemap: Basemap,
/// The blank basemap's paper (#2532): its colour where a blank map would draw white, so a
/// map frame can sit on a coloured page. Drawn opaque ([`Map::blank_paper`]); only kept with
/// [`Basemap::Blank`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub paper: Option<Rgba>,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/// Web tile basemaps and overlays (index 0 on top), each drawn over the map layer it names
/// (`TileLayer::over`), or under all of them; see [`Map::stack`].
#[serde(default, skip_serializing_if = "Vec::is_empty")]
Expand Down Expand Up @@ -1809,6 +1814,7 @@ impl Map {
service_groups: Vec::new(),
groups: Vec::new(),
basemap: Basemap::Paper,
paper: None,
tiles: Vec::new(),
camera: Camera::world(),
bookmarks: Vec::new(),
Expand Down Expand Up @@ -2969,9 +2975,13 @@ impl Map {

/// The built-in basemap's (background, land, land outline, graticule) colours. The world
/// outline is the Earth's, so on another body the background is plain: the land's grey, with
/// no land drawn on it (#223).
/// no land drawn on it (#223). A blank basemap's paper colour (#2532) is its background and its
/// land, on any body.
pub fn palette(&self) -> (Rgba, Rgba, Rgba, Rgba) {
let (water, land, outline, grat) = self.basemap.palette();
if let Some(paper) = self.blank_paper() {
return (paper, paper, outline, grat);
}
if self.body().is_earth() {
return (water, land, outline, grat);
}
Expand All @@ -2980,6 +2990,12 @@ impl Map {
(grey, grey, Rgba::new(0, 0, 0, 0), grat)
}

/// The blank basemap's paper colour, when the map is on the blank basemap and has one: always
/// opaque, a file's translucent one included (the paper is the backdrop: nothing shows through).
pub fn blank_paper(&self) -> Option<Rgba> {
self.paper.filter(|_| self.basemap == Basemap::Blank).map(|c| Rgba::rgb(c.r(), c.g(), c.b()))
}

/// Whether the built-in world outline is drawn: where the palette's land and water differ, so
/// not on the blank basemap or another body.
pub fn draws_world_outline(&self) -> bool {
Expand Down Expand Up @@ -3207,6 +3223,7 @@ impl Map {
service_groups,
groups: _,
basemap: _,
paper: _,
tiles,
camera: _,
bookmarks: _,
Expand Down
Loading
Loading