From 4ef5e6cf7fedfd7ef8f854cbb56c2faf420ea515 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 25 Nov 2026 11:11:56 -0500 Subject: [PATCH] feat(layout): a page colour painted under every element layout.page takes color (#RRGGBB, opaque; null or white restores white), drawn in the view, PNG, PDF and SVG, saved as paper on the layout and required as layout-page-color. A translucent one in a hand-edited file is read as it looks on white paper and counted. Page Size gets a Page color picker. Closes #2855 --- crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/layout.rs | 10 +++- crates/engine/src/cmd/mod.rs | 18 ++++++ crates/engine/src/cmd/navigate.rs | 16 +----- crates/engine/src/project.rs | 3 +- crates/engine/src/project_capabilities.rs | 68 ++++++++++++++++++++++- crates/engine/src/tests.rs | 49 ++++++++++++++++ crates/engine/src/tests/layout_files.rs | 1 + crates/map/src/layout.rs | 37 +++++++++++- crates/render/src/layout.rs | 29 +++++++++- crates/render/src/svg.rs | 4 +- crates/ui-egui/src/layoutview.rs | 31 +++++++---- crates/ui-egui/src/ribbon.rs | 47 +++++++++++++--- docs/maintaining.md | 8 +++ docs/user-guide/layouts.md | 8 +++ schema/fixtures/layout_page_color.rgis | 25 +++++++++ schema/project.schema.json | 6 +- 17 files changed, 318 insertions(+), 44 deletions(-) create mode 100644 schema/fixtures/layout_page_color.rgis diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 548e134dfe..d8fbdf0ba1 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -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 diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 547b6a24a4..b4ebd65277 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -111,7 +111,7 @@ pub fn commands() -> Vec { }).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: " 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}"#, @@ -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 diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 5cfd7da7f8..d6f9f4a93d 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -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>, 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) } diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 7463431b39..1a04bc3a60 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -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). diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 2233e4d49f..d70aaefed8 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -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. @@ -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) )); } diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 779dc60794..ac838b0b43 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -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 @@ -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 { @@ -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 { 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::(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. @@ -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)) @@ -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})), @@ -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. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d2bc6eec41..e0169b007a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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] diff --git a/crates/engine/src/tests/layout_files.rs b/crates/engine/src/tests/layout_files.rs index 5aefd83b6f..d954bfda5b 100644 --- a/crates/engine/src/tests/layout_files.rs +++ b/crates/engine/src/tests/layout_files.rs @@ -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(); diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index 15e8f1f5cb..6a7f41f2b8 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -2675,6 +2675,11 @@ pub struct Layout { /// Spanish, French or German do; off, the other way round. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub decimal_comma: bool, + /// The page's colour, painted under every element (#2855); none, white. Always opaque: a + /// page has nothing under it to show through, so a translucent one in a hand-edited file is + /// read as it looks on white paper. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub paper: Option, #[serde(default)] next_id: u32, /// Process-local identity, kept by undo snapshots but never stored in a project. @@ -2727,6 +2732,7 @@ impl Layout { series: None, guides: Guides::default(), decimal_comma: false, + paper: None, next_id: 1, instance: Instance::default(), } @@ -2812,6 +2818,12 @@ impl Layout { let count = self.elements.len(); self.width = finite_or(self.width, 210.0).clamp(20.0, 5000.0); self.height = finite_or(self.height, 297.0).clamp(20.0, 5000.0); + // A page colour is opaque (a page has nothing under it to show through) and white is the + // page's own (#2855): a hand-edited translucent one is read as it looks on white paper, + // and said. + let white = Rgba::rgb(255, 255, 255); + let translucent = self.paper.is_some_and(|c| c.a() != 255); + self.paper = self.paper.map(|c| white.lerp(c.with_alpha(255), f64::from(c.a()) / 255.0)).filter(|c| *c != white); // The same limits `layout.guides` sets: the view walks these lists every frame. for list in [&mut self.guides.x, &mut self.guides.y] { list.retain(|v| v.is_finite() && v.abs() <= 5000.0); @@ -3029,7 +3041,7 @@ impl Layout { } } let series_adjusted = !series_removed && self.series != page.3; - let page_adjusted = series_adjusted || (self.width, self.height, &self.guides) != (page.0, page.1, &page.2); + let page_adjusted = series_adjusted || translucent || (self.width, self.height, &self.guides) != (page.0, page.1, &page.2); LayoutRepairs { elements_adjusted: adjusted, elements_cut: cut_count, @@ -3052,7 +3064,7 @@ pub struct LayoutRepairs { pub elements_cut: usize, /// Elements removed: beyond the 500 a layout holds, or tied to a map frame it doesn't have. pub elements_removed: usize, - /// Whether the page size, guides or map series margin changed (0 or 1). + /// Whether the page size, guides, page colour or map series margin changed (0 or 1). pub page_adjusted: usize, /// Whether the map series was removed, its map frame missing (0 or 1). pub series_removed: usize, @@ -4441,6 +4453,27 @@ mod tests { } } + /// A page colour with alpha, which only a hand-edited file holds, is read as it looks on white + /// paper (a page has nothing else under it), so a clear one is the white page, and every one + /// is counted as a page repaired (#2855). An opaque one is kept, and opaque white is the page's + /// own, so it is let go without a word. + #[test] + fn a_translucent_page_colour_is_made_opaque_and_counted() { + for (paper, kept, adjusted) in [ + (serde_json::json!([11, 27, 43, 128]), Some(Rgba::rgb(133, 141, 149)), 1), + (serde_json::json!([11, 27, 43, 0]), None, 1), + (serde_json::json!([11, 27, 43, 255]), Some(Rgba::rgb(11, 27, 43)), 0), + (serde_json::json!([255, 255, 255, 255]), None, 0), + (serde_json::json!([255, 255, 255, 128]), None, 1), + ] { + let mut l: Layout = + serde_json::from_value(serde_json::json!({"name": "L", "width": 120, "height": 90, "elements": [], "paper": paper})) + .unwrap(); + let r = l.clamp(); + assert_eq!((l.paper, r.page_adjusted), (kept, adjusted), "{paper}"); + } + } + #[test] fn grid_labels_follow_the_format() { let g = Grid::default(); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 25ed8b4b14..2b132528b3 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -683,7 +683,9 @@ fn draw_page( let mut pm = if record.is_some() { Canvas::recording(bounds.width(), bounds.height())? } else { Canvas::new(bounds.width(), bounds.height())? }; if element.is_none() { - pm.fill(tiny_skia::Color::WHITE); + // The page's colour (#2855), white unless given. + let paper = layout.paper.unwrap_or(Rgba::rgb(0xFF, 0xFF, 0xFF)); + pm.fill(tiny_skia::Color::from_rgba8(paper.r(), paper.g(), paper.b(), 255)); } let visible = |e: &&rustgis_map::layout::Element| e.visible && element.is_none_or(|id| e.id == id); // Frame cameras first: surrounds and extent indicators read them. @@ -6199,6 +6201,31 @@ mod tests { assert_eq!(layers(&layout), [("Texto".to_string(), u64::from(b))]); } + /// The page's colour (#2855) is the first thing the PDF's drawing fills, over the whole page; + /// a white page is filled white as before. + #[test] + fn a_pages_colour_is_filled_first_in_the_pdfs_drawing() { + use crate::vector::{Brush, Item}; + let mut layout = Layout::new("Paper", 120.0, 90.0); + let first = |layout: &Layout| { + let (drawing, _) = render_drawing(layout, &mut [], 72.0, &PageInfo::default()).unwrap(); + let (w, h, items) = drawing.finish(); + match items.into_iter().next() { + Some(Item::Fill { path, brush: Brush::Solid(c), .. }) => { + let b = path.bounds(); + assert!(b.left() <= 0.0 && b.top() <= 0.0 && b.right() >= w - 0.5 && b.bottom() >= h - 0.5, "{b:?}"); + c.to_color_u8() + } + _ => panic!("the page is not filled first"), + } + }; + let c = first(&layout); + assert_eq!((c.red(), c.green(), c.blue(), c.alpha()), (255, 255, 255, 255)); + layout.paper = Some(Rgba::rgb(0x0B, 0x1B, 0x2B)); + let c = first(&layout); + assert_eq!((c.red(), c.green(), c.blue(), c.alpha()), (0x0B, 0x1B, 0x2B, 255)); + } + /// A page with a frame of the built-in world and a title. fn vector_page() -> (Layout, Vec) { let mut layout = Layout::new("Vectors", 120.0, 90.0); diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 7d7667e83a..bcc91fe2a3 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -61,7 +61,9 @@ fn layout_svg_inner( if !defs.text.is_empty() { let _ = write!(s, "\n{}\n", defs.text); } - let _ = writeln!(s, r##""##, num(pw), num(ph)); + // The page's colour (#2855), white unless given; its channels alone, opaque as the PNG's. + let paper = layout.paper.map_or_else(|| "#ffffff".to_string(), |c| format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())); + let _ = writeln!(s, r##""##, num(pw), num(ph)); body.insert_str(0, &s); body.push_str("\n"); Some((body, pictured)) diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index fe3d5a77b5..4d814bffd6 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -811,7 +811,8 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } // Shadow, page, elements. painter.rect_filled(page.translate(vec2(3.0, 4.0)), 2.0, Color32::from_black_alpha(50)); - painter.rect_filled(page, 0.0, Color32::WHITE); + // The page's colour (#2855), shown until the page's texture is drawn over it. + painter.rect_filled(page, 0.0, layout.paper.map_or(Color32::WHITE, crate::theme::c32)); let pointer = ui.input(|i| i.pointer.latest_pos()); if let Some(tex) = &app.layout.texture { painter.image(tex.id(), page, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); @@ -2645,7 +2646,8 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { let mut on = ink.is_some(); let hint = tl!("Its own colour for its text and lines; off, the default dark grey"); if ui.checkbox(&mut on, "").labelled_by(input_label.id).on_hover_text(hint).changed() { - update(app, json!({"color": on.then(|| first_ink(e.background.as_ref()).hex())})); + let page = layout.paper.unwrap_or(rustgis_engine::map::Rgba::rgb(0xFF, 0xFF, 0xFF)); + update(app, json!({"color": on.then(|| first_ink(e.background.as_ref(), page).hex())})); } let Some(current) = ink else { return }; let mut c = crate::theme::c32(current); @@ -2967,13 +2969,15 @@ fn choice(ui: &mut Ui, salt: (&str, u32), label: egui::Id, current: &str, items: picked } -/// The ink an element starts with when Ink is turned on (#2257): white over a background that is -/// dark once drawn on the white page, else the default dark grey, so its text never disappears. -fn first_ink(background: Option<&Background>) -> rustgis_engine::map::Rgba { - let Some(fill) = background.map(|b| b.fill) else { return INK }; +/// The ink an element starts with when Ink is turned on (#2257): white over what shows under its +/// text, its background drawn on the page (`page`, the page's colour, #2855), when that is dark, +/// else the default dark grey, so its text never disappears. +fn first_ink(background: Option<&Background>, page: rustgis_engine::map::Rgba) -> rustgis_engine::map::Rgba { + // No background: nothing drawn over the page, so the page itself shows under the text. + let fill = background.map_or(rustgis_engine::map::Rgba::new(0, 0, 0, 0), |b| b.fill); let a = u16::from(fill.a()); - let over = |c: u8| u8::try_from((u16::from(c) * a + 255 * (255 - a)) / 255).unwrap_or(u8::MAX); - let shown = Color32::from_rgb(over(fill.r()), over(fill.g()), over(fill.b())); + let over = |c: u8, under: u8| u8::try_from((u16::from(c) * a + u16::from(under) * (255 - a)) / 255).unwrap_or(u8::MAX); + let shown = Color32::from_rgb(over(fill.r(), page.r()), over(fill.g(), page.g()), over(fill.b(), page.b())); let white = rustgis_engine::map::Rgba::rgb(0xFF, 0xFF, 0xFF); if crate::theme::contrast(shown, Color32::WHITE) > crate::theme::contrast(shown, crate::theme::c32(INK)) { white } else { INK } } @@ -3025,14 +3029,21 @@ mod tests { fn ink_starts_readable_on_its_background() { use rustgis_engine::map::Rgba; use rustgis_engine::map::layout::{Background, INK}; - let on = |fill: Rgba| first_ink(Some(&Background { fill, ..serde_json::from_value(json!({})).unwrap() })); let white = Rgba::rgb(0xFF, 0xFF, 0xFF); - assert_eq!(first_ink(None), INK); + let on = |fill: Rgba| first_ink(Some(&Background { fill, ..serde_json::from_value(json!({})).unwrap() }), white); + assert_eq!(first_ink(None, white), INK); assert_eq!(on(white), INK); assert_eq!(on(Rgba::rgb(0x1E, 0x29, 0x3B)), white); // A dark fill seen through mostly: the page shows, so it reads as light. assert_eq!(on(Rgba::new(0x1E, 0x29, 0x3B, 0x20)), INK); assert_eq!(on(Rgba::new(0x1E, 0x29, 0x3B, 0xE0)), white); + // On a dark page (#2855): white with no background, or over a fill the page shows through; + // dark grey over a light fill. + let navy = Rgba::rgb(0x0B, 0x1B, 0x2B); + let on_navy = |fill: Rgba| first_ink(Some(&Background { fill, ..serde_json::from_value(json!({})).unwrap() }), navy); + assert_eq!(first_ink(None, navy), white); + assert_eq!(on_navy(Rgba::new(0xFF, 0xFF, 0xFF, 0x20)), white); + assert_eq!(on_navy(white), INK); } /// In the browser, a page drawn while its frames' tiles were on their way is drawn again as diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 14c3aa8005..02f53893bd 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -748,6 +748,26 @@ pub(crate) fn sample_data_gallery(ui: &mut Ui, app: &mut RustGisApp) { } } +/// The page's colour (#2855), under Page Size. The picker is drawn in the menu itself, as the +/// blank basemap's paper is: a colour button's picker is a popup of its own, and opening it would +/// close the menu. +fn page_color(ui: &mut Ui, app: &mut RustGisApp, li: usize, layout: &rustgis_engine::map::layout::Layout) { + let white = rustgis_engine::map::Rgba::rgb(0xFF, 0xFF, 0xFF); + ui.separator(); + egui::CollapsingHeader::new(tl!("Page color")).id_salt("page_color").show(ui, |ui| { + if let Some(c) = opaque_picker(ui, app, layout.paper.unwrap_or(white)) + && let Err(e) = app.run("layout.page", json!({"layout": li, "color": c.hex()})) + { + app.session.notify(e, true); + } + if ui.add_enabled(layout.paper.is_some(), egui::Button::new(tl!("White"))).clicked() + && let Err(e) = app.run("layout.page", json!({"layout": li, "color": null})) + { + app.session.notify(e, true); + } + }); +} + /// The blank basemap's paper colour (#2532), while the map is on it with no web basemap over it: /// the colour a map frame shows on a coloured page. The picker is drawn in the gallery itself: a /// colour button's picker is a popup of its own, and opening it would close this menu. @@ -756,19 +776,29 @@ fn blank_paper(ui: &mut Ui, app: &mut RustGisApp) { if map.basemap != Basemap::Blank || !map.tiles.iter().all(|t| t.overlay) { return; } - let mut c = crate::theme::c32(map.palette().0); + let current = map.palette().0; ui.add_space(6.0); egui::CollapsingHeader::new(tl!("Paper color")).id_salt("blank_paper").show(ui, |ui| { - let picked = ui.scope(|ui| egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque)); - if picked.inner { - crate::widgets::one_step_per_press(app, &picked.response); - let [r, g, b, _] = c.to_srgba_unmultiplied(); - let _ = - app.run("map.basemap", json!({"name": "blank", "color": rustgis_engine::map::Rgba::rgb(r, g, b).hex(), "keepTiles": true})); + if let Some(c) = opaque_picker(ui, app, current) { + let _ = app.run("map.basemap", json!({"name": "blank", "color": c.hex(), "keepTiles": true})); } }); } +/// An opaque colour picker drawn in place, from `current`: the colour picked, its drag one step +/// to undo. Drawn in the menu or gallery itself, as a colour button's picker is a popup of its own +/// and opening it would close them. +fn opaque_picker(ui: &mut Ui, app: &mut RustGisApp, current: rustgis_engine::map::Rgba) -> Option { + let mut c = crate::theme::c32(current); + let picked = ui.scope(|ui| egui::color_picker::color_picker_color32(ui, &mut c, egui::color_picker::Alpha::Opaque)); + if !picked.inner { + return None; + } + crate::widgets::one_step_per_press(app, &picked.response); + let [r, g, b, _] = c.to_srgba_unmultiplied(); + Some(rustgis_engine::map::Rgba::rgb(r, g, b)) +} + pub(crate) fn basemap_gallery(ui: &mut Ui, app: &mut RustGisApp) { let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new(tl!("Basemaps")).font(semibold(12.5))); @@ -3376,7 +3406,7 @@ fn layout_groups(app: &mut RustGisApp, ui: &mut Ui) { } }; group(ui, "Page", |ui| { - big_menu(ui, app, "new_layout", "Page\nSize", "Change the page size and orientation.", |ui, app| { + big_form_menu(ui, app, "new_layout", "Page\nSize", "Change the page size and orientation.", |ui, app| { for (id, label, w, h) in rustgis_engine::map::layout::PAGES { let landscape = layout.width > layout.height; let (pw, ph) = if landscape { (h.max(*w), h.min(*w)) } else { (*w, *h) }; @@ -3396,6 +3426,7 @@ fn layout_groups(app: &mut RustGisApp, ui: &mut Ui) { ui.close(); } } + page_color(ui, app, li, &layout); }); col(ui, |ui| { let snap = !app.layout.no_snap; diff --git a/docs/maintaining.md b/docs/maintaining.md index 8046f80b6b..b228dad443 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -294,6 +294,14 @@ too: a saved `layout.update` can't tell whose they are, so a number there requir (`.rgislayout`) with such a bar lists it in its header, so an older reader refuses the file too. A scale bar's text size isn't one of its details: it requires `layout-text-size`, as above. +Projects with a layout whose page isn't white (`paper` on the layout, #2855) require +`layout-page-color`, so an older reader refuses them instead of opening the page white and saving +it again without its colour. A saved `layout.page` that gives a `color` other than white requires +it too; `null` or `"#FFFFFF"` need nothing. A saved `layout.import` whose `text` has a coloured +page requires it as well. A translucent page colour, which only a hand-edited file holds, is read +as it looks on white paper (a clear one is the white page) and counted with the page settings the +project says it repaired. + Projects, map files and layer files with a layer or table held in a coordinate system of its own (`Dataset::held_in`: a file's system, kept since #2580) save its features in that system, exactly, with `held_in` beside them, and require `native-coordinates`: an older reader would read those diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 2188dee782..56fefe4dc9 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -200,6 +200,14 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu "note": "Only cells with a significant trend (p < 0.05) are coloured."} ``` +- **Page colour**: Publish › Page Size › **Page color** paints the whole page a colour under + every element, in the view and in PNG, PDF and SVG exports; **White** gives the white page back. + `layout.page={"color": "#0B1B2B"}` sets it, `null` or `"#FFFFFF"` restores white. It is + opaque: a page has nothing under it to show through. The elements keep their own colours: on a + dark page, give texts a light colour, and legends, colorbars, tables and charts a light **Ink** + (below). A map frame keeps its own map's background; give the frame the blank basemap with a + paper colour to match a coloured page. + - **Map frames**: rectangle, circle and ellipse frames, or polygon and lasso frames drawn on the page. Each frame shows a map of the project at its own centre and scale. Turn on **Pan/Zoom Map** (Map Frames group, or a frame's properties) to drag inside frames to pan their maps and diff --git a/schema/fixtures/layout_page_color.rgis b/schema/fixtures/layout_page_color.rgis new file mode 100644 index 0000000000..5a937eed5b --- /dev/null +++ b/schema/fixtures/layout_page_color.rgis @@ -0,0 +1,25 @@ +{ + "format": 2, + "name": "Page colour", + "requires": ["layout-page-color"], + "active_map": 0, + "maps": [ + { + "name": "Map", + "layers": [], + "basemap": "Paper", + "camera": {"center": {"x": 0, "y": 0}, "res": 30000} + } + ], + "layouts": [ + { + "name": "Dark page", + "width": 297, + "height": 210, + "paper": [11, 27, 43, 255], + "elements": [ + {"id": 1, "name": "Map", "x": 10, "y": 10, "w": 277, "h": 190, "kind": {"MapFrame": {"map": "Map", "center": {"x": 0, "y": 0}, "scale": 1000000}}} + ] + } + ] +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 5e4242281c..c18c867010 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1283,7 +1283,8 @@ "label-clearance", "svg-markers", "label-duplicates", - "tile-resampling" + "tile-resampling", + "layout-page-color" ], "type": "string" }, @@ -1395,7 +1396,8 @@ "label-clearance", "svg-markers", "label-duplicates", - "tile-resampling" + "tile-resampling", + "layout-page-color" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2