From 53d1a3113b696dcdb62889aef711d08c5212da5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 15:31:08 -0500 Subject: [PATCH 1/6] feat(layout): choose the font of a scale bar's labels --- crates/engine/src/cmd/layout.rs | 6 +- crates/engine/src/cmd/layout/elements.rs | 9 +- crates/engine/src/cmd/layout/export.rs | 6 +- crates/engine/src/cmd/layout/text.rs | 5 +- crates/engine/src/cmd/layout/update.rs | 15 +- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 109 +++++++++++++-- crates/engine/src/tests.rs | 17 ++- crates/engine/src/tests/layout_north_font.rs | 6 +- crates/engine/src/tests/layout_scale_font.rs | 129 ++++++++++++++++++ crates/map/src/layout/elements.rs | 20 ++- crates/render/src/layout/scale_bar.rs | 47 +++++-- crates/render/src/layout/tests.rs | 31 +++++ .../ui-egui/src/layoutview/format/scalebar.rs | 12 ++ crates/ui-egui/src/layoutview/tests.rs | 39 ++++++ docs/maintaining.md | 8 ++ docs/user-guide/layouts.md | 4 +- schema/fixtures/layout_scale_bar_font.rgis | 1 + schema/project.schema.json | 2 + 19 files changed, 420 insertions(+), 47 deletions(-) create mode 100644 crates/engine/src/tests/layout_scale_font.rs create mode 100644 schema/fixtures/layout_scale_bar_font.rgis diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index e7c1c11699..cd204e3d9a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -210,7 +210,7 @@ pub fn commands() -> Vec { r##""valign"?: "top"|"middle"|"bottom" (text, dynamicText: where its block of lines sits down its box; default top; a block taller than its box is drawn from the top, its last lines left out, which a warning says; refused for other kinds), "##, r##""lineSpacing"?: 0.5 to 3 (text, dynamicText: the distance between its lines, a multiple of the usual; default 1; refused outside that range, and for other kinds), "##, r##""case"?: "none"|"upper"|"lower" (text, dynamicText: drawn in upper or lower case once its dynamic text is filled in, its text kept as typed; default none; refused for other kinds), "##, - r##""font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText, and a northArrow's N; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "##, + r##""font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText, a northArrow's N and a scaleBar's labels; a family not installed here is drawn in its fallback, and a serif where none is installed in the sans, with a warning; refused for other kinds), "##, r##""fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "##, r##""title"?: legend title (default "Legend"); chart: its own title ("" for none; default: its field, or the statistic of its field by the group); profile: written over its curve ("" for none; default its layer's name), "##, r##""subtitle"?: text (legend: one line under its title, at the rows' text size, up to 200 characters; "" for none, the default; refused for other kinds), "##, @@ -327,8 +327,8 @@ pub fn commands() -> Vec { r##""valign"?, "##, r##""lineSpacing"?, "##, r##""case"? (text, as in layout.addElement; null leaves each as it is; refused for other elements), "##, - r##""font"?: "sans"|"serif"|an installed font family's name (text, dynamicText, a northArrow's N), "##, - r##""fallback"?: "sans"|"serif" (text, dynamicText, a northArrow's N, as in layout.addElement; refused for other elements), "##, + r##""font"?: "sans"|"serif"|an installed font family's name (text, dynamicText, a northArrow's N, a scaleBar's labels), "##, + r##""fallback"?: "sans"|"serif" (text, dynamicText, a northArrow's N, a scaleBar's labels, as in layout.addElement; refused for other elements), "##, r##""title"? (legend, colorbar; chart: its own title ("" for none; null giving it the title it is given again)), "##, r##""subtitle"?: text (legend, as in layout.addElement; "" takes it away, null leaves it as it is), "##, r##""allClasses"?: bool (legend), "##, diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 7cd51a6396..589d4a65be 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -394,7 +394,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu } // A family is a text's: refused elsewhere, as a legend's left-out layers are, so a script // doesn't take it as applied. - if !matches!(kind, "text" | "dynamicText" | "northArrow") && gives_font(p) { + if !matches!(kind, "text" | "dynamicText" | "northArrow" | "scaleBar") && gives_font(p) { return Err(ONLY_TEXT_FONT.into()); } if kind != "rectangle" && p.get("radius").is_some_and(|v| !v.is_null()) { @@ -802,6 +802,9 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu ElementKind::NorthArrow { font, font_name, .. } if gives_font(p) => { font_warning(*font, font_name.as_deref(), p.get("fallback").is_some_and(|v| !v.is_null()), (true, false)) } + ElementKind::ScaleBar { font, font_name, .. } if gives_font(p) => { + font_warning(*font, font_name.as_deref(), p.get("fallback").is_some_and(|v| !v.is_null()), (false, false)) + } _ => None, }; // A colorbar with nothing to show says why, as a notice the app shows. @@ -1133,6 +1136,8 @@ const ADD_SCALE_BAR_KEYS: &[&str] = &[ "textSize", "color", "fill", + "font", + "fallback", ]; /// Keys read by `layout.addElement` for a legend (#3074). @@ -1667,7 +1672,7 @@ mod tests { // Every key a kind reads, each given a value it takes. let calls = [ json!({"kind": "northArrow", "layout": 0, "frame": frame, "x": 10, "y": 10, "w": 15, "h": 20, "style": "compass", "fill": "#112233", "outline": "#445566", "font": "sans", "fallback": null, "background": {"fill": "#FFFFFF"}}), - json!({"kind": "scaleBar", "frame": frame, "x": 10, "y": 10, "w": 60, "h": 12, "style": "stepped", "units": "miles", "divisions": 3, "subdivisions": 2, "divisionsBeforeZero": 1, "labelPosition": "below", "unitLabel": "mi", "unitLabelPosition": "afterBar", "fit": "adjustWidth", "decimals": 1, "textSize": 9, "color": "#112233", "fill": "#FFFFFF"}), + json!({"kind": "scaleBar", "frame": frame, "x": 10, "y": 10, "w": 60, "h": 12, "style": "stepped", "units": "miles", "divisions": 3, "subdivisions": 2, "divisionsBeforeZero": 1, "labelPosition": "below", "unitLabel": "mi", "unitLabelPosition": "afterBar", "fit": "adjustWidth", "decimals": 1, "textSize": 9, "color": "#112233", "fill": "#FFFFFF", "font": "sans", "fallback": null}), json!({"kind": "legend", "frame": frame, "title": "T", "allClasses": true, "hideOther": true, "showNoData": true, "exclude": [], "layerOrder": [], "columns": 2, "labels": {}, "textSize": 8, "fit": "adjustSize", "showLayerNames": false, "showCounts": true, "sizes": "nested", "color": "#112233"}), json!({"kind": "colorbar", "frame": frame, "title": "T", "orientation": "vertical", "ticks": 3, "tickSide": "left", "reverse": true, "color": "#112233"}), json!({"kind": "text", "text": "A", "size": 14, "color": "#112233", "bold": true, "italic": true, "align": "center", "letterSpacing": 1, "font": "Some Family", "fallback": "serif", "rotation": 90, "wrap": true, "valign": "middle", "lineSpacing": 1.5, "case": "upper", "name": "ignored"}), diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index ada10439b2..46ac6cfcf4 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -2,13 +2,13 @@ use super::*; -/// What an export of a layout whose texts or north arrows name installed families is told while the app is still -/// indexing the fonts (its first seconds; the app's exports don't wait for them): those texts +/// What an export of a layout whose texts, north arrows or scale bars name installed families is told +/// while the app is still indexing the fonts (its first seconds; the app's exports don't wait for them): those texts /// are drawn in their fallbacks. A script or the command line indexes them at once. pub(in crate::cmd::layout) fn named_fonts_unread(layout: &Layout) -> Option<&'static str> { let named = layout.elements.iter().any(|e| e.kind.named_font().is_some()); (named && rustgis_render::families::available().is_none()).then_some( - "the installed fonts are still being read, so texts and north arrows in a named font family are drawn in their fallback: export again in a moment", + "the installed fonts are still being read, so texts, north arrows and scale bars in a named font family are drawn in their fallback: export again in a moment", ) } diff --git a/crates/engine/src/cmd/layout/text.rs b/crates/engine/src/cmd/layout/text.rs index 70a70ce914..70716bde3d 100644 --- a/crates/engine/src/cmd/layout/text.rs +++ b/crates/engine/src/cmd/layout/text.rs @@ -346,9 +346,10 @@ pub(crate) fn text_block_settings(p: &Value, current: (TextVAlign, f64, TextCase } /// What a `font` given for an element that draws no text of a chosen family is told. -pub(in crate::cmd::layout) const ONLY_TEXT_FONT: &str = "only text elements and north arrows take a font or a fallback"; +pub(in crate::cmd::layout) const ONLY_TEXT_FONT: &str = "only text elements, north arrows and scale bars take a font or a fallback"; -/// Whether `p` gives a `font` or a `fallback`, which only text elements and north arrows take. +/// Whether `p` gives a `font` or a `fallback`, which only text elements, north arrows and +/// scale bars take. pub(in crate::cmd::layout) fn gives_font(p: &Value) -> bool { ["font", "fallback"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) } diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 11ba999039..e19d837521 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -73,8 +73,11 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result { - if SCALE_BAR_LOOK_KEYS.iter().chain(SCALE_BAR_KEYS.iter()).all(|k| p.get(k).is_none()) { + let keys = SCALE_BAR_LOOK_KEYS.iter().chain(SCALE_BAR_KEYS.iter()).chain(["font", "fallback"].iter()); + if keys.into_iter().all(|k| p.get(k).is_none()) { return Ok(None); } let style = match given_name(p, "style", "alternating, stepped or line")? { @@ -122,6 +125,7 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result return Err("unitLabel is text, or null for the unit's abbreviation".into()), }; + let (font, font_name) = text_font(p, (*font, font_name.clone()))?; Ok(Some(ElementKind::ScaleBar { frame: *frame, units, @@ -137,6 +141,8 @@ pub(in crate::cmd::layout) fn restyle(kind: &ElementKind, p: &Value) -> Result { @@ -398,8 +404,8 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { Some(ElementKind::Text { italic, align, letter_spacing, font, font_name, .. }) => { Some((text_style(p, *italic, *align, *letter_spacing)?, text_font(p, (*font, font_name.clone()))?)) } - // A north arrow's are read with its look, by `restyle`. - Some(ElementKind::NorthArrow { .. }) => None, + // A north arrow's and a scale bar's are read with their look, by `restyle`. + Some(ElementKind::NorthArrow { .. } | ElementKind::ScaleBar { .. }) => None, _ if gives_font(p) => return Err(ONLY_TEXT_FONT.into()), _ => None, }; @@ -428,10 +434,11 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { Some(ElementKind::Text { bold, .. }) => b(p, "bold").unwrap_or(*bold), _ => false, }; - // The family asked for: a text's, or a north arrow's, whose `N` is bold. + // The family asked for: a text's, a north arrow's, whose `N` is bold, or a scale bar's. let asked = match (&new_text_style, &restyled) { (Some(((italic, _, _), (f, n))), _) => Some((*f, n.as_deref(), (bold_now, *italic))), (None, Some(ElementKind::NorthArrow { font, font_name, .. })) => Some((*font, font_name.as_deref(), (true, false))), + (None, Some(ElementKind::ScaleBar { font, font_name, .. })) => Some((*font, font_name.as_deref(), (false, false))), _ => None, }; let font_told = asked diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index d726224f3e..fde5ff78b1 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -113,6 +113,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-table-look", "layout-colorbar-labels", "layout-north-arrow-font", + "layout-scale-bar-font", "field-generation", "field-package", FIELD_CONFLICTS, diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index c4ae8328b9..85e12c0cf6 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -177,6 +177,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-table-look", command_uses_table_look), ("layout-colorbar-labels", command_uses_colorbar_labels), ("layout-north-arrow-font", command_uses_north_arrow_font), + ("layout-scale-bar-font", command_uses_scale_bar_font), ("blank-paper", command_uses_blank_paper), ("layout-frame-border", command_uses_frame_border), ("layout-section", command_uses_section), @@ -1243,27 +1244,46 @@ fn north_arrows_with_font(e: &rustgis_map::layout::Element) -> bool { /// purpose: a reader without this refuses a font on a north arrow when the step runs. fn command_uses_north_arrow_font(id: &str, params: &Value) -> bool { match id { - "layout.addElement" => { - params.get("kind").and_then(Value::as_str).is_some_and(|k| k.trim().eq_ignore_ascii_case("northArrow")) - && params - .get("font") - .and_then(Value::as_str) - .is_some_and(|f| rustgis_map::layout::FontFamily::from_name(f.trim()) != Some(rustgis_map::layout::FontFamily::Sans)) - } + "layout.addElement" => adds_with_font(params, "northArrow"), "layout.import" | "report.existingTemplate" => imported_layout_uses(params, &["\"font"], north_arrows_with_font), // It opens its `text` only, whatever else the step holds. - "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_gives_north_arrow_font), + "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(|t| text_gives_font(t, "layout-north-arrow-font")), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_north_arrow_font)), _ => false, } } -/// Whether a project's saved text requires `layout-north-arrow-font`, as one saved would: its -/// north arrows', its steps' and its notebooks'. Parsed only when the text may name a font, may +/// Whether a project's saved text requires the font `capability`, as one saved would: its +/// elements', its steps' and its notebooks'. Parsed only when the text may name a font, may /// hide the key ([`may_hide_a_key`]) or holds a step's base64 `data` ([`names_data`]). -fn text_gives_north_arrow_font(text: &str) -> bool { +fn text_gives_font(text: &str, capability: &str) -> bool { (text.contains("font") || may_hide_a_key(text) || names_data(text)) - && Project::from_json(text).is_ok_and(|p| p.required_capabilities().contains(&"layout-north-arrow-font")) + && Project::from_json(text).is_ok_and(|p| p.required_capabilities().contains(&capability)) +} + +fn scale_bars_with_font(e: &rustgis_map::layout::Element) -> bool { + e.kind.scale_bar_uses_font() +} + +/// A layout command that gives a scale bar a font (#3468), read as +/// [`command_uses_north_arrow_font`] reads a north arrow's. +fn command_uses_scale_bar_font(id: &str, params: &Value) -> bool { + match id { + "layout.addElement" => adds_with_font(params, "scaleBar"), + "layout.import" | "report.existingTemplate" => imported_layout_uses(params, &["\"font"], scale_bars_with_font), + "project.openText" => params.get("text").and_then(Value::as_str).is_some_and(|t| text_gives_font(t, "layout-scale-bar-font")), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_scale_bar_font)), + _ => false, + } +} + +/// Whether a `layout.addElement` of a `kind` element gives it a family other than the sans. +fn adds_with_font(params: &Value, kind: &str) -> bool { + params.get("kind").and_then(Value::as_str).is_some_and(|k| k.trim().eq_ignore_ascii_case(kind)) + && params + .get("font") + .and_then(Value::as_str) + .is_some_and(|f| rustgis_map::layout::FontFamily::from_name(f.trim()) != Some(rustgis_map::layout::FontFamily::Sans)) } /// Whether a command carries its layout inline with an element `uses`, as `layout.import` and @@ -1847,6 +1867,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static (elements().any(tables_with_a_look), "layout-table-look"), (elements().any(colorbars_with_labels), "layout-colorbar-labels"), (elements().any(north_arrows_with_font), "layout-north-arrow-font"), + (elements().any(scale_bars_with_font), "layout-scale-bar-font"), (elements().any(|e| e.kind.has_custom_border()), "layout-frame-border"), (elements().any(|e| e.kind.has_sections()), "layout-section"), (elements().any(|e| e.kind.is_profile()), "layout-profile"), @@ -2334,6 +2355,7 @@ mod tests { (&[], "layout.addElement", chart), (&["layout-colorbar-labels"], "layout.addElement", json!({"kind": "colorbar", "decimals": 2})), (&["layout-north-arrow-font"], "layout.addElement", json!({"kind": "northArrow", "font": "serif"})), + (&["layout-scale-bar-font"], "layout.addElement", json!({"kind": "scaleBar", "font": "serif"})), ]; let mut covered = std::collections::BTreeSet::new(); for (capability, id, params) in samples { @@ -2637,6 +2659,7 @@ mod tests { "layout-table-look", "layout-colorbar-labels", "layout-north-arrow-font", + "layout-scale-bar-font", "layout-frame-border", "layout-text-size", "layout-scale-bar-details", @@ -3866,6 +3889,68 @@ mod tests { } } + /// A scale bar's font (#3468) requires `layout-scale-bar-font`, in a saved layout and in + /// a saved command. + #[test] + fn scale_bar_font_capability_follows_saved_layouts_and_commands() { + use rustgis_map::layout::{ElementKind, FontFamily}; + let fixture = Project::from_json(include_str!("../../../schema/fixtures/layout_scale_bar_font.rgis")).unwrap(); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["layout-scale-bar-font"])); + let mut clean = fixture; + for e in &mut clean.layouts[0].elements { + if let ElementKind::ScaleBar { font, font_name, .. } = &mut e.kind { + (*font, *font_name) = (FontFamily::Sans, None); + } + } + let base = serde_json::to_value(&clean).unwrap(); + assert!(base.get("requires").is_none(), "a plain scale bar needs nothing"); + // Project texts a step opens: without the header an older reader would drop the font. + let mut headerless = saved.clone(); + headerless.as_object_mut().unwrap().remove("requires"); + let mut generic = headerless.clone(); + generic["layouts"][0]["elements"][1]["kind"]["ScaleBar"].as_object_mut().unwrap().remove("font_name"); + // Its key written with an escape, in a project whose name doesn't spell it. + let mut escaped = headerless.clone(); + escaped["name"] = json!("Bar"); + let escaped = escaped.to_string().replace("\"font", "\"\\u0066ont"); + let stepped = |params: Value| { + let mut p = base.clone(); + p["tasks"] = json!([{"name": "Inner", "steps": [{"title": "Add", "command": "layout.addElement", "params": params}]}]); + p.to_string() + }; + for (id, params, required) in [ + ("project.openText", json!({"text": headerless.to_string()}), true), + ("project.openText", json!({"text": saved.to_string()}), true), + ("project.openText", json!({"text": generic.to_string()}), true), + ("project.openText", json!({"text": escaped}), true), + ("project.openText", json!({"text": stepped(json!({"kind": "scaleBar", "font": "serif"}))}), true), + ("project.openText", json!({"text": stepped(json!({"kind": "text", "font": "serif"}))}), false), + ("project.openText", json!({"text": base.to_string()}), false), + // Left out on purpose: it names no element kind, and a text takes a font too. + ("layout.update", json!({"element": 2, "font": "serif"}), false), + ("layout.addElement", json!({"kind": "scaleBar", "font": "serif"}), true), + ("layout.addElement", json!({"kind": "scaleBar", "font": "DejaVu Serif"}), true), + ("layout.addElement", json!({"kind": "scaleBar", "font": "sans-serif"}), false), + ("layout.addElement", json!({"kind": "scaleBar", "font": null}), false), + ("layout.addElement", json!({"kind": "text", "font": "serif"}), false), + ("layout.import", json!({"text": saved["layouts"][0].to_string()}), true), + ("layout.import", json!({"text": base["layouts"][0].to_string()}), false), + ] { + let script = format!("{id} {params}"); + for value in [ + json!([{"name": "Task", "steps": [{"title": "Bar", "command": id, "params": params}]}]), + json!([{"name": "Script", "steps": [{"title": "Bar", "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 has = saved["requires"].as_array().is_some_and(|r| r.contains(&json!("layout-scale-bar-font"))); + assert_eq!(has, required, "{id} {params}"); + } + } + } + #[test] fn field_identity_is_preserved_and_required_in_a_plain_saved_project() { let project = Project::from_json(include_str!("../../../schema/fixtures/field_origin.rgis")).unwrap(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d5e17b9e72..62dd118550 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -198,6 +198,10 @@ mod layout_open; #[path = "tests/layout_north_font.rs"] mod layout_north_font; +/// A scale bar's font (#3468). +#[path = "tests/layout_scale_font.rs"] +mod layout_scale_font; + #[path = "tests/sde_connections.rs"] mod sde_connections; @@ -49030,11 +49034,12 @@ fn text_elements_take_a_font_family() { assert!(s.run("layout.addElement", &json!({"kind": "text", "font": bad})).is_err()); } assert_eq!(font(&s, title), FontFamily::Serif); - // Only a text or a north arrow takes a family: another element refuses it rather than ignore it. - let bar = s.run("layout.addElement", &json!({"kind": "scaleBar"})).unwrap()["element"].clone(); - let err = s.run("layout.update", &json!({"element": bar, "font": "serif"})).unwrap_err(); + // Only a text, a north arrow or a scale bar takes a family: another element refuses it rather + // than ignore it. + let shape = s.run("layout.addElement", &json!({"kind": "rectangle"})).unwrap()["element"].clone(); + let err = s.run("layout.update", &json!({"element": shape, "font": "serif"})).unwrap_err(); assert!(err.contains("only text elements"), "{err}"); - assert!(s.run("layout.addElement", &json!({"kind": "scaleBar", "font": "serif"})).unwrap_err().contains("only text elements")); + assert!(s.run("layout.addElement", &json!({"kind": "rectangle", "font": "serif"})).unwrap_err().contains("only text elements")); // The page draws either way. assert!(s.run("layout.update", &json!({"element": title, "text": "Mapa do Brasil", "bold": true, "italic": true})).is_ok()); assert!(!crate::cmd::layout::layout_bytes(&mut s, 0, false, 72.0, false).unwrap().is_empty()); @@ -49103,8 +49108,8 @@ fn text_elements_take_an_installed_font_family_by_name() { assert!(s.run("layout.update", &p).is_err(), "{bad}"); } assert_eq!(font(&s, id), (FontFamily::Sans, None), "a refused call changes nothing"); - let bar = s.run("layout.addElement", &json!({"kind": "scaleBar"})).unwrap()["element"].clone(); - assert!(s.run("layout.update", &json!({"element": bar, "fallback": "serif"})).unwrap_err().contains("only text elements")); + let shape = s.run("layout.addElement", &json!({"kind": "rectangle"})).unwrap()["element"].clone(); + assert!(s.run("layout.update", &json!({"element": shape, "fallback": "serif"})).unwrap_err().contains("only text elements")); // An installed family, where this computer has a small one (its file read whatever the // session's budget): kept as the font names it, its fallback its own class, and nothing said. let small = |f: &&rustgis_render::families::Family| { diff --git a/crates/engine/src/tests/layout_north_font.rs b/crates/engine/src/tests/layout_north_font.rs index 5add012570..fac9b753a0 100644 --- a/crates/engine/src/tests/layout_north_font.rs +++ b/crates/engine/src/tests/layout_north_font.rs @@ -131,8 +131,8 @@ fn a_bad_font_or_fallback_is_refused() { #[test] fn an_element_without_a_font_still_refuses_one() { let (mut s, _) = arrowed(json!({})); - let said = "only text elements and north arrows take a font or a fallback"; - let bar = s.run("layout.addElement", &json!({"kind": "scaleBar"})).unwrap()["element"].clone(); - refused(&mut s, "layout.update", json!({"element": bar, "font": "serif"}), said); + let said = "only text elements, north arrows and scale bars take a font or a fallback"; + let shape = s.run("layout.addElement", &json!({"kind": "rectangle"})).unwrap()["element"].clone(); + refused(&mut s, "layout.update", json!({"element": shape, "font": "serif"}), said); refused(&mut s, "layout.addElement", json!({"kind": "rectangle", "font": "serif"}), said); } diff --git a/crates/engine/src/tests/layout_scale_font.rs b/crates/engine/src/tests/layout_scale_font.rs new file mode 100644 index 0000000000..81e2a77da0 --- /dev/null +++ b/crates/engine/src/tests/layout_scale_font.rs @@ -0,0 +1,129 @@ +//! A layout scale bar's font (#3468). + +use super::*; + +/// A map layout with a scale bar of its own; the bar's element id. +fn barred(params: Value) -> (Session, u64) { + let mut s = world(); + s.run("layout.new", &json!({"template": "map"})).unwrap(); + let mut p = params; + p["kind"] = json!("scaleBar"); + let id = s.run("layout.addElement", &p).unwrap()["element"].as_u64().unwrap(); + (s, id) +} + +/// The stored scale bar `id`, as the project saves it. +fn bar(s: &Session, id: u64) -> Value { + let e = s.project.layouts[0].elements.iter().find(|e| u64::from(e.id) == id).unwrap(); + serde_json::to_value(&e.kind).unwrap()["ScaleBar"].clone() +} + +/// The font and its name as `bar` saves them. +fn font(s: &Session, id: u64) -> (Value, Value) { + let b = bar(s, id); + (b["font"].clone(), b["font_name"].clone()) +} + +fn update(s: &mut Session, id: u64, mut params: Value) -> Result { + params["element"] = json!(id); + s.run("layout.update", ¶ms) +} + +/// Whether the project, as saved, requires the scale bar's font capability. +fn requires_font(s: &Session) -> bool { + let saved = serde_json::to_value(&s.project).unwrap(); + saved["requires"].as_array().is_some_and(|r| r.contains(&json!("layout-scale-bar-font"))) +} + +/// Runs `command` 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, ¶ms).expect_err(¶ms.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 svg(s: &mut Session) -> String { + rustgis_render::svg::layout_svg(&s.project.layouts[0], &mut s.project.maps, 72.0, &Default::default()).unwrap().0 +} + +#[test] +fn a_scale_bar_without_a_font_saves_none() { + for params in [json!({}), json!({"font": null, "fallback": null}), json!({"font": "sans"}), json!({"font": "sans-serif"})] { + let (s, id) = barred(params.clone()); + assert_eq!(font(&s, id), (Value::Null, Value::Null), "{params}"); + assert!(!requires_font(&s), "{params}"); + } +} + +#[test] +fn a_scale_bar_takes_the_serif_and_draws_its_labels_in_it() { + let (mut s, id) = barred(json!({})); + let plain = svg(&mut s); + let out = update(&mut s, id, json!({"font": "serif"})).unwrap(); + assert_eq!(font(&s, id), (json!("Serif"), Value::Null)); + assert!(requires_font(&s)); + let serif = rustgis_render::fonts::serif_available(); + assert_eq!(out.get("warning").is_some(), !serif, "{out}"); + if serif { + assert_ne!(svg(&mut s), plain, "the labels are drawn in the serif"); + } + // Another change keeps the font and says nothing of it. + assert_eq!(update(&mut s, id, json!({"divisions": 2})).unwrap(), Value::Null); + assert_eq!(font(&s, id).0, json!("Serif")); + s.run("edit.undo", &json!({})).unwrap(); + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(font(&s, id), (Value::Null, Value::Null), "one step each"); + assert_eq!(svg(&mut s), plain); +} + +#[test] +fn a_scale_bars_family_not_installed_is_kept_drawn_in_its_fallback_and_said() { + let (mut s, id) = barred(json!({"font": " No Such Family 3468 "})); + assert_eq!(font(&s, id), (Value::Null, json!("No Such Family 3468"))); + assert!(requires_font(&s)); + let out = s.run("layout.addElement", &json!({"kind": "scaleBar", "font": "No Such Family 3468"})).unwrap(); + assert!(out["warning"].as_str().is_some_and(|w| w.starts_with("No Such Family 3468 is not installed")), "{out}"); + let out = update(&mut s, id, json!({"fallback": "serif"})).unwrap(); + assert!(out["warning"].as_str().is_some_and(|w| w.starts_with("No Such Family 3468")), "{out}"); + assert_eq!(font(&s, id), (json!("Serif"), json!("No Such Family 3468"))); + // Through a save and back. + let back: rustgis_map::layout::Layout = serde_json::from_str(&serde_json::to_string(&s.project.layouts[0]).unwrap()).unwrap(); + assert_eq!(back, s.project.layouts[0]); + // A generic family clears the name. + update(&mut s, id, json!({"font": "sans"})).unwrap(); + assert_eq!(font(&s, id), (Value::Null, Value::Null)); +} + +#[test] +fn a_scale_bar_keeps_an_installed_family_as_the_font_names_it() { + let small = |f: &&rustgis_render::families::Family| { + f.listed && f.faces.iter().all(|face| std::fs::metadata(&face.path).is_ok_and(|m| m.len() < 4 << 20)) + }; + let Some(f) = rustgis_render::families::installed().iter().find(small) else { return }; + let (s, id) = barred(json!({"font": f.name.to_uppercase()})); + assert_eq!(font(&s, id).1, json!(f.name)); +} + +#[test] +fn a_scale_bars_bad_font_or_fallback_is_refused() { + let (mut s, id) = barred(json!({})); + let name = "font must be sans, serif or an installed font family's name"; + for (bad, said) in [ + (json!({"font": " "}), name), + (json!({"font": 2}), name), + (json!({"font": ["serif"]}), name), + (json!({"fallback": "serif"}), "fallback goes with a font family's name"), + (json!({"font": "serif", "fallback": "sans"}), "fallback goes with a font family's name, not sans or serif"), + (json!({"font": "Arial", "fallback": "mono"}), "fallback must be sans or serif"), + ] { + let mut add = bad.clone(); + add["kind"] = json!("scaleBar"); + refused(&mut s, "layout.addElement", add, said); + let mut change = bad; + change["element"] = json!(id); + refused(&mut s, "layout.update", change, said); + } +} diff --git a/crates/map/src/layout/elements.rs b/crates/map/src/layout/elements.rs index 45bf450a93..d64b28a0f6 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -112,6 +112,12 @@ pub enum ElementKind { /// What gives way when the bar's length does not fit its box. #[serde(default, skip_serializing_if = "is_default")] fit: ScaleBarFit, + /// The numbers' and unit's family, as a text's `font`; left out when sans. + #[serde(default, skip_serializing_if = "is_sans")] + font: FontFamily, + /// An installed family for them, as a text's `font_name`. + #[serde(default, deserialize_with = "crate::symbology::de_font", skip_serializing_if = "Option::is_none")] + font_name: Option, }, Legend { frame: u32, @@ -496,6 +502,8 @@ impl ElementKind { unit_label_position: UnitLabelPosition::default(), decimals: None, fit: ScaleBarFit::default(), + font: FontFamily::Sans, + font_name: None, } } @@ -758,10 +766,12 @@ impl ElementKind { matches!(self, ElementKind::Colorbar { text_size, decimals, .. } if !is_colorbar_text_pt(text_size) || decimals.is_some()) } - /// The installed family a text or a north arrow's `N` is set in by name. + /// The installed family a text, a north arrow's `N` or a scale bar's labels are set in by name. pub fn named_font(&self) -> Option<&str> { match self { - ElementKind::Text { font_name, .. } | ElementKind::NorthArrow { font_name, .. } => font_name.as_deref(), + ElementKind::Text { font_name, .. } | ElementKind::NorthArrow { font_name, .. } | ElementKind::ScaleBar { font_name, .. } => { + font_name.as_deref() + } _ => None, } } @@ -772,6 +782,12 @@ impl ElementKind { matches!(self, ElementKind::NorthArrow { font, font_name, .. } if !is_sans(font) || font_name.is_some()) } + /// Whether this is a scale bar with a font of its own (#3468): an older reader would draw its + /// labels in the sans and save it again without. + pub fn scale_bar_uses_font(&self) -> bool { + matches!(self, ElementKind::ScaleBar { font, font_name, .. } if !is_sans(font) || font_name.is_some()) + } + /// Whether a chart uses what a chart had none of before (grouping, its statistic, its order, /// its limit, an "Other" bar): an older reader would draw it as one bar per feature, the 20 /// largest, and save it again without them; a statistic kept while ungrouped is lost so too. diff --git a/crates/render/src/layout/scale_bar.rs b/crates/render/src/layout/scale_bar.rs index 3c64d8dd1c..dbfaf43d19 100644 --- a/crates/render/src/layout/scale_bar.rs +++ b/crates/render/src/layout/scale_bar.rs @@ -96,14 +96,26 @@ pub(super) fn bar_label(total: f64, divisions: usize, i: usize, abbr: &str, comm /// included, so a box can be the size of its bar (#1379). `width_pt` when no narrower one draws /// that bar; `None` when it draws none. pub fn scale_bar_width_pt(ground_per_pt: f64, width_pt: f64, bar: (ScaleUnits, usize, f64), comma: bool, pad_pt: f64) -> Option { + plain_width_pt(ground_per_pt, width_pt, bar, text::Face::default(), comma, pad_pt) +} + +/// [`scale_bar_width_pt`] with the labels measured in `face`. +fn plain_width_pt( + ground_per_pt: f64, + width_pt: f64, + bar: (ScaleUnits, usize, f64), + face: text::Face, + comma: bool, + pad_pt: f64, +) -> Option { let (units, divisions, text_size) = bar; let k = layout_text_scale(text_size, SCALE_BAR_TEXT_PT); let plan = bar_plan(ground_per_pt, width_pt, units)?; let divisions = divisions.clamp(1, rustgis_map::layout::MAX_SCALE_DIVISIONS); let len = plan.total * plan.unit_m / ground_per_pt; let last = bar_label(plan.total, divisions, divisions, plan.abbr, comma); - let half = f64::from(text::measure(&last, (SCALE_BAR_TEXT_PT * k) as f32, false)) / 2.0; - let inset = f64::from(bar_inset(&bar_label(plan.total, divisions, 0, plan.abbr, comma), k as f32, 1.0)); + let half = f64::from(text::measure_in(&last, (SCALE_BAR_TEXT_PT * k) as f32, face)) / 2.0; + let inset = f64::from(bar_inset(&bar_label(plan.total, divisions, 0, plan.abbr, comma), k as f32, 1.0, face)); // A little over the share the bar takes, so the f32 rectangle an export rebuilds the width // from (its error growing with the element's place on the page) doesn't pick the next shorter // length: a ten-thousandth, 0.003 mm on a 30 mm box. @@ -121,7 +133,8 @@ pub fn scale_bar_width_pt(ground_per_pt: f64, width_pt: f64, bar: (ScaleUnits, u pub fn scale_bar_box_width_pt(ground_per_pt: f64, width_pt: f64, bar: &ElementKind, comma: bool, pad_pt: f64) -> Option { let options = BarOptions::of(bar)?; if !bar.scale_bar_uses_details() { - return scale_bar_width_pt(ground_per_pt, width_pt, (options.units, options.divisions, options.text_size), comma, pad_pt); + let bar = (options.units, options.divisions, options.text_size); + return plain_width_pt(ground_per_pt, width_pt, bar, options.face, comma, pad_pt); } // At a point a pixel; the height leaves the width as it is. let place = |w: f64| Rect::from_xywh(0.0, 0.0, w as f32, 60.0).and_then(|r| bar_layout(r, ground_per_pt, &options, 1.0, comma)); @@ -163,8 +176,8 @@ pub fn scale_bar_box_width_pt(ground_per_pt: f64, width_pt: f64, bar: &ElementKi /// reaches no further past the side than it does at the default size, as the bar moves down to /// keep its labels from reaching higher. At the default size, [`BAR_INSET`]: pixels, as the /// drawing has always placed the bar, not following `ppp`, which only the labels' widths do. -pub(super) fn bar_inset(first: &str, k: f32, ppp: f32) -> f32 { - let half = |k: f32| text::measure(first, SCALE_BAR_TEXT_PT as f32 * k * ppp, false) / 2.0; +pub(super) fn bar_inset(first: &str, k: f32, ppp: f32, face: text::Face) -> f32 { + let half = |k: f32| text::measure_in(first, SCALE_BAR_TEXT_PT as f32 * k * ppp, face) / 2.0; (BAR_INSET * k).max(half(k) - (half(1.0) - BAR_INSET).max(0.0)) } @@ -182,6 +195,8 @@ pub(super) struct BarOptions<'a> { pub(super) decimals: Option, pub(super) text_size: f64, pub(super) fit: ScaleBarFit, + /// The face its labels are drawn and measured in. + pub(super) face: text::Face, } impl<'a> BarOptions<'a> { @@ -199,11 +214,14 @@ impl<'a> BarOptions<'a> { decimals, text_size, fit, + font, + font_name, .. } = kind else { return None; }; + let face = text_style(false, false, *font, font_name.as_deref(), TextAlign::Center, 0.0).face; Some(BarOptions { units: *units, divisions: *divisions, @@ -216,6 +234,7 @@ impl<'a> BarOptions<'a> { decimals: *decimals, text_size: *text_size, fit: *fit, + face, }) } } @@ -348,7 +367,7 @@ pub(super) fn bar_layout(r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, ppp: let bar_h = (r.height() * 0.28).min(6.0 * p); // Its labels' size, and the default's, in pixels. let (px, px8) = (SCALE_BAR_TEXT_PT as f32 * k * 1.33 * p, SCALE_BAR_TEXT_PT as f32 * 1.33 * p); - let measure_at = |s: &str, px: f32| text::measure(s, px / 1.33, false); + let measure_at = |s: &str, px: f32| text::measure_in(s, px / 1.33, bar.face); let measure = |s: &str| measure_at(s, px); let half = |s: &str| measure(s) / 2.0; let gap = 3.0 * k * p; @@ -405,7 +424,7 @@ pub(super) fn bar_layout(r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, ppp: // How far in the bar starts for labels `k` times the default size: past a first label before // zero, or as far as the first label at zero needs ([`bar_inset`]). let zero = number(total, divs, 0); - let inset_at = |k: f32, pad: f32| if before > 0 { BAR_INSET * k + pad } else { bar_inset(&zero, k, p) }; + let inset_at = |k: f32, pad: f32| if before > 0 { BAR_INSET * k + pad } else { bar_inset(&zero, k, p, bar.face) }; let x0 = r.x() + inset_at(k, pad); // The box less the insets the bar keeps. let (inner_left, inner_right) = (r.x() + BAR_INSET, r.right() - BAR_INSET); @@ -592,11 +611,21 @@ pub(super) fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarO } } // Labels at the divisions, over or under the bar, and the unit label where it is asked. + // A line of it, placed across as `align` says, in the bar's face. + let write = |pm: &mut Canvas, s: &str, x: f32, y: f32, align: text::Align| { + let w = || text::measure_in(s, px / 1.33, bar.face); + let left = match align { + text::Align::Left => x, + text::Align::Center => x - w() / 2.0, + text::Align::Right => x - w(), + }; + text::styled_at(pm, s, left, y, px, dark, bar.face, 0.0); + }; for (x, s) in &labels { - text::text_at(pm, s, *x, label_y, px, dark, false, text::Align::Center, false); + write(pm, s, *x, label_y, text::Align::Center); } if let Some(BarUnit { x, y, text: shown, align }) = unit { - text::text_at(pm, &shown, x, y, px, dark, false, align, false); + write(pm, &shown, x, y, align); } } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 705ec39c58..6fdf2edf8a 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6946,6 +6946,37 @@ fn a_scale_bar_draws_the_same_in_its_narrowest_element() { assert!(w <= 300.0 && bar_plan(100.0, w, ScaleUnits::Miles) == bar_plan(100.0, 300.0, ScaleUnits::Miles)); } +/// A bar's labels in another face (#3468) are drawn in it and measured with it: the box that +/// holds a wider face is no narrower, and its bar still fits it. +#[test] +fn a_scale_bars_labels_are_drawn_and_measured_in_its_face() { + if !crate::fonts::serif_available() { + return; + } + let mut serif = ElementKind::scale_bar(0); + if let ElementKind::ScaleBar { font, text_size, .. } = &mut serif { + (*font, *text_size) = (rustgis_map::layout::FontFamily::Serif, 20.0); + } + let mut sans = serif.clone(); + if let ElementKind::ScaleBar { font, .. } = &mut sans { + *font = rustgis_map::layout::FontFamily::Sans; + } + let (a, b) = (BarOptions::of(&sans).unwrap(), BarOptions::of(&serif).unwrap()); + assert_ne!(draw_bar(&a, 300).data(), draw_bar(&b, 300).data()); + let r = Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(); + let placed = |bar: &BarOptions<'_>| bar_layout(r, 100.0, bar, 1.0, false).unwrap(); + let last = |p: &BarLayout, face| p.labels.last().map(|(x, s)| x + text::measure_in(s, p.px / 1.33, face) / 2.0).unwrap(); + let right = placed(&b); + assert!(right.right >= last(&right, b.face) - 0.01, "the ink the box counts is the face's"); + for kind in [&sans, &serif] { + let w = scale_bar_box_width_pt(100.0, 300.0, kind, false, 4.0).unwrap(); + let bar = BarOptions::of(kind).unwrap(); + let narrow = Rect::from_xywh(0.0, 0.0, w as f32, 60.0).unwrap(); + let p = bar_layout(narrow, 100.0, &bar, 1.0, false).unwrap(); + assert!(!p.cramped && last(&p, bar.face) <= w as f32 + 0.01, "{w} points"); + } +} + #[test] fn scale_bars_draw_in_their_colours() { let mut pm = Pixmap::new(300, 60).unwrap(); diff --git a/crates/ui-egui/src/layoutview/format/scalebar.rs b/crates/ui-egui/src/layoutview/format/scalebar.rs index 405ff88312..554b91c8ad 100644 --- a/crates/ui-egui/src/layoutview/format/scalebar.rs +++ b/crates/ui-egui/src/layoutview/format/scalebar.rs @@ -33,6 +33,8 @@ pub(super) fn scale_bar_rows( unit_label_position, decimals, fit, + font, + font_name, .. } = &e.kind else { @@ -84,6 +86,16 @@ pub(super) fn scale_bar_rows( if let Some(pt) = text_size_row(ui, tl!("Text size"), drag_key("textSize"), *text_size) { update(app, json!({"textSize": pt})); } + // The numbers' and unit's font, chosen as a text's is. + let (mut family, mut named) = (*font, font_name.clone()); + if crate::textform::font_rows(ui, egui::Id::unique(("scale_font", id)), &mut family, &mut named, true) { + // A named family with its fallback, else the generic one. + let change = match &named { + Some(n) => json!({"font": n, "fallback": family.code()}), + None => json!({"font": family.code()}), + }; + update(app, change); + } // Each division split into parts, and divisions left of zero. for (label, key, current, max) in [ (tl!("Subdivisions"), "subdivisions", *subdivisions, MAX_SCALE_SUBDIVISIONS), diff --git a/crates/ui-egui/src/layoutview/tests.rs b/crates/ui-egui/src/layoutview/tests.rs index 9499e7e020..a3846dea8a 100644 --- a/crates/ui-egui/src/layoutview/tests.rs +++ b/crates/ui-egui/src/layoutview/tests.rs @@ -1502,6 +1502,45 @@ fn a_north_arrows_font_is_picked_in_the_format_pane() { assert_eq!(family(h.state()), FontFamily::Sans, "one step undoes it"); } +/// A scale bar's Font in the Format pane (#3468): Serif picked from the list is stored as one +/// undoable step. +#[test] +fn a_scale_bars_font_is_picked_in_the_format_pane() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + use rustgis_engine::map::layout::{ElementKind, FontFamily}; + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Scale"})).unwrap(); + let li = app.session.active_layout.unwrap(); + let bar = app.session.project.layouts[li].elements.iter().find(|e| e.name == "Scale Bar").unwrap().id; + app.layout.selected = Some(bar); + let family = move |app: &RustGisApp| match &app.session.project.layouts[li].element(bar).unwrap().kind { + ElementKind::ScaleBar { font, .. } => *font, + other => panic!("{other:?}"), + }; + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 900.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + with_format(app, ui); + }, + app, + ); + h.run_steps(3); + assert_eq!(family(h.state()), FontFamily::Sans); + h.get_by_role_and_label(Role::ComboBox, "Font").click(); + h.run_steps(2); + h.get_by_label("Serif").click(); + h.run_steps(3); + assert_eq!(family(h.state()), FontFamily::Serif); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(family(h.state()), FontFamily::Sans, "one step undoes it"); +} + /// A text element's "Wrap to the box" (#2346): off as it is added, on when ticked, as one /// undoable step, and off again. #[test] diff --git a/docs/maintaining.md b/docs/maintaining.md index 39c87921ce..e4d755684b 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -326,6 +326,14 @@ north arrow with a font other than the sans require it too. A saved `layout.impo `project.openText` whose project needs it. A saved `layout.update` doesn't: it names no element kind, and an older reader refuses a font on a north arrow when the step runs. +Projects with a layout scale bar whose labels have a font of their own (`font` or `font_name` on a +scale bar) require `layout-scale-bar-font`, so an older reader refuses them instead of drawing the +sans-serif and saving the bar again without (#3468). Saved `layout.addElement` commands for a scale +bar with a font other than the sans require it too. A saved `layout.import` or +`report.existingTemplate` carrying such a bar requires it as well, as does a saved +`project.openText` whose project needs it. A saved `layout.update` doesn't, for the reason given for +a north arrow's. + Projects with a map frame whose border isn't the default dark grey 0.8 pt line (`border_color`, `border_width` on a map frame, a width of 0 drawing none) require `layout-frame-border`, so an older reader refuses them instead of drawing the default border and saving the frame again diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 3e7da78f6f..aa15c4e56a 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -443,7 +443,9 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu points, 8 by default; the room over the bar and between the labels follows, the bar keeps its length and height and moves down, and right, in its box to make room for larger labels, which reach no further past its top and left than the default size's, and `null` gives the default - back) (`"style":"line","units":"miles","divisions":2,"color":"#1F4E79","textSize":12`). A box too + back) and the **Font** of its numbers and unit (sans-serif by default), with its **Fallback**, + both chosen as a text's are; its labels are measured in it, a wider family taking more room + (`"style":"line","units":"miles","divisions":2,"color":"#1F4E79","textSize":12,"font":"serif"`). A box too small for its labels and bar (too short, which draws the bar below it, too narrow for its last label, or so narrow that a larger last label runs into the first), or a label that runs off the page, is said when its place, size, text size, units, divisions or details change or its frame is diff --git a/schema/fixtures/layout_scale_bar_font.rgis b/schema/fixtures/layout_scale_bar_font.rgis new file mode 100644 index 0000000000..0db6302b0b --- /dev/null +++ b/schema/fixtures/layout_scale_bar_font.rgis @@ -0,0 +1 @@ +{"format":2,"requires":["layout-scale-bar-font"],"name":"Scale bar font","maps":[{"name":"Map","layers":[],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":1}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[{"name":"Listed","width":120,"height":90,"elements":[{"id":1,"name":"Frame","x":10,"y":10,"w":60,"h":70,"kind":{"MapFrame":{"map":"Map","center":{"x":0,"y":0},"scale":1000000}}},{"id":2,"name":"Scale Bar","x":10,"y":75,"w":60,"h":12,"kind":{"ScaleBar":{"frame":1,"font":"Serif","font_name":"DejaVu Serif"}}}]}],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 00562ae933..7435200c38 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1282,6 +1282,7 @@ "layout-table-look", "layout-colorbar-labels", "layout-north-arrow-font", + "layout-scale-bar-font", "field-generation", "field-package", "field-conflicts", @@ -1426,6 +1427,7 @@ "layout-table-look", "layout-colorbar-labels", "layout-north-arrow-font", + "layout-scale-bar-font", "field-generation", "field-package", "field-conflicts", From 1c65e6310cbbc9c2308d7d602ab660555710e2df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 15:36:47 -0500 Subject: [PATCH 2/6] fix(layout): measure a publication's scale box again for the bar's font --- crates/engine/src/cmd/layout/frame.rs | 2 +- crates/engine/src/cmd/layout/legend.rs | 6 +++-- crates/engine/src/tests/layout_scale_font.rs | 23 ++++++++++++++++++++ docs/user-guide/layouts.md | 2 +- 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout/frame.rs b/crates/engine/src/cmd/layout/frame.rs index 7df4a0b4e1..4581605756 100644 --- a/crates/engine/src/cmd/layout/frame.rs +++ b/crates/engine/src/cmd/layout/frame.rs @@ -305,7 +305,7 @@ pub(in crate::cmd::layout) fn frame_view_changed(s: &mut Session, li: usize, fra /// box as wide as `before` (what it was measured from before the change: its frame, bar and text) /// is measured again: one set by hand keeps its width. A change to the text under the bar or to /// anything of the bar's that changes its labels or their room (its units, divisions, text size, -/// subdivisions, divisions before zero, labels, unit label and where it sits, decimals or fit) +/// subdivisions, divisions before zero, labels, unit label and where it sits, decimals, fit or font) /// measures it again too, with every setting the bar has. A box that would then cover the legend, /// locator or north arrow, which it didn't, stays as it was, which is said. pub(in crate::cmd::layout) fn refit_scale_box(s: &mut Session, li: usize, before: &BoxBasis) { diff --git a/crates/engine/src/cmd/layout/legend.rs b/crates/engine/src/cmd/layout/legend.rs index e5c9c35ddc..81d1a99d8e 100644 --- a/crates/engine/src/cmd/layout/legend.rs +++ b/crates/engine/src/cmd/layout/legend.rs @@ -262,8 +262,8 @@ pub(in crate::cmd) fn say_unfitted_legends_in( /// What a scale bar is given that changes its labels (#2581): its text size (`null` included, which /// gives the default back), its units and divisions, which change what they say, and its details, /// which change its rows, its labels and the room they have (`null` included: a unit label given -/// back is its abbreviation again). -pub(in crate::cmd::layout) const BAR_FIT_KEYS: [&str; 10] = [ +/// back is its abbreviation again), and the font they are measured in. +pub(in crate::cmd::layout) const BAR_FIT_KEYS: [&str; 12] = [ "textSize", "units", "divisions", @@ -274,6 +274,8 @@ pub(in crate::cmd::layout) const BAR_FIT_KEYS: [&str; 10] = [ "unitLabelPosition", "decimals", "fit", + "font", + "fallback", ]; /// The `"columns"` a legend is given, refused outside 1 to [`MAX_LEGEND_COLUMNS`]: the one reader diff --git a/crates/engine/src/tests/layout_scale_font.rs b/crates/engine/src/tests/layout_scale_font.rs index 81e2a77da0..3bde0cabf6 100644 --- a/crates/engine/src/tests/layout_scale_font.rs +++ b/crates/engine/src/tests/layout_scale_font.rs @@ -127,3 +127,26 @@ fn a_scale_bars_bad_font_or_fallback_is_refused() { refused(&mut s, "layout.update", change, said); } } + +/// A publication's scale bar box is measured again for the labels' new face, as for any other +/// change to them. +#[test] +fn a_publication_scale_box_follows_the_bars_font() { + if !rustgis_render::fonts::serif_available() { + return; + } + let mut s = world(); + s.run("layout.publication", &json!({"profile": "thesis-half", "extent": [-46.8, -11.6, -38.5, -2.2]})).unwrap(); + let li = s.project.layouts.len() - 1; + let named = |s: &Session, n: &str| s.project.layouts[li].elements.iter().find(|e| e.name == n).unwrap().clone(); + let auto = |s: &Session| crate::cmd::layout::scale_box_auto(s, li).expect("an automatic box"); + let bar = named(&s, "Scale Bar").id; + // A unit after the bar, whose width follows the face. + let unit = json!({"layout": li, "element": bar, "unitLabel": "Kilometres", "unitLabelPosition": "afterBar"}); + s.run("layout.update", &unit).unwrap(); + let sans = named(&s, "Scale Box").w; + s.run("layout.update", &json!({"layout": li, "element": bar, "font": "serif"})).unwrap(); + let serif = named(&s, "Scale Box").w; + assert!((auto(&s) - sans).abs() > 0.05, "the faces measure differently: {sans} vs {}", auto(&s)); + assert!((serif - auto(&s)).abs() < 0.01, "measured for the serif: {serif} vs {}", auto(&s)); +} diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index aa15c4e56a..3618e80c34 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -448,7 +448,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu (`"style":"line","units":"miles","divisions":2,"color":"#1F4E79","textSize":12,"font":"serif"`). A box too small for its labels and bar (too short, which draws the bar below it, too narrow for its last label, or so narrow that a larger last label runs into the first), or a label that runs off the - page, is said when its place, size, text size, units, divisions or details change or its frame is + page, is said when its place, size, text size, units, divisions, details or font change or its frame is drawn at another scale, and an export reports it as cut off, as it does a text. A locked scale bar refuses a new text size, `null` included. It also takes the details printed maps commonly use: **Subdivisions** (0 to 10: the first division after zero cut into unlabelled parts), **Divisions before zero** (0 to 2, counted toward the ten in all, labelled with From 777a6e189e383405888979ae7aee3af892dca622 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 16:18:02 -0500 Subject: [PATCH 3/6] fix(layout): judge a scale bar's labels off the page in its font --- crates/render/src/layout/losses.rs | 11 ++++++---- crates/render/src/layout/tests.rs | 35 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/render/src/layout/losses.rs b/crates/render/src/layout/losses.rs index 13bfc2b8c6..8dbff932e4 100644 --- a/crates/render/src/layout/losses.rs +++ b/crates/render/src/layout/losses.rs @@ -64,7 +64,8 @@ pub fn text_loss(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, id: u /// Whether a scale bar `e` drawn in `r` puts a label's ink past the page's `size` in pixels, and /// whether its box is too small for its labels and bar ([`BarLayout::cramped`]), its labels placed /// by [`bar_layout`] as the drawing places them: their line's middle at `label_y`, each centred on -/// its advance as `text_at` draws it, and its unit label where it is drawn; and whether that unit +/// its advance in the bar's face as the drawing writes it, and its unit label where it is drawn; +/// and whether that unit /// label is shortened or left out to fit ([`BarLayout::unit_cut`]). `None` when it draws no bar. pub(super) fn bar_labels_cut( layout: &Layout, @@ -78,14 +79,16 @@ pub(super) fn bar_labels_cut( let ElementKind::MapFrame { map, center, scale, bearing, pitch, .. } = &layout.element(*frame)?.kind else { return None }; let m = maps.get(map_index(maps, map)?)?; let ground = m.ground_res_at(&frame_camera(m, *center, *scale, *bearing, *pitch)); - let bar = bar_layout(r, ground, &BarOptions::of(&e.kind)?, f64::from(ppp), layout.decimal_comma)?; + let options = BarOptions::of(&e.kind)?; + let bar = bar_layout(r, ground, &options, f64::from(ppp), layout.decimal_comma)?; + let face = options.face; let (w, h) = size; // Its labels, centred on their divisions, and its unit label where it is drawn. let unit = bar.unit.as_ref().map(|u| (u.x, u.y, u.text.as_str(), matches!(u.align, text::Align::Center))); let drawn = bar.labels.iter().map(|(x, s)| (*x, bar.label_y, s.as_str(), true)).chain(unit); let off_page = drawn.into_iter().any(|(x, y, s, centred)| { - let pen = if centred { x - text::measure(s, bar.px / 1.33, false) / 2.0 } else { x }; - text::styled_bounds(s, bar.px, text::Face::default(), 0.0) + let pen = if centred { x - text::measure_in(s, bar.px / 1.33, face) / 2.0 } else { x }; + text::styled_bounds(s, bar.px, face, 0.0) .is_some_and(|ink| pen + ink.left() < 0.0 || y + ink.top() < 0.0 || pen + ink.right() > w || y + ink.bottom() > h) }); Some((off_page, bar.cramped, bar.unit_cut)) diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 6fdf2edf8a..e0d75e43c2 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6977,6 +6977,41 @@ fn a_scale_bars_labels_are_drawn_and_measured_in_its_face() { } } +/// A label off the page is judged in the bar's own face (#3468): said once the page ends inside +/// the ink drawn, and not with the page just past it. +#[test] +fn a_scale_bars_label_off_the_page_is_judged_in_its_face() { + if !crate::fonts::serif_available() { + return; + } + let maps = vec![Map::new("m")]; + let mut l = Layout::new("Page", 120.0, 90.0); + let frame = l.add( + "Frame", + (10.0, 30.0, 100.0, 50.0), + serde_json::from_value(serde_json::json!({"MapFrame":{"map":"m", "center":{"x":0,"y":0}, "scale":1000000}})).unwrap(), + ); + let mut kind = ElementKind::scale_bar(frame); + if let ElementKind::ScaleBar { font, text_size, units, unit_label, unit_label_position, .. } = &mut kind { + (*font, *text_size, *units) = (rustgis_map::layout::FontFamily::Serif, 20.0, ScaleUnits::Kilometers); + (*unit_label, *unit_label_position) = (Some("Kilometres".into()), UnitLabelPosition::AfterBar); + } + let id = l.add("Scale Bar", (0.0, 0.0, 100.0, 20.0), kind); + let e = l.element(id).unwrap(); + let r = Rect::from_xywh(0.0, 10.0, 400.0, 80.0).unwrap(); + let Some(ElementKind::MapFrame { center, scale, .. }) = l.element(frame).map(|e| &e.kind) else { panic!("a frame") }; + let ground = maps[0].ground_res_at(&frame_camera(&maps[0], *center, *scale, 0.0, 0.0)); + let mut pm = Pixmap::new(600, 100).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let bar = BarOptions::of(&e.kind).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &bar, DEFAULT_COLORS, 1.0, false)); + let marked = |x: &u32| (0..pm.height()).any(|y| pm.pixel(*x, y).is_some_and(|p| p.red() < 250)); + let right = (0..pm.width()).rev().find(marked).expect("ink") as f32 + 1.0; + let off = |w: f32| bar_labels_cut(&l, &maps, e, r, 1.0, (w, 100.0)).expect("a bar").0; + assert!(off(right - 2.0), "the page ends inside the ink, {right} px"); + assert!(!off(right + 2.0), "the page ends past the ink, {right} px"); +} + #[test] fn scale_bars_draw_in_their_colours() { let mut pm = Pixmap::new(300, 60).unwrap(); From 1b2d5070f75a510354313df413e82296ae6505e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 16:27:02 -0500 Subject: [PATCH 4/6] fix(ui): keep a missing font's name from widening the Format pane --- crates/ui-egui/src/layoutview/tests.rs | 40 ++++++++++++++++++++++++++ crates/ui-egui/src/textform.rs | 2 ++ 2 files changed, 42 insertions(+) diff --git a/crates/ui-egui/src/layoutview/tests.rs b/crates/ui-egui/src/layoutview/tests.rs index a3846dea8a..bc3d288988 100644 --- a/crates/ui-egui/src/layoutview/tests.rs +++ b/crates/ui-egui/src/layoutview/tests.rs @@ -1541,6 +1541,46 @@ fn a_scale_bars_font_is_picked_in_the_format_pane() { assert_eq!(family(h.state()), FontFamily::Sans, "one step undoes it"); } +/// A family this computer hasn't doesn't widen a scale bar's Format pane (#3468): its long name +/// is cut in the list and its note wraps in the column the pane already has. +#[test] +fn a_scale_bars_missing_font_does_not_widen_the_format_pane() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Scale"})).unwrap(); + let li = app.session.active_layout.unwrap(); + let bar = app.session.project.layouts[li].elements.iter().find(|e| e.name == "Scale Bar").unwrap().id; + app.layout.selected = Some(bar); + // The families indexed, so a name is shown as not installed from the first frame. + rustgis_engine::render::families::installed(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(320.0, 1100.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + with_format(app, ui); + }, + app, + ); + h.run_steps(4); + // The right edge of the pane's column of fields, as the unit label's field fills it. + let column = h.get_by_role_and_label(Role::TextInput, "Unit label").rect().right(); + let change = json!({"element": bar, "font": "A Family Nobody Has Installed 3468", "fallback": "serif"}); + h.state_mut().run("layout.update", change).unwrap(); + h.run_steps(4); + for rect in [ + h.get_by_role_and_label(Role::ComboBox, "Font").rect(), + h.get_by_label_contains("This font isn't installed here").rect(), + h.get_by_role_and_label(Role::TextInput, "Unit label").rect(), + ] { + assert!(rect.right() <= column + 0.5, "{rect:?} past {column}"); + } +} + /// A text element's "Wrap to the box" (#2346): off as it is added, on when ticked, as one /// undoable step, and off again. #[test] diff --git a/crates/ui-egui/src/textform.rs b/crates/ui-egui/src/textform.rs index 7e4bd62c2a..5e41ab66a6 100644 --- a/crates/ui-egui/src/textform.rs +++ b/crates/ui-egui/src/textform.rs @@ -408,6 +408,8 @@ pub(crate) fn font_rows(ui: &mut Ui, id: egui::Id, fam: &mut FontFamily, name: & let search_id = id.with("font_search"); let list = egui::ComboBox::from_id_salt(id.with("font")) .selected_text(shown) + // A long family's name is cut with an ellipsis rather than widen a narrow pane. + .truncate() .height(320.0) .close_behavior(crate::labelpane::SEARCHED_LIST_CLOSES) .show_ui(ui, |ui| { From 467da3cfecfd07caed15fa5029d056628b18b9e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 16:33:14 -0500 Subject: [PATCH 5/6] style(layout): name the scale bar's label drawing and reflow its doc --- crates/render/src/layout/losses.rs | 4 ++-- crates/render/src/layout/scale_bar.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/render/src/layout/losses.rs b/crates/render/src/layout/losses.rs index 8dbff932e4..ae604200e9 100644 --- a/crates/render/src/layout/losses.rs +++ b/crates/render/src/layout/losses.rs @@ -65,8 +65,8 @@ pub fn text_loss(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, id: u /// whether its box is too small for its labels and bar ([`BarLayout::cramped`]), its labels placed /// by [`bar_layout`] as the drawing places them: their line's middle at `label_y`, each centred on /// its advance in the bar's face as the drawing writes it, and its unit label where it is drawn; -/// and whether that unit -/// label is shortened or left out to fit ([`BarLayout::unit_cut`]). `None` when it draws no bar. +/// and whether that unit label is shortened or left out to fit ([`BarLayout::unit_cut`]). `None` +/// when it draws no bar. pub(super) fn bar_labels_cut( layout: &Layout, maps: &[Map], diff --git a/crates/render/src/layout/scale_bar.rs b/crates/render/src/layout/scale_bar.rs index dbfaf43d19..07edbbd4f8 100644 --- a/crates/render/src/layout/scale_bar.rs +++ b/crates/render/src/layout/scale_bar.rs @@ -612,7 +612,7 @@ pub(super) fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarO } // Labels at the divisions, over or under the bar, and the unit label where it is asked. // A line of it, placed across as `align` says, in the bar's face. - let write = |pm: &mut Canvas, s: &str, x: f32, y: f32, align: text::Align| { + let draw_label = |pm: &mut Canvas, s: &str, x: f32, y: f32, align: text::Align| { let w = || text::measure_in(s, px / 1.33, bar.face); let left = match align { text::Align::Left => x, @@ -622,10 +622,10 @@ pub(super) fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarO text::styled_at(pm, s, left, y, px, dark, bar.face, 0.0); }; for (x, s) in &labels { - write(pm, s, *x, label_y, text::Align::Center); + draw_label(pm, s, *x, label_y, text::Align::Center); } if let Some(BarUnit { x, y, text: shown, align }) = unit { - write(pm, &shown, x, y, align); + draw_label(pm, &shown, x, y, align); } } From 40bd108dfc54f1867bb4d4c1286f0b764f81b8dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 17:08:26 -0500 Subject: [PATCH 6/6] test(layout): keep the off-page test's bar clear of the page's left edge --- crates/render/src/layout/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index e0d75e43c2..20c949be64 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6998,7 +6998,8 @@ fn a_scale_bars_label_off_the_page_is_judged_in_its_face() { } let id = l.add("Scale Bar", (0.0, 0.0, 100.0, 20.0), kind); let e = l.element(id).unwrap(); - let r = Rect::from_xywh(0.0, 10.0, 400.0, 80.0).unwrap(); + // Clear of the page's other edges, which a first label can pass in some faces. + let r = Rect::from_xywh(40.0, 10.0, 400.0, 80.0).unwrap(); let Some(ElementKind::MapFrame { center, scale, .. }) = l.element(frame).map(|e| &e.kind) else { panic!("a frame") }; let ground = maps[0].ground_res_at(&frame_camera(&maps[0], *center, *scale, 0.0, 0.0)); let mut pm = Pixmap::new(600, 100).unwrap();