From 390ed5fecdcc86abd112e0890ec0cdf2ada2e7d0 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:28:13 -0600 Subject: [PATCH 01/55] feat(layout): scale bar details in the layout model Subdivisions, divisions before zero, label and unit label placement, a unit label, decimals, a label size and a fit strategy on a scale bar, saved only when set and brought into range when a layout is read. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/layout.rs | 9 +- crates/map/src/layout.rs | 324 +++++++++++++++++++++++++++++++- crates/render/src/layout.rs | 14 +- 3 files changed, 335 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 48f0bb123c..82ae87bbf6 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -4911,7 +4911,7 @@ fn restyle(kind: &ElementKind, p: &Value) -> Result, String> outline: color(p, "outline", *outline)?, })) } - ElementKind::ScaleBar { frame, units, divisions, style, color: c, fill } => { + ElementKind::ScaleBar { units, divisions, style, color: c, fill, .. } => { if ["style", "units", "divisions", "color", "fill"].iter().all(|k| p.get(k).is_none()) { return Ok(None); } @@ -4932,7 +4932,12 @@ fn restyle(kind: &ElementKind, p: &Value) -> Result, String> None => *divisions, }; let (color, fill) = (color(p, "color", *c)?, color(p, "fill", *fill)?); - Ok(Some(ElementKind::ScaleBar { frame: *frame, units, divisions, style, color, fill })) + // The details (subdivisions, labels, fit) stay as they were. + let mut next = kind.clone(); + if let ElementKind::ScaleBar { units: u, divisions: d, style: st, color: co, fill: fi, .. } = &mut next { + (*u, *d, *st, *co, *fi) = (units, divisions, style, color, fill); + } + Ok(Some(next)) } ElementKind::Rectangle { fill, outline, width, dash, .. } | ElementKind::Ellipse { fill, outline, width, dash } => { if ["fill", "outline", "color", "width", "radius", "dash"].iter().all(|k| p.get(k).is_none()) { diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index 3a0d0eb554..ecbcb0eb81 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -831,6 +831,144 @@ fn divisions() -> usize { 4 } +/// The most subdivisions each division of a scale bar is split into. +pub const MAX_SCALE_SUBDIVISIONS: usize = 10; + +/// The most divisions a scale bar draws to the left of its zero. +pub const MAX_SCALE_BEFORE_ZERO: usize = 2; + +/// The most decimal places a scale bar's numbers show. +pub const MAX_SCALE_DECIMALS: usize = 3; + +/// The sizes a scale bar's labels have, in points. +pub const SCALE_LABEL_SIZE: std::ops::RangeInclusive = 4.0..=24.0; + +/// The size a scale bar's labels have unless set, in points. +pub const DEFAULT_SCALE_LABEL_SIZE: f64 = 8.0; + +/// The most characters a scale bar's unit label has. +pub const MAX_UNIT_LABEL_CHARS: usize = 100; + +fn scale_label_size() -> f64 { + DEFAULT_SCALE_LABEL_SIZE +} + +fn is_scale_label_size(v: &f64) -> bool { + *v == DEFAULT_SCALE_LABEL_SIZE +} + +/// Where a scale bar's numbers sit against the bar. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ScaleLabelPosition { + /// Over the bar. + #[default] + Above, + /// Under the bar. + Below, +} + +impl ScaleLabelPosition { + pub const ALL: [ScaleLabelPosition; 2] = [ScaleLabelPosition::Above, ScaleLabelPosition::Below]; + + pub fn code(self) -> &'static str { + match self { + ScaleLabelPosition::Above => "above", + ScaleLabelPosition::Below => "below", + } + } + + pub fn label(self) -> &'static str { + match self { + ScaleLabelPosition::Above => "Above the bar", + ScaleLabelPosition::Below => "Below the bar", + } + } + + pub fn from_name(s: &str) -> Option { + ScaleLabelPosition::ALL.into_iter().find(|v| v.code().eq_ignore_ascii_case(s.trim())) + } +} + +/// Where a scale bar's unit label sits. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum UnitLabelPosition { + /// After the last number, on the same line. + #[default] + AfterLabels, + /// Beside the end of the bar. + AfterBar, + /// Over the bar. + Above, + /// Under the bar. + Below, +} + +impl UnitLabelPosition { + pub const ALL: [UnitLabelPosition; 4] = + [UnitLabelPosition::AfterLabels, UnitLabelPosition::AfterBar, UnitLabelPosition::Above, UnitLabelPosition::Below]; + + pub fn code(self) -> &'static str { + match self { + UnitLabelPosition::AfterLabels => "afterLabels", + UnitLabelPosition::AfterBar => "afterBar", + UnitLabelPosition::Above => "above", + UnitLabelPosition::Below => "below", + } + } + + pub fn label(self) -> &'static str { + match self { + UnitLabelPosition::AfterLabels => "After the labels", + UnitLabelPosition::AfterBar => "After the bar", + UnitLabelPosition::Above => "Above the bar", + UnitLabelPosition::Below => "Below the bar", + } + } + + pub fn from_name(s: &str) -> Option { + UnitLabelPosition::ALL.into_iter().find(|v| v.code().eq_ignore_ascii_case(s.trim())) + } +} + +/// What a scale bar gives way on when its length does not fit its box. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ScaleBarFit { + /// Keep the number of divisions and the bar's width; the value of a division changes. + #[default] + AdjustDivisionValue, + /// Keep the value of a division and the bar's width; the number of divisions changes. + AdjustDivisions, + /// Keep the value and the number of divisions; the bar's width changes. + AdjustWidth, +} + +impl ScaleBarFit { + pub const ALL: [ScaleBarFit; 3] = [ScaleBarFit::AdjustDivisionValue, ScaleBarFit::AdjustDivisions, ScaleBarFit::AdjustWidth]; + + pub fn code(self) -> &'static str { + match self { + ScaleBarFit::AdjustDivisionValue => "adjustDivisionValue", + ScaleBarFit::AdjustDivisions => "adjustDivisions", + ScaleBarFit::AdjustWidth => "adjustWidth", + } + } + + pub fn label(self) -> &'static str { + match self { + ScaleBarFit::AdjustDivisionValue => "Adjust division value", + ScaleBarFit::AdjustDivisions => "Adjust number of divisions", + ScaleBarFit::AdjustWidth => "Adjust width", + } + } + + pub fn from_name(s: &str) -> Option { + ScaleBarFit::ALL.into_iter().find(|v| v.code().eq_ignore_ascii_case(s.trim())) + } +} + /// The most columns a legend lays its rows in. pub const MAX_LEGEND_COLUMNS: usize = 3; @@ -975,6 +1113,31 @@ pub enum ElementKind { /// The alternating bar's light divisions. #[serde(default = "white")] fill: Rgba, + /// Parts each division is split into, 0 (none) to [`MAX_SCALE_SUBDIVISIONS`]. + #[serde(default, skip_serializing_if = "is_default")] + subdivisions: usize, + /// Divisions drawn left of zero, 0 to [`MAX_SCALE_BEFORE_ZERO`]. + #[serde(default, skip_serializing_if = "is_default")] + divisions_before_zero: usize, + /// Where the numbers sit against the bar. + #[serde(default, skip_serializing_if = "is_default")] + label_position: ScaleLabelPosition, + /// Text printed in place of the units' abbreviation. `None` prints the abbreviation and + /// `Some("")` prints nothing. + #[serde(default, skip_serializing_if = "Option::is_none")] + unit_label: Option, + /// Where the unit label sits. + #[serde(default, skip_serializing_if = "is_default")] + unit_label_position: UnitLabelPosition, + /// Decimal places in the numbers, 0 to [`MAX_SCALE_DECIMALS`]. + #[serde(default, skip_serializing_if = "is_default")] + decimals: usize, + /// The numbers' size in points, within [`SCALE_LABEL_SIZE`]. + #[serde(default = "scale_label_size", skip_serializing_if = "is_scale_label_size")] + label_size: f64, + /// What gives way when the bar's length does not fit its box. + #[serde(default, skip_serializing_if = "is_default")] + fit: ScaleBarFit, }, Legend { frame: u32, @@ -1395,9 +1558,53 @@ impl ElementKind { style: ScaleBarStyle::default(), color: ink(), fill: white(), + subdivisions: 0, + divisions_before_zero: 0, + label_position: ScaleLabelPosition::default(), + unit_label: None, + unit_label_position: UnitLabelPosition::default(), + decimals: 0, + label_size: DEFAULT_SCALE_LABEL_SIZE, + fit: ScaleBarFit::default(), } } + /// Whether this is a scale bar with any of the details set: subdivisions, divisions before + /// zero, a label or unit label placement, a unit label, decimals, a label size or a fit. + pub fn scale_bar_uses_details(&self) -> bool { + let ElementKind::ScaleBar { + frame, + subdivisions, + divisions_before_zero, + label_position, + unit_label, + unit_label_position, + decimals, + label_size, + fit, + .. + } = self + else { + return false; + }; + let ElementKind::ScaleBar { + subdivisions: s0, + divisions_before_zero: z0, + label_position: lp0, + unit_label: u0, + unit_label_position: up0, + decimals: d0, + label_size: ls0, + fit: f0, + .. + } = ElementKind::scale_bar(*frame) + else { + return false; + }; + (*subdivisions, *divisions_before_zero, *label_position, unit_label, *unit_label_position, *decimals, *label_size, *fit) + != (s0, z0, lp0, &u0, up0, d0, ls0, f0) + } + pub fn code(&self) -> &'static str { match self { ElementKind::MapFrame { .. } => "mapFrame", @@ -2549,7 +2756,23 @@ impl Layout { text.truncate(end); } ElementKind::Table { rows, .. } => *rows = (*rows).clamp(1, 500), - ElementKind::ScaleBar { divisions, .. } => *divisions = (*divisions).clamp(1, MAX_SCALE_DIVISIONS), + ElementKind::ScaleBar { divisions, subdivisions, divisions_before_zero, decimals, label_size, unit_label, .. } => { + *divisions = (*divisions).clamp(1, MAX_SCALE_DIVISIONS); + *subdivisions = (*subdivisions).min(MAX_SCALE_SUBDIVISIONS); + *divisions_before_zero = (*divisions_before_zero).min(MAX_SCALE_BEFORE_ZERO); + *decimals = (*decimals).min(MAX_SCALE_DECIMALS); + *label_size = + finite_or(*label_size, DEFAULT_SCALE_LABEL_SIZE).clamp(*SCALE_LABEL_SIZE.start(), *SCALE_LABEL_SIZE.end()); + // The label is one line: a break in a hand-edited file is a space. + if let Some(label) = unit_label { + if label.contains(['\n', '\r']) { + *label = label.replace(['\n', '\r'], " "); + } + let end = label.char_indices().nth(MAX_UNIT_LABEL_CHARS).map_or(label.len(), |(i, _)| i); + cut |= end < label.len(); + label.truncate(end); + } + } ElementKind::Rectangle { width, .. } | ElementKind::Ellipse { width, .. } => { *width = finite_or(*width, 1.0).clamp(0.0, 50.0) } @@ -4106,4 +4329,103 @@ mod tests { let mut text = ElementKind::text("t", 12.0, Rgba::rgb(0, 0, 0), false); assert!(!text.takes_ink() && text.ink_mut().is_none(), "a text's colour is its own option"); } + + #[test] + fn scale_bars_without_details_save_as_before() { + // As main writes a plain bar: colour and fill always, nothing new. + let plain = r#"{"ScaleBar":{"frame":2,"units":"Auto","divisions":4,"style":"Alternating","color":[34,34,34,255],"fill":[255,255,255,255]}}"#; + let bar: ElementKind = serde_json::from_str(plain).unwrap(); + assert_eq!(serde_json::to_string(&bar).unwrap(), plain); + assert_eq!(bar, ElementKind::scale_bar(2)); + assert!(!bar.scale_bar_uses_details()); + let ElementKind::ScaleBar { + subdivisions, + divisions_before_zero, + label_position, + unit_label, + unit_label_position, + decimals, + label_size, + fit, + .. + } = &bar + else { + panic!("a scale bar") + }; + assert_eq!((*subdivisions, *divisions_before_zero, *decimals, *label_size), (0, 0, 0, 8.0)); + assert_eq!( + (*label_position, unit_label.clone(), *unit_label_position, *fit), + (ScaleLabelPosition::Above, None, UnitLabelPosition::AfterLabels, ScaleBarFit::AdjustDivisionValue) + ); + // Every setting, saved under its own key and read back equal. + let mut all = bar.clone(); + if let ElementKind::ScaleBar { + subdivisions, + divisions_before_zero, + label_position, + unit_label, + unit_label_position, + decimals, + label_size, + fit, + .. + } = &mut all + { + (*subdivisions, *divisions_before_zero, *label_position) = (4, 1, ScaleLabelPosition::Below); + (*unit_label, *unit_label_position) = (Some("Kilometres".into()), UnitLabelPosition::AfterBar); + (*decimals, *label_size, *fit) = (2, 10.5, ScaleBarFit::AdjustWidth); + } + assert!(all.scale_bar_uses_details()); + let s = serde_json::to_string(&all).unwrap(); + assert!(s.starts_with(r#"{"ScaleBar":{"frame":2,"units":"Auto","divisions":4,"style":"Alternating","color":[34,34,34,255],"fill":[255,255,255,255],"#), "{s}"); + for part in [ + r#""subdivisions":4"#, + r#""divisions_before_zero":1"#, + r#""label_position":"below""#, + r#""unit_label":"Kilometres""#, + r#""unit_label_position":"afterBar""#, + r#""decimals":2"#, + r#""label_size":10.5"#, + r#""fit":"adjustWidth""#, + ] { + assert!(s.contains(part), "{part} in {s}"); + } + assert_eq!(serde_json::from_str::(&s).unwrap(), all); + // An empty unit label is a setting too: it prints none. + let mut blank = bar.clone(); + if let ElementKind::ScaleBar { unit_label, .. } = &mut blank { + *unit_label = Some(String::new()); + } + assert!(blank.scale_bar_uses_details()); + assert!(serde_json::to_string(&blank).unwrap().contains(r#""unit_label":"""#)); + // A loaded layout's out-of-range values are brought into range, and said. + let text = format!( + r#"{{"name":"x","width":200,"height":100,"elements":[ + {{"id":1,"name":"a","x":0,"y":0,"w":10,"h":10,"kind":{{"MapFrame":{{"map":"m","center":{{"x":0,"y":0}},"scale":1000}}}}}}, + {{"id":2,"name":"b","x":0,"y":0,"w":10,"h":10,"kind":{{"ScaleBar":{{"frame":1,"subdivisions":99,"divisions_before_zero":9,"decimals":9,"label_size":1e9,"unit_label":"{}"}}}}}}, + {{"id":3,"name":"c","x":0,"y":0,"w":10,"h":10,"kind":{{"ScaleBar":{{"frame":1,"label_size":-4,"unit_label":"a\nb"}}}}}}]}}"#, + "x".repeat(150) + ); + let mut l: Layout = serde_json::from_str(&text).unwrap(); + let repairs = l.clamp(); + let got = |id| match l.element(id).map(|e| &e.kind) { + Some(ElementKind::ScaleBar { subdivisions, divisions_before_zero, decimals, label_size, unit_label, .. }) => { + (*subdivisions, *divisions_before_zero, *decimals, *label_size, unit_label.clone().unwrap_or_default()) + } + _ => (0, 0, 0, 0.0, String::new()), + }; + assert_eq!(got(2), (MAX_SCALE_SUBDIVISIONS, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, 24.0, "x".repeat(MAX_UNIT_LABEL_CHARS))); + assert_eq!(got(3), (0, 0, 0, 4.0, "a b".to_string())); + assert_eq!((repairs.elements_adjusted, repairs.elements_cut), (2, 1)); + for v in ScaleLabelPosition::ALL { + assert_eq!(ScaleLabelPosition::from_name(&format!(" {} ", v.code().to_uppercase())), Some(v)); + } + for v in UnitLabelPosition::ALL { + assert_eq!(UnitLabelPosition::from_name(v.code()), Some(v)); + } + for v in ScaleBarFit::ALL { + assert_eq!(ScaleBarFit::from_name(v.code()), Some(v)); + } + assert_eq!(ScaleBarFit::from_name("manual"), None); + } } diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 8591a2770b..fa494c8eea 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -660,7 +660,7 @@ fn draw_page( let bearing = frame(*f).map_or(0.0, |fr| fr.2.bearing); north_arrow(&mut pm, r, *style, *fill, *outline, ppp, bearing) } - ElementKind::ScaleBar { frame: f, units, divisions, style, color, fill } => { + ElementKind::ScaleBar { frame: f, units, divisions, style, color, fill, .. } => { if let Some(&(_, mi, cam, _, _)) = frame(*f) && let Some(map) = maps.get(mi) { @@ -8281,14 +8281,10 @@ Elaboração: RustGIS", }, ); let (crimson, navy) = (Rgba::rgb(0xD0, 0x10, 0x10), Rgba::rgb(0x10, 0x10, 0xD0)); - let bar = ElementKind::ScaleBar { - frame, - units: ScaleUnits::Auto, - divisions: 4, - style: ScaleBarStyle::Alternating, - color: crimson, - fill: navy, - }; + let mut bar = ElementKind::scale_bar(frame); + if let ElementKind::ScaleBar { color, fill, .. } = &mut bar { + (*color, *fill) = (crimson, navy); + } l.add("Scale Bar", (5.0, 5.0, 90.0, 20.0), bar); let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); // Above the frame (30 mm of the page's 60): the bar's divisions in its colour and fill, and From 5ef024e35815bd2f28727bf57186af6f7d5ae958 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:06:19 -0600 Subject: [PATCH 02/55] fix(layout): the fit strategy is adjustDivision The middle fit saves as adjustDivision, the camelCase of its variant. A unit label's line breaks, a CRLF included, become one space each. Co-Authored-By: Claude Fable 5.1 --- crates/map/src/layout.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index ecbcb0eb81..197fe97925 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -940,18 +940,18 @@ pub enum ScaleBarFit { #[default] AdjustDivisionValue, /// Keep the value of a division and the bar's width; the number of divisions changes. - AdjustDivisions, + AdjustDivision, /// Keep the value and the number of divisions; the bar's width changes. AdjustWidth, } impl ScaleBarFit { - pub const ALL: [ScaleBarFit; 3] = [ScaleBarFit::AdjustDivisionValue, ScaleBarFit::AdjustDivisions, ScaleBarFit::AdjustWidth]; + pub const ALL: [ScaleBarFit; 3] = [ScaleBarFit::AdjustDivisionValue, ScaleBarFit::AdjustDivision, ScaleBarFit::AdjustWidth]; pub fn code(self) -> &'static str { match self { ScaleBarFit::AdjustDivisionValue => "adjustDivisionValue", - ScaleBarFit::AdjustDivisions => "adjustDivisions", + ScaleBarFit::AdjustDivision => "adjustDivision", ScaleBarFit::AdjustWidth => "adjustWidth", } } @@ -959,7 +959,7 @@ impl ScaleBarFit { pub fn label(self) -> &'static str { match self { ScaleBarFit::AdjustDivisionValue => "Adjust division value", - ScaleBarFit::AdjustDivisions => "Adjust number of divisions", + ScaleBarFit::AdjustDivision => "Adjust number of divisions", ScaleBarFit::AdjustWidth => "Adjust width", } } @@ -2765,9 +2765,7 @@ impl Layout { finite_or(*label_size, DEFAULT_SCALE_LABEL_SIZE).clamp(*SCALE_LABEL_SIZE.start(), *SCALE_LABEL_SIZE.end()); // The label is one line: a break in a hand-edited file is a space. if let Some(label) = unit_label { - if label.contains(['\n', '\r']) { - *label = label.replace(['\n', '\r'], " "); - } + *label = label.replace("\r\n", " ").replace(['\n', '\r'], " "); let end = label.char_indices().nth(MAX_UNIT_LABEL_CHARS).map_or(label.len(), |(i, _)| i); cut |= end < label.len(); label.truncate(end); @@ -4377,6 +4375,12 @@ mod tests { } assert!(all.scale_bar_uses_details()); let s = serde_json::to_string(&all).unwrap(); + // The middle fit saves as the camelCase of its variant. + let mut middle = all.clone(); + if let ElementKind::ScaleBar { fit, .. } = &mut middle { + *fit = ScaleBarFit::AdjustDivision; + } + assert!(serde_json::to_string(&middle).unwrap().contains(r#""fit":"adjustDivision""#)); assert!(s.starts_with(r#"{"ScaleBar":{"frame":2,"units":"Auto","divisions":4,"style":"Alternating","color":[34,34,34,255],"fill":[255,255,255,255],"#), "{s}"); for part in [ r#""subdivisions":4"#, @@ -4403,7 +4407,7 @@ mod tests { r#"{{"name":"x","width":200,"height":100,"elements":[ {{"id":1,"name":"a","x":0,"y":0,"w":10,"h":10,"kind":{{"MapFrame":{{"map":"m","center":{{"x":0,"y":0}},"scale":1000}}}}}}, {{"id":2,"name":"b","x":0,"y":0,"w":10,"h":10,"kind":{{"ScaleBar":{{"frame":1,"subdivisions":99,"divisions_before_zero":9,"decimals":9,"label_size":1e9,"unit_label":"{}"}}}}}}, - {{"id":3,"name":"c","x":0,"y":0,"w":10,"h":10,"kind":{{"ScaleBar":{{"frame":1,"label_size":-4,"unit_label":"a\nb"}}}}}}]}}"#, + {{"id":3,"name":"c","x":0,"y":0,"w":10,"h":10,"kind":{{"ScaleBar":{{"frame":1,"label_size":-4,"unit_label":"a\r\nb\rc\nd"}}}}}}]}}"#, "x".repeat(150) ); let mut l: Layout = serde_json::from_str(&text).unwrap(); @@ -4415,7 +4419,7 @@ mod tests { _ => (0, 0, 0, 0.0, String::new()), }; assert_eq!(got(2), (MAX_SCALE_SUBDIVISIONS, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, 24.0, "x".repeat(MAX_UNIT_LABEL_CHARS))); - assert_eq!(got(3), (0, 0, 0, 4.0, "a b".to_string())); + assert_eq!(got(3), (0, 0, 0, 4.0, "a b c d".to_string())); assert_eq!((repairs.elements_adjusted, repairs.elements_cut), (2, 1)); for v in ScaleLabelPosition::ALL { assert_eq!(ScaleLabelPosition::from_name(&format!(" {} ", v.code().to_uppercase())), Some(v)); From 2e6023072322fde31dee294deaf6bae16c7751cf Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:18:56 -0600 Subject: [PATCH 03/55] test(render): pin how a plain scale bar draws Co-Authored-By: Claude Fable 5.1 --- crates/render/src/layout.rs | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index fa494c8eea..b26c0d9090 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -8150,6 +8150,45 @@ Elaboração: RustGIS", assert!(x < -3.0, "{x}"); } + /// 64-bit FNV-1a over the pixmaps' bytes. + fn fnv(pms: &[Pixmap]) -> u64 { + pms.iter().flat_map(|p| p.data().iter()).fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) + } + + /// A plain scale bar on a white `w` x 60 pixmap, in the default colours. + fn draw_default(style: ScaleBarStyle, units: ScaleUnits, divisions: usize, ground: f64, w: u32, ppp: f64, comma: bool) -> Pixmap { + let mut pm = Pixmap::new(w, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, w as f32, 60.0).unwrap(); + let colors = (Rgba::rgb(0x22, 0x22, 0x22), Rgba::rgb(0xFF, 0xFF, 0xFF)); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, (units, divisions, style), colors, ppp, comma)); + pm + } + + /// How [`scale_bars_without_details_draw_as_before`]'s bars drew before scale bars had details. + const PINNED: u64 = 0xc3cb_47e7_d78d_abb4; + + /// A bar with none of the details draws exactly as main drew it: every style, unit, division + /// count, ground resolution, density and decimal mark. + #[test] + fn scale_bars_without_details_draw_as_before() { + let mut drawn = Vec::new(); + for style in ScaleBarStyle::ALL { + for units in [ScaleUnits::Auto, ScaleUnits::Miles, ScaleUnits::Feet, ScaleUnits::Meters] { + for divisions in [1, 4, 10] { + for ground in [0.37, 100.0, 7.84] { + for (w, ppp) in [(93u32, 1.0), (300, 1.0), (300, 300.0 / 72.0)] { + for comma in [false, true] { + drawn.push(draw_default(style, units, divisions, ground, w, ppp, comma)); + } + } + } + } + } + } + assert_eq!(fnv(&drawn), PINNED, "{:#x}", fnv(&drawn)); + } + #[test] fn scale_bars_count_in_their_units_and_divisions() { let draw_in = |bar, colors| { From ceda19ab8e76d3e6546e08cb190bd8c7a4954e9e Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:35:22 -0600 Subject: [PATCH 04/55] feat(render): scale bars with subdivisions, divisions before zero and a fit strategy A plain bar draws as before, pinned by a hash of today's drawing. Co-Authored-By: Claude Fable 5.1 --- crates/render/src/layout.rs | 314 +++++++++++++++++++++++++++++------- 1 file changed, 260 insertions(+), 54 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index b26c0d9090..ccb2c03c1f 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -8,8 +8,9 @@ use rustgis_data::GeometryType; use rustgis_data::query::{Env, SeriesPage}; use rustgis_geom::{Coord, Extent}; use rustgis_map::layout::{ - ArrowStyle, ChartLook, ColorScale, ElementKind, FrameShape, Grid, GridKind, INK, Layout, LineHead, MAX_LEGEND_COLUMNS, Orientation, - PT_PER_MM, ScaleBarStyle, ScaleUnits, TextAlign, TickSide, frame_camera, + ArrowStyle, ChartLook, ColorScale, DEFAULT_SCALE_LABEL_SIZE, ElementKind, FrameShape, Grid, GridKind, INK, Layout, LineHead, + MAX_LEGEND_COLUMNS, Orientation, PT_PER_MM, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, TextAlign, TickSide, + UnitLabelPosition, frame_camera, }; use rustgis_map::symbology::LegendEntry; use rustgis_map::{Map, Rgba}; @@ -660,12 +661,12 @@ fn draw_page( let bearing = frame(*f).map_or(0.0, |fr| fr.2.bearing); north_arrow(&mut pm, r, *style, *fill, *outline, ppp, bearing) } - ElementKind::ScaleBar { frame: f, units, divisions, style, color, fill, .. } => { + ElementKind::ScaleBar { frame: f, color, fill, .. } => { if let Some(&(_, mi, cam, _, _)) = frame(*f) && let Some(map) = maps.get(mi) + && let Some(bar) = BarOptions::of(&e.kind) { - let bar = (*units, *divisions, *style); - scale_bar(&mut pm, r, map.ground_res_at(&cam), bar, (*color, *fill), ppp, layout.decimal_comma); + scale_bar(&mut pm, r, map.ground_res_at(&cam), &bar, (*color, *fill), ppp, layout.decimal_comma); } } ElementKind::Legend { frame: f, title, all_classes, hide_other, show_no_data, exclude, columns, labels, color, text_size } => { @@ -2103,7 +2104,7 @@ const BAR_SHARE: f64 = 0.85; /// A scale bar's labels' size, in points, and how far its bar starts in from the element's left /// edge, in pixels. [`scale_bar_width_pt`] counts that inset as as many points: when a point is a /// pixel or more, a pixel is no larger than a point, so the box is never too narrow. -const BAR_LABEL_PT: f32 = 8.0; +const BAR_LABEL_PT: f32 = DEFAULT_SCALE_LABEL_SIZE as f32; const BAR_INSET: f32 = 2.0; /// What a scale bar counts: its whole length in its unit, that unit in metres and its abbreviation. @@ -2150,26 +2151,136 @@ pub fn scale_bar_width_pt(ground_per_pt: f64, width_pt: f64, bar: (ScaleUnits, u Some(if w < width_pt && bar_plan(ground_per_pt, w, units) == Some(plan) { w } else { width_pt }) } -/// A scale bar filling most of the element's width, in `units`, with `divisions` labelled steps. -/// `ground_per_pt` is ground metres per logical point of paper; `colors` are its lines, dark -/// divisions and labels, then the alternating bar's light divisions. -fn scale_bar( - pm: &mut Canvas, - r: Rect, - ground_per_pt: f64, - bar: (ScaleUnits, usize, ScaleBarStyle), - colors: (Rgba, Rgba), - ppp: f64, - comma: bool, -) { - let (units, divisions, style) = bar; +/// A scale bar's look: the fields of [`ElementKind::ScaleBar`] but its frame and colours. +#[derive(Clone, Copy, Debug, PartialEq)] +struct BarOptions<'a> { + units: ScaleUnits, + divisions: usize, + style: ScaleBarStyle, + subdivisions: usize, + divisions_before_zero: usize, + label_position: ScaleLabelPosition, + unit_label: Option<&'a str>, + unit_label_position: UnitLabelPosition, + decimals: usize, + label_size: f64, + fit: ScaleBarFit, +} + +impl<'a> BarOptions<'a> { + /// A scale bar element's look; `None` for any other element. + fn of(kind: &'a ElementKind) -> Option> { + let ElementKind::ScaleBar { + units, + divisions, + style, + subdivisions, + divisions_before_zero, + label_position, + unit_label, + unit_label_position, + decimals, + label_size, + fit, + .. + } = kind + else { + return None; + }; + Some(BarOptions { + units: *units, + divisions: *divisions, + style: *style, + subdivisions: *subdivisions, + divisions_before_zero: *divisions_before_zero, + label_position: *label_position, + unit_label: unit_label.as_deref(), + unit_label_position: *unit_label_position, + decimals: *decimals, + label_size: *label_size, + fit: *fit, + }) + } +} + +/// A new scale bar's look. +#[cfg(test)] +impl Default for BarOptions<'_> { + fn default() -> Self { + static PLAIN: std::sync::LazyLock = std::sync::LazyLock::new(|| ElementKind::scale_bar(0)); + BarOptions::of(&PLAIN).expect("a scale bar") + } +} + +/// How long a scale bar is and how it divides: its whole length in its unit, any divisions before +/// zero included, and its divisions after zero. +#[derive(Clone, Copy, Debug, PartialEq)] +struct BarFit { + total: f64, + after: usize, +} + +/// A scale bar of `before` divisions before zero and `after` after it, counting in a unit `unit_m` +/// metres long, fitted to `room_m` ground metres by `fit`: the roundest length divided as asked +/// (`AdjustDivisionValue`, the length [`bar_plan`] takes), as many round divisions as fit +/// (`AdjustDivision`), or the asked divisions each a round length (`AdjustWidth`). `None` when it +/// draws none. +fn bar_fit(room_m: f64, unit_m: f64, fit: ScaleBarFit, before: usize, after: usize) -> Option { + let count = (before + after) as f64; + let (total, after) = match fit { + ScaleBarFit::AdjustDivisionValue => (rustgis_geom::nice_distance(room_m / unit_m), after), + ScaleBarFit::AdjustDivision => { + let value = rustgis_geom::nice_distance(room_m / unit_m / count); + let fits = (room_m / unit_m / value + 1e-9).floor() - before as f64; + let after = fits.clamp(1.0, rustgis_map::layout::MAX_SCALE_DIVISIONS as f64) as usize; + (value * (before + after) as f64, after) + } + ScaleBarFit::AdjustWidth => (rustgis_geom::nice_distance(room_m / unit_m / count) * count, after), + }; + (total.is_finite() && total > 0.0).then_some(BarFit { total, after }) +} + +/// A scale bar filling most of the element's width as `bar` asks: its divisions after zero (and +/// any before it) labelled, the first after zero split into its subdivisions. `ground_per_pt` is +/// ground metres per logical point of paper; `colors` are its lines, dark divisions and labels, +/// then the alternating bar's light divisions. +fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, colors: (Rgba, Rgba), ppp: f64, comma: bool) { + use rustgis_map::layout::{MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS}; + if !(ground_per_pt.is_finite() && ground_per_pt > 0.0 && ppp.is_finite() && ppp > 0.0) { + return; + } let (dark, light) = colors; - let divisions = divisions.clamp(1, rustgis_map::layout::MAX_SCALE_DIVISIONS); - let Some(BarPlan { total, unit_m, abbr }) = bar_plan(ground_per_pt, f64::from(r.width()) / ppp, units) else { return }; + let after = bar.divisions.clamp(1, MAX_SCALE_DIVISIONS); + let before = bar.divisions_before_zero.min(MAX_SCALE_BEFORE_ZERO); + // One part is the division whole. + let parts = bar.subdivisions.clamp(1, MAX_SCALE_SUBDIVISIONS); + let width_pt = f64::from(r.width()) / ppp; + let Some(BarPlan { unit_m, abbr, .. }) = bar_plan(ground_per_pt, width_pt, bar.units) else { return }; + // The points of the box its labels take from the bar: none yet. + let taken_pt = 0.0; + let room_m = ground_per_pt * width_pt * BAR_SHARE - ground_per_pt * taken_pt; + let Some(BarFit { total, after }) = bar_fit(room_m, unit_m, bar.fit, before, after) else { return }; + let divs = before + after; let len = (total * unit_m / ground_per_pt * ppp) as f32; + let px = BAR_LABEL_PT * 1.33 * ppp as f32; + let half = |s: &str| text::measure(s, px / 1.33, false) / 2.0; + // Division `j` counts `j - before` from zero. Its label, the last with the unit. + let label = |j: usize| { + let k = j as isize - before as isize; + let v = decimal(scale_number((total * k as f64 / divs as f64).abs(), total / divs as f64), comma); + let v = if k < 0 { format!("-{v}") } else { v }; + if j == divs { format!("{v} {abbr}") } else { v } + }; + // Left of zero the first label is a negative one, centred on the bar's end: the bar starts far + // enough in for it. + let pad = if before > 0 { (half(&label(0)) - 2.0).max(0.0) } else { 0.0 }; let bar_h = (r.height() * 0.28).min(6.0 * ppp as f32); - let (x0, y0) = (r.x() + BAR_INSET, r.y() + r.height() * 0.62 - bar_h / 2.0); - let seg = len / divisions as f32; + let (x0, y0) = (r.x() + BAR_INSET + pad, r.y() + r.height() * 0.62 - bar_h / 2.0); + let seg = len / divs as f32; + let zero_x = x0 + seg * before as f32; + // Where the first division after zero is cut into its subdivisions. + let cuts: Vec = (1..parts).map(|p| zero_x + seg * p as f32 / parts as f32).collect(); + let dark_at = |j: usize| (j as isize - before as isize).rem_euclid(2) == 0; let line = Stroke { width: 0.6 * ppp as f32, ..Stroke::default() }; let stroke = |pm: &mut Canvas, pts: &[(f32, f32)], w: &Stroke| { let mut pb = PathBuilder::new(); @@ -2180,11 +2291,21 @@ fn scale_bar( pm.stroke_path(&p, &paint(dark, 1.0), w, Transform::identity(), None); } }; - match style { + match bar.style { ScaleBarStyle::Alternating => { - for i in 0..divisions { - let c = if i % 2 == 0 { dark } else { light }; - if let Some(b) = Rect::from_xywh(x0 + seg * i as f32, y0, seg, bar_h) { + for j in 0..divs { + let x = x0 + seg * j as f32; + if j == before && parts > 1 { + // Alternating parts, the last dark against the light division after it. + let part = seg / parts as f32; + for p in 0..parts { + let c = if (parts - 1 - p) % 2 == 0 { dark } else { light }; + if let Some(b) = Rect::from_xywh(x + part * p as f32, y0, part, bar_h) { + pm.fill_rect(b, &paint(c, 1.0), Transform::identity(), None); + } + } + } else if let Some(b) = Rect::from_xywh(x, y0, seg, bar_h) { + let c = if dark_at(j) { dark } else { light }; pm.fill_rect(b, &paint(c, 1.0), Transform::identity(), None); } } @@ -2194,35 +2315,41 @@ fn scale_bar( } ScaleBarStyle::Stepped => { let mut pts = vec![(x0, y0 + bar_h)]; - for i in 0..divisions { - let y = if i % 2 == 0 { y0 } else { y0 + bar_h }; - let (a, b) = (x0 + seg * i as f32, x0 + seg * (i + 1) as f32); + for j in 0..divs { + let y = if dark_at(j) { y0 } else { y0 + bar_h }; + let (a, b) = (x0 + seg * j as f32, x0 + seg * (j + 1) as f32); pts.extend([(a, y), (b, y)]); } pts.push((x0 + len, y0 + bar_h)); stroke(pm, &pts, &Stroke { width: 1.0 * ppp as f32, ..Stroke::default() }); + // The first division after zero is on the upper step: its ticks hang from it. + for &x in &cuts { + stroke(pm, &[(x, y0), (x, y0 + bar_h * 0.5)], &line); + } } ScaleBarStyle::Line => { let base = y0 + bar_h; stroke(pm, &[(x0, base), (x0 + len, base)], &Stroke { width: 1.0 * ppp as f32, ..Stroke::default() }); - for i in 0..=divisions { - let tall = if i == 0 || i == divisions { bar_h } else { bar_h * 0.6 }; - let x = x0 + seg * i as f32; + // Tall ticks at the ends and at zero. + for j in 0..=divs { + let tall = if j == 0 || j == divs || j == before { bar_h } else { bar_h * 0.6 }; + let x = x0 + seg * j as f32; stroke(pm, &[(x, base), (x, base - tall)], &line); } + for &x in &cuts { + stroke(pm, &[(x, base), (x, base - bar_h * 0.3)], &line); + } } } // Labels at the divisions, the last with the unit; one that would touch its neighbour is left // out (never the ends). - let px = BAR_LABEL_PT * 1.33 * ppp as f32; let ty = y0 - px * 0.7; let gap = 3.0 * ppp as f32; - let labels: Vec<(f32, String)> = (0..=divisions).map(|i| (x0 + seg * i as f32, bar_label(total, divisions, i, abbr, comma))).collect(); - let half = |s: &str| text::measure(s, px / 1.33, false) / 2.0; + let labels: Vec<(f32, String)> = (0..=divs).map(|j| (x0 + seg * j as f32, label(j))).collect(); let last = labels.last().map(|(x, s)| x - half(s)).unwrap_or(f32::MAX); let mut right = f32::MIN; for (i, (x, s)) in labels.iter().enumerate() { - let end = i == divisions; + let end = i == divs; if !end && (x - half(s) < right + gap || x + half(s) + gap > last) && i != 0 { continue; } @@ -8150,6 +8277,47 @@ Elaboração: RustGIS", assert!(x < -3.0, "{x}"); } + /// A scale bar's default colour and fill. + const DEFAULT_COLORS: (Rgba, Rgba) = (Rgba::rgb(0x22, 0x22, 0x22), Rgba::rgb(0xFF, 0xFF, 0xFF)); + + /// A white `width` x 60 pixmap with `bar` drawn on it at 100 m of ground a point, a pixel a + /// point, with a decimal point, in the default colours. + fn draw_bar(bar: &BarOptions<'_>, width: u32) -> Pixmap { + let mut pm = Pixmap::new(width, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, width as f32, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, bar, DEFAULT_COLORS, 1.0, false)); + pm + } + + /// Dark runs along row `y`. + fn dark_runs(pm: &Pixmap, y: u32) -> usize { + let dark: Vec = (0..pm.width()).map(|x| pm.pixel(x, y).is_some_and(ink)).collect(); + dark.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(dark.first() == Some(&true)) + } + + /// The first and last columns with anything but white on row `y`. + fn marked_span(pm: &Pixmap, y: u32) -> Option<(u32, u32)> { + let marked = |x: &u32| pm.pixel(*x, y).is_some_and(|p| p.red() < 200 || p.green() < 200 || p.blue() < 200); + let first = (0..pm.width()).find(marked)?; + let last = (0..pm.width()).rev().find(marked)?; + Some((first, last)) + } + + /// The rows holding ink. + fn bar_ink_rows(pm: &Pixmap) -> Vec { + (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| pm.pixel(x, y).is_some_and(ink))).collect() + } + + /// How much darker than white the pixels in rows `from..=to` are, summed. + fn darkness(pm: &Pixmap, from: u32, to: u32) -> u32 { + (from..=to) + .flat_map(|y| (0..pm.width()).map(move |x| (x, y))) + .filter_map(|(x, y)| pm.pixel(x, y)) + .map(|p| 255 - u32::from(p.red())) + .sum() + } + /// 64-bit FNV-1a over the pixmaps' bytes. fn fnv(pms: &[Pixmap]) -> u64 { pms.iter().flat_map(|p| p.data().iter()).fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) @@ -8160,8 +8328,8 @@ Elaboração: RustGIS", let mut pm = Pixmap::new(w, 60).unwrap(); pm.fill(tiny_skia::Color::WHITE); let r = Rect::from_xywh(0.0, 0.0, w as f32, 60.0).unwrap(); - let colors = (Rgba::rgb(0x22, 0x22, 0x22), Rgba::rgb(0xFF, 0xFF, 0xFF)); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, (units, divisions, style), colors, ppp, comma)); + let bar = BarOptions { units, divisions, style, ..BarOptions::default() }; + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &bar, DEFAULT_COLORS, ppp, comma)); pm } @@ -8191,15 +8359,8 @@ Elaboração: RustGIS", #[test] fn scale_bars_count_in_their_units_and_divisions() { - let draw_in = |bar, colors| { - let mut pm = Pixmap::new(300, 60).unwrap(); - pm.fill(tiny_skia::Color::WHITE); - // 100 m of ground per point: about 25 km across the bar. - let r = Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, bar, colors, 1.0, false)); - pm - }; - let draw = |bar| draw_in(bar, (Rgba::rgb(0x22, 0x22, 0x22), Rgba::rgb(0xFF, 0xFF, 0xFF))); + // 100 m of ground per point: about 25 km across the bar. + let draw = |(units, divisions, style)| draw_bar(&BarOptions { units, divisions, style, ..BarOptions::default() }, 300); // Dark runs along the bar's middle row: one per dark division of an alternating bar. let runs = |pm: &Pixmap| { let y = (60.0 * 0.62) as u32; @@ -8219,6 +8380,55 @@ Elaboração: RustGIS", assert!(dark < 20, "{style:?}: {dark} dark pixels across the bar"); assert_ne!(pm.data(), four.data()); } + let with = |f: &dyn Fn(&mut BarOptions<'static>)| { + let mut b = BarOptions::default(); + f(&mut b); + draw_bar(&b, 300) + }; + let runs = |pm: &Pixmap| dark_runs(pm, 37); + assert_eq!(runs(&with(&|_| {})), 2); + // The first division cut in four alternating parts, the last dark: two runs there, one after. + assert_eq!(runs(&with(&|b| b.subdivisions = 4)), 3); + assert_eq!(with(&|b| b.subdivisions = 1).data(), with(&|_| {}).data(), "one part is the division whole"); + // Two whole divisions before zero: six divisions, three dark. + assert_eq!(runs(&with(&|b| b.divisions_before_zero = 2)), 3); + assert_eq!(bar_ink_rows(&with(&|b| b.divisions_before_zero = 2)), bar_ink_rows(&with(&|_| {})), "the same rows, bar and labels"); + // A single or stepped line gets short ticks inside its first division. + for style in [ScaleBarStyle::Line, ScaleBarStyle::Stepped] { + let plain = with(&|b| b.style = style); + let cut = with(&|b| { + b.style = style; + b.subdivisions = 3; + }); + assert!(darkness(&cut, 35, 39) > darkness(&plain, 35, 39) + 100, "{style:?}"); + } + } + + #[test] + fn scale_bars_fit_their_box_by_the_strategy() { + // 79 px to use at 100 m a point: 7.9 km of ground, in kilometres. + let width = |fit| { + let bar = BarOptions { units: ScaleUnits::Kilometers, fit, ..BarOptions::default() }; + let (a, b) = marked_span(&draw_bar(&bar, 93), 37).unwrap(); + b - a + }; + assert!((width(ScaleBarFit::AdjustDivisionValue) as i32 - 50).abs() <= 2, "a round 5 km in four 1.25 km divisions"); + assert!((width(ScaleBarFit::AdjustDivision) as i32 - 70).abs() <= 2, "seven round 1 km divisions"); + assert!((width(ScaleBarFit::AdjustWidth) as i32 - 40).abs() <= 2, "four 1 km divisions, narrower than the box"); + // Extreme grounds, every fit, divisions before zero: never past the box, never empty. + for ground in [1e-4, 0.37, 100.0, 1e5, 1e7] { + for fit in ScaleBarFit::ALL { + for before in [0, 2] { + let bar = BarOptions { fit, divisions_before_zero: before, divisions: 10, ..BarOptions::default() }; + let mut pm = Pixmap::new(120, 60).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(10.0, 0.0, 100.0, 60.0).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &bar, DEFAULT_COLORS, 1.0, false)); + let (a, b) = marked_span(&pm, 37).unwrap_or((0, 0)); + assert!(b > a && b < 120, "{ground} {fit:?} {before}: {a}..{b}"); + } + } + } } /// The narrowest element keeps its bar where an export rebuilds it from an f32 rectangle: near @@ -8251,10 +8461,7 @@ Elaboração: RustGIS", let mut pm = Pixmap::new(320, 60).unwrap(); pm.fill(tiny_skia::Color::WHITE); let r = Rect::from_xywh(0.0, 0.0, width, 60.0).unwrap(); - let colors = (Rgba::rgb(0x22, 0x22, 0x22), Rgba::rgb(0xFF, 0xFF, 0xFF)); - crate::canvas::with_canvas(&mut pm, |c| { - scale_bar(c, r, ground, (ScaleUnits::Auto, 4, ScaleBarStyle::Alternating), colors, 1.0, true) - }); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &BarOptions::default(), DEFAULT_COLORS, 1.0, true)); pm }; // 20 km on a bar of 300 points takes two thirds of it; 10 km at 37.2 m a point, a third. @@ -8280,9 +8487,8 @@ Elaboração: RustGIS", type Px = tiny_skia::PremultipliedColorU8; // A red colour and a blue fill. let colors = (Rgba::rgb(0xD0, 0x10, 0x10), Rgba::rgb(0x10, 0x10, 0xD0)); - let bar = (ScaleUnits::Auto, 4, ScaleBarStyle::Alternating); let r = Rect::from_xywh(0.0, 0.0, 300.0, 60.0).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, bar, colors, 1.0, false)); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &BarOptions::default(), colors, 1.0, false)); let count = |hit: fn(Px) -> bool, y: u32| (0..300).filter(|&x| pm.pixel(x, y).is_some_and(hit)).count(); let y = (60.0 * 0.62) as u32; // Along the bar: the dark divisions in the colour, the light ones in the fill, nothing in From e341a9fb823207711bd15110126a90074adf5050 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:02:58 -0600 Subject: [PATCH 05/55] feat(render): scale bar labels above or below, a unit label where asked, decimals and a label size Co-Authored-By: Claude Fable 5.1 --- crates/render/src/layout.rs | 275 ++++++++++++++++++++++++++++++++---- 1 file changed, 250 insertions(+), 25 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index ccb2c03c1f..f5600a9cf3 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2099,6 +2099,24 @@ fn scale_number(v: f64, step: f64) -> String { if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s } } +/// A scale bar's number for `v`, a multiple of `step`, with a decimal comma when `comma`. With no +/// `decimals`, as [`scale_number`] prints it and no thousands separators, as bars always printed; +/// with 1 to [`MAX_SCALE_DECIMALS`](rustgis_map::layout::MAX_SCALE_DECIMALS), that many places and +/// the thousands apart. A minus only in front of a digit other than zero; NaN and infinity print 0. +fn bar_number(v: f64, step: f64, decimals: usize, comma: bool) -> String { + let v = if v.is_finite() { v } else { 0.0 }; + let places = decimals.min(rustgis_map::layout::MAX_SCALE_DECIMALS); + let body = if places == 0 { + decimal(scale_number(v.abs(), step), comma) + } else { + let s = format!("{:.*}", places, v.abs()); + let (whole, part) = s.split_once('.').unwrap_or((s.as_str(), "")); + let whole = rustgis_map::graphics::thousands(whole.parse().unwrap_or(0.0)); + decimal(format!("{whole}.{part}"), comma) + }; + if v < 0.0 && body.chars().any(|c| matches!(c, '1'..='9')) { format!("-{body}") } else { body } +} + /// The share of its element's width a scale bar's length may take. const BAR_SHARE: f64 = 0.85; /// A scale bar's labels' size, in points, and how far its bar starts in from the element's left @@ -2152,7 +2170,7 @@ pub fn scale_bar_width_pt(ground_per_pt: f64, width_pt: f64, bar: (ScaleUnits, u } /// A scale bar's look: the fields of [`ElementKind::ScaleBar`] but its frame and colours. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug)] struct BarOptions<'a> { units: ScaleUnits, divisions: usize, @@ -2245,7 +2263,9 @@ fn bar_fit(room_m: f64, unit_m: f64, fit: ScaleBarFit, before: usize, after: usi /// ground metres per logical point of paper; `colors` are its lines, dark divisions and labels, /// then the alternating bar's light divisions. fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, colors: (Rgba, Rgba), ppp: f64, comma: bool) { - use rustgis_map::layout::{MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS}; + use rustgis_map::layout::{ + MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, MAX_UNIT_LABEL_CHARS, SCALE_LABEL_SIZE, + }; if !(ground_per_pt.is_finite() && ground_per_pt > 0.0 && ppp.is_finite() && ppp > 0.0) { return; } @@ -2256,26 +2276,61 @@ fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, let parts = bar.subdivisions.clamp(1, MAX_SCALE_SUBDIVISIONS); let width_pt = f64::from(r.width()) / ppp; let Some(BarPlan { unit_m, abbr, .. }) = bar_plan(ground_per_pt, width_pt, bar.units) else { return }; - // The points of the box its labels take from the bar: none yet. - let taken_pt = 0.0; - let room_m = ground_per_pt * width_pt * BAR_SHARE - ground_per_pt * taken_pt; - let Some(BarFit { total, after }) = bar_fit(room_m, unit_m, bar.fit, before, after) else { return }; - let divs = before + after; - let len = (total * unit_m / ground_per_pt * ppp) as f32; - let px = BAR_LABEL_PT * 1.33 * ppp as f32; + let decimals = bar.decimals.min(MAX_SCALE_DECIMALS); + let label_pt = if bar.label_size.is_finite() { + bar.label_size.clamp(*SCALE_LABEL_SIZE.start(), *SCALE_LABEL_SIZE.end()) + } else { + DEFAULT_SCALE_LABEL_SIZE + }; + let px = label_pt as f32 * 1.33 * ppp as f32; let half = |s: &str| text::measure(s, px / 1.33, false) / 2.0; - // Division `j` counts `j - before` from zero. Its label, the last with the unit. - let label = |j: usize| { - let k = j as isize - before as isize; - let v = decimal(scale_number((total * k as f64 / divs as f64).abs(), total / divs as f64), comma); - let v = if k < 0 { format!("-{v}") } else { v }; - if j == divs { format!("{v} {abbr}") } else { v } + let gap = 3.0 * ppp as f32; + // The unit's words: its abbreviation unless the bar names it, on one line. + let unit: String = match bar.unit_label { + None => abbr.to_string(), + Some(t) => t.chars().take(MAX_UNIT_LABEL_CHARS).map(|c| if matches!(c, '\n' | '\r') { ' ' } else { c }).collect(), + }; + let has_unit = !unit.trim().is_empty(); + let unit_at = bar.unit_label_position; + // The pixels a unit after the bar takes from it, at most half the bar's room. + let beside = if has_unit && unit_at == UnitLabelPosition::AfterBar { + (text::measure(&unit, px / 1.33, false) + gap + ppp as f32).min(r.width() * BAR_SHARE as f32 * 0.5) + } else { + 0.0 }; + // Division `k` from zero of a bar `total` long in `divs` divisions. + let number = |total: f64, divs: usize, k: isize| bar_number(total * k as f64 / divs as f64, total / divs as f64, decimals, comma); // Left of zero the first label is a negative one, centred on the bar's end: the bar starts far // enough in for it. - let pad = if before > 0 { (half(&label(0)) - 2.0).max(0.0) } else { 0.0 }; + let pad_of = |f: &BarFit| if before > 0 { (half(&number(f.total, before + f.after, -(before as isize))) - 2.0).max(0.0) } else { 0.0 }; + // The bar in what's left of its room once `taken` pixels of the box are its labels'. + let fitted = |taken: f32| { + let taken_pt = f64::from(taken) / ppp; + let room_m = ground_per_pt * width_pt * BAR_SHARE - ground_per_pt * taken_pt; + bar_fit(room_m, unit_m, bar.fit, before, after) + }; + let Some(first) = fitted(beside) else { return }; + // The room left of zero follows the bar's length: fitted again with the first label's. + let fit = if before > 0 { fitted(beside + pad_of(&first)) } else { Some(first) }; + let Some(fit) = fit else { return }; + let BarFit { total, after } = fit; + let pad = pad_of(&fit); + let divs = before + after; + let len = (total * unit_m / ground_per_pt * ppp) as f32; + // Division `j` counts `j - before` from zero. Its label, the last with the unit when it follows + // the labels. + let label = |j: usize| { + let v = number(total, divs, j as isize - before as isize); + if j == divs && has_unit && unit_at == UnitLabelPosition::AfterLabels { format!("{v} {unit}") } else { v } + }; + let rows = bar_rows(bar.label_position, unit_at, has_unit); + // Each line above the bar moves it down, each below up; labels over it alone leave it where it + // always was. + let centre = 0.62 + 0.12 * (rows.up as f32 - 1.0 - rows.down as f32); let bar_h = (r.height() * 0.28).min(6.0 * ppp as f32); - let (x0, y0) = (r.x() + BAR_INSET + pad, r.y() + r.height() * 0.62 - bar_h / 2.0); + let (x0, y0) = (r.x() + BAR_INSET + pad, r.y() + r.height() * centre - bar_h / 2.0); + // The middle of text line `n` out from the bar. + let row = |n: usize| (0.7 + 1.25 * n as f32) * px; let seg = len / divs as f32; let zero_x = x0 + seg * before as f32; // Where the first division after zero is cut into its subdivisions. @@ -2341,10 +2396,9 @@ fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, } } } - // Labels at the divisions, the last with the unit; one that would touch its neighbour is left + // Labels at the divisions, over or under the bar; one that would touch its neighbour is left // out (never the ends). - let ty = y0 - px * 0.7; - let gap = 3.0 * ppp as f32; + let ty = if bar.label_position == ScaleLabelPosition::Below { y0 + bar_h + row(0) } else { y0 - row(0) }; let labels: Vec<(f32, String)> = (0..=divs).map(|j| (x0 + seg * j as f32, label(j))).collect(); let last = labels.last().map(|(x, s)| x - half(s)).unwrap_or(f32::MAX); let mut right = f32::MIN; @@ -2356,6 +2410,42 @@ fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, text::text_at(pm, s, *x, ty, px, dark, false, text::Align::Center, false); right = x + half(s); } + // The unit after the bar, level with its middle, or centred over or under it on a line of its own. + if has_unit { + let mid = x0 + len / 2.0; + let (x, y, align) = match unit_at { + UnitLabelPosition::AfterLabels => return, + UnitLabelPosition::AfterBar => (x0 + len + gap + ppp as f32, y0 + bar_h / 2.0, text::Align::Left), + UnitLabelPosition::Above => (mid, y0 - row(rows.unit_row), text::Align::Center), + UnitLabelPosition::Below => (mid, y0 + bar_h + row(rows.unit_row), text::Align::Center), + }; + text::text_at(pm, &unit, x, y, px, dark, false, align, false); + } +} + +/// The text lines a scale bar has above and below it, and the line its unit takes on its side +/// (0 next to the bar, 1 past its labels). +#[derive(Clone, Copy, Debug, PartialEq)] +struct BarRows { + up: usize, + down: usize, + unit_row: usize, +} + +/// The lines of a scale bar with its labels at `labels` and its unit (if `has_unit`) at `unit`. +fn bar_rows(labels: ScaleLabelPosition, unit: UnitLabelPosition, has_unit: bool) -> BarRows { + let labels_up = labels == ScaleLabelPosition::Above; + // The side the unit has a line of its own on: true above. + let unit_up = match unit { + UnitLabelPosition::Above if has_unit => Some(true), + UnitLabelPosition::Below if has_unit => Some(false), + _ => None, + }; + BarRows { + up: usize::from(labels_up) + usize::from(unit_up == Some(true)), + down: usize::from(!labels_up) + usize::from(unit_up == Some(false)), + unit_row: usize::from(unit_up == Some(labels_up)), + } } /// Each visible layer's legend for what it draws at a scale denominator (#207), by layer id; a @@ -8425,7 +8515,7 @@ Elaboração: RustGIS", let r = Rect::from_xywh(10.0, 0.0, 100.0, 60.0).unwrap(); crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, ground, &bar, DEFAULT_COLORS, 1.0, false)); let (a, b) = marked_span(&pm, 37).unwrap_or((0, 0)); - assert!(b > a && b < 120, "{ground} {fit:?} {before}: {a}..{b}"); + assert!(b > a && b < 110, "{ground} {fit:?} {before}: {a}..{b}"); } } } @@ -8502,10 +8592,10 @@ Elaboração: RustGIS", assert_eq!((0..y.saturating_sub(8)).map(|row| count(ink, row)).sum::(), 0, "no ink labels"); } - /// A page draws a scale bar in its own colour and fill: the element's, through `draw_page`. - #[test] - fn a_page_draws_its_scale_bar_in_its_colours() { - let mut maps = vec![Map::new("m")]; + /// A 100 x 60 mm page with a 90 x 20 mm frame at its foot showing a map at 1:10,000,000: the + /// map, the page and the frame's id. + fn colour_test_page() -> (Vec, Layout, u32) { + let maps = vec![Map::new("m")]; let mut l = Layout::new("Layout", 100.0, 60.0); let frame = l.add( "Map", @@ -8525,6 +8615,13 @@ Elaboração: RustGIS", pitch: 0.0, }, ); + (maps, l, frame) + } + + /// A page draws a scale bar in its own colour and fill: the element's, through `draw_page`. + #[test] + fn a_page_draws_its_scale_bar_in_its_colours() { + let (mut maps, mut l, frame) = colour_test_page(); let (crimson, navy) = (Rgba::rgb(0xD0, 0x10, 0x10), Rgba::rgb(0x10, 0x10, 0xD0)); let mut bar = ElementKind::scale_bar(frame); if let ElementKind::ScaleBar { color, fill, .. } = &mut bar { @@ -8543,6 +8640,134 @@ Elaboração: RustGIS", assert_eq!(count(ink), 0, "no default ink"); } + #[test] + fn scale_numbers_have_decimals_and_thousands() { + // 0 decimals: as each label needs, with no separators, exactly as before. + assert_eq!(bar_number(5000.0, 1000.0, 0, false), "5000"); + assert_eq!(bar_number(0.0125, 0.0125, 0, false), "0.0125"); + assert_eq!(bar_number(-500.0, 500.0, 0, false), "-500"); + assert_eq!(bar_number(2.5, 1.25, 0, true), "2,5"); + // Fixed decimals with their thousands apart, the marks swapped under a decimal comma. + assert_eq!(bar_number(1250.0, 250.0, 2, false), "1,250.00"); + assert_eq!(bar_number(1250.0, 250.0, 2, true), "1.250,00"); + assert_eq!(bar_number(12500.0, 2500.0, 3, true), "12.500,000"); + assert_eq!(bar_number(-1500.0, 500.0, 1, true), "-1.500,0"); + assert_eq!(bar_number(0.0, 5.0, 2, false), "0.00"); + assert_eq!(bar_number(-0.001, 5.0, 1, false), "0.0", "no sign on a zero"); + assert_eq!(bar_number(f64::NAN, 1.0, 2, false), "0.00", "never a panic"); + } + + #[test] + fn scale_bars_draw_subdivisions_and_place_labels_above_or_below() { + let with = |f: &dyn Fn(&mut BarOptions<'static>)| { + let mut b = BarOptions::default(); + f(&mut b); + draw_bar(&b, 300) + }; + let above = with(&|_| {}); + let rows = bar_ink_rows(&above); + assert!(rows.iter().any(|&y| y < 32) && rows.iter().all(|&y| y < 42), "labels over the bar: {rows:?}"); + let below = with(&|b| b.label_position = ScaleLabelPosition::Below); + let rows = bar_ink_rows(&below); + assert!(rows.iter().all(|&y| y >= 18) && rows.iter().any(|&y| y > 28), "labels under it: {rows:?}"); + // Subdivisions aren't labelled: the first ink row stays where the labels put it. + let cut = with(&|b| b.subdivisions = 3); + assert_eq!(bar_ink_rows(&cut).first(), bar_ink_rows(&above).first()); + // A bigger label is taller; decimals change the labels. + assert!(bar_ink_rows(&with(&|b| b.label_size = 16.0)).len() > rows.len() + 4); + assert_ne!(with(&|b| b.decimals = 2).data(), above.data()); + assert_ne!(with(&|b| b.divisions_before_zero = 1).data(), above.data()); + } + + #[test] + fn unit_labels_sit_after_the_bar_when_asked() { + let draw = |text: Option<&'static str>, at| { + draw_bar(&BarOptions { unit_label: text, unit_label_position: at, units: ScaleUnits::Kilometers, ..BarOptions::default() }, 300) + }; + let right_of = + |pm: &Pixmap| (0..pm.height()).filter_map(|y| (0..pm.width()).rev().find(|&x| pm.pixel(x, y).is_some_and(ink))).max(); + let none = draw(Some(""), UnitLabelPosition::AfterBar); + let feet = draw(Some("Feet"), UnitLabelPosition::AfterBar); + let (_, bare_end) = marked_span(&none, 37).unwrap(); + let (_, word_end) = marked_span(&feet, 37).unwrap(); + assert!(word_end > bare_end + 15, "level with the bar, after it: {word_end} against {bare_end}"); + // Left out, the abbreviation follows the last label; "" prints none. + let default = draw(None, UnitLabelPosition::AfterLabels); + let blank = draw(Some(""), UnitLabelPosition::AfterLabels); + assert!(right_of(&default) > right_of(&blank)); + // Above or below, on a line of its own. + let top = |pm: &Pixmap| bar_ink_rows(pm).first().copied().unwrap_or(0); + let bottom = |pm: &Pixmap| bar_ink_rows(pm).last().copied().unwrap_or(0); + assert!(top(&draw(Some("Feet"), UnitLabelPosition::Above)) < top(&blank)); + assert!(bottom(&draw(Some("Feet"), UnitLabelPosition::Below)) > bottom(&blank)); + assert_ne!(draw(Some("FEET"), UnitLabelPosition::AfterBar).data(), feet.data(), "verbatim"); + // Other scripts and emoji draw without a panic. + for text in ["距離 km", "مسافة", "🚶"] { + for at in UnitLabelPosition::ALL { + let _ = draw(Some(text), at); + } + } + // A whitespace label adds no ink (on its own line it still takes its row, so compare after the bar). + assert_eq!(draw(Some(" "), UnitLabelPosition::AfterBar).data(), none.data()); + } + + #[test] + fn a_wide_unit_label_after_the_bar_keeps_the_bar() { + let long = "Kilometres of ground distance, as measured on the map ".repeat(2); + for width in [12u32, 40, 93, 300] { + for height in [8u32, 60] { + let bar = BarOptions { + unit_label: Some(long.as_str()), + unit_label_position: UnitLabelPosition::AfterBar, + units: ScaleUnits::Kilometers, + ..BarOptions::default() + }; + let mut pm = Pixmap::new(width, height).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + let r = Rect::from_xywh(0.0, 0.0, width as f32, height as f32).unwrap(); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, DEFAULT_COLORS, 1.0, false)); + if width >= 40 && height == 60 { + let (a, b) = marked_span(&pm, 37).unwrap_or((0, 0)); + assert!(b > a + width / 4, "width {width}: the bar keeps half its room, {a}..{b}"); + } + } + } + } + + /// A page draws its scale bar's details through `draw_page`: the unit label in the bar's colour. + #[test] + fn a_page_draws_a_scale_bar_with_its_details() { + let (mut maps, mut l, frame) = colour_test_page(); + let mut bar = ElementKind::scale_bar(frame); + if let ElementKind::ScaleBar { + color, label_position, unit_label, unit_label_position, subdivisions, divisions_before_zero, .. + } = &mut bar + { + *color = Rgba::rgb(0xD0, 0x10, 0x10); + (*label_position, *unit_label, *unit_label_position) = + (ScaleLabelPosition::Below, Some("Kilometres".into()), UnitLabelPosition::Above); + (*subdivisions, *divisions_before_zero) = (4, 1); + } + l.add("Scale Bar", (5.0, 5.0, 90.0, 20.0), bar.clone()); + let pm = render(&l, &mut maps, 96.0, &PageInfo::default()).unwrap(); + let rows = |from: u32, to: u32, hit: fn(tiny_skia::PremultipliedColorU8) -> bool| { + (from..to).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).filter(|&(x, y)| pm.pixel(x, y).is_some_and(hit)).count() + }; + // The strip of the bar's 20 mm box over the bar (its middle at 15 mm, its top 4 px above) + // holds the unit label, in the bar's colour. + let mm = pm.height() as f32 / 60.0; + assert!(rows((5.0 * mm) as u32, (13.5 * mm) as u32, red) > 30, "the unit label over the bar, crimson"); + assert_eq!(rows(0, pm.height() / 2, ink), 0, "no default ink"); + // The same bar without its details draws differently on the same page. + let (mut maps2, mut plain, frame2) = colour_test_page(); + let mut same = ElementKind::scale_bar(frame2); + if let ElementKind::ScaleBar { color, .. } = &mut same { + *color = Rgba::rgb(0xD0, 0x10, 0x10); + } + plain.add("Scale Bar", (5.0, 5.0, 90.0, 20.0), same); + assert_ne!(pm.data(), render(&plain, &mut maps2, 96.0, &PageInfo::default()).unwrap().data()); + } + #[test] fn scale_numbers_are_short() { assert_eq!(scale_number(5.0, 1.25), "5"); From dad5f7a183727ae18b7eb8997a76fd3a0be2ce47 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:13:56 -0600 Subject: [PATCH 06/55] fix(render): scale bar clippy and a real test for the unit-label cap Co-Authored-By: Claude Fable 5.1 --- crates/render/src/layout.rs | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index f5600a9cf3..209d0f71ad 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2310,8 +2310,17 @@ fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, bar_fit(room_m, unit_m, bar.fit, before, after) }; let Some(first) = fitted(beside) else { return }; - // The room left of zero follows the bar's length: fitted again with the first label's. - let fit = if before > 0 { fitted(beside + pad_of(&first)) } else { Some(first) }; + // The room left of zero follows the bar's length: fitted again with the first label's, and once + // more if the shorter bar's first label is wider ("-1.25" for "-1"). + let fit = if before > 0 { + let reserved = pad_of(&first); + match fitted(beside + reserved) { + Some(f) if pad_of(&f) > reserved => fitted(beside + pad_of(&f)), + f => f, + } + } else { + Some(first) + }; let Some(fit) = fit else { return }; let BarFit { total, after } = fit; let pad = pad_of(&fit); @@ -2354,7 +2363,7 @@ fn scale_bar(pm: &mut Canvas, r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, // Alternating parts, the last dark against the light division after it. let part = seg / parts as f32; for p in 0..parts { - let c = if (parts - 1 - p) % 2 == 0 { dark } else { light }; + let c = if (parts - 1 - p).is_multiple_of(2) { dark } else { light }; if let Some(b) = Rect::from_xywh(x + part * p as f32, y0, part, bar_h) { pm.fill_rect(b, &paint(c, 1.0), Transform::identity(), None); } @@ -8707,8 +8716,9 @@ Elaboração: RustGIS", let _ = draw(Some(text), at); } } - // A whitespace label adds no ink (on its own line it still takes its row, so compare after the bar). + // A label of spaces prints nothing and takes no room: after the bar or on a line of its own. assert_eq!(draw(Some(" "), UnitLabelPosition::AfterBar).data(), none.data()); + assert_eq!(draw(Some(" "), UnitLabelPosition::Above).data(), draw(Some(""), UnitLabelPosition::Above).data()); } #[test] @@ -8725,10 +8735,21 @@ Elaboração: RustGIS", let mut pm = Pixmap::new(width, height).unwrap(); pm.fill(tiny_skia::Color::WHITE); let r = Rect::from_xywh(0.0, 0.0, width as f32, height as f32).unwrap(); - crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, DEFAULT_COLORS, 1.0, false)); + // Filled in its colour throughout, so along its middle the bar is one solid run. + let solid = (DEFAULT_COLORS.0, DEFAULT_COLORS.0); + crate::canvas::with_canvas(&mut pm, |c| scale_bar(c, r, 100.0, &bar, solid, 1.0, false)); if width >= 40 && height == 60 { - let (a, b) = marked_span(&pm, 37).unwrap_or((0, 0)); - assert!(b > a + width / 4, "width {width}: the bar keeps half its room, {a}..{b}"); + let marked = |x: u32| pm.pixel(x, 37).is_some_and(|p| p.red() < 200 || p.green() < 200 || p.blue() < 200); + let a = (0..width).find(|&x| marked(x)).unwrap_or(width); + // The bar ends where the 3 px gap before its unit begins; the unit follows. + let gap = (a..width).find(|&x| (x..x + 3).all(|x| !marked(x))).unwrap_or(width); + let end = gap.saturating_sub(1); + let unit = (gap..width).find(|&x| marked(x)); + // Half the 85 % room is the bar's; its round length is at least 40 % of that. + let room = width as f32 * 0.85 * 0.5; + let (least, most) = ((room * 0.4) as u32 - 2, (room + 2.0) as u32); + assert!(end >= a + least && end <= a + most, "width {width}: the bar keeps half its room, {a}..{end}"); + assert!(unit.is_some_and(|x| x >= end + 3), "width {width}: the unit after the bar, from {unit:?}"); } } } From 2ad527a651fdd9603fb193c7f85faee32f09e1ee Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:50:38 -0600 Subject: [PATCH 07/55] feat(layout): scale bar details through layout.addElement and layout.update Bad values are refused before anything changes; the details are refused for other elements. Projects and saved commands that use them require layout-scale-bar-details. A publication's scale box isn't re-measured for a detailed bar. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/cmd/layout.rs | 132 +++++++++++-- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 112 +++++++++++ crates/engine/src/tests.rs | 174 ++++++++++++++++++ crates/engine/src/tests/layout_files.rs | 7 + crates/map/src/layout.rs | 3 +- docs/maintaining.md | 10 + schema/fixtures/layout_scale_bar_details.rgis | 1 + 8 files changed, 423 insertions(+), 17 deletions(-) create mode 100644 schema/fixtures/layout_scale_bar_details.rgis diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 82ae87bbf6..029c98c2d9 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -9,9 +9,10 @@ use rustgis_geom::{Coord, Extent}; use rustgis_map::layout::{ Arrange, ArrowStyle, Background, CHART_BAR, CHART_BARS, ChartOrder, CoordFormat, ElementKind, FontFamily, FrameShape, Grid, GridEdges, GridKind, GridStyle, Guides, LEGEND_TEXT_SIZE, Layout, LineDir, LineHead, MAX_CHART_BARS, MAX_CHART_DECIMALS, MAX_COLORBAR_TICKS, - MAX_GRID_WIDTH, MAX_GUIDES, MAX_LEGEND_COLUMNS, MAX_LEGEND_LABEL_CHARS, MAX_LEGEND_LABELS, MAX_SCALE_DIVISIONS, MAX_TICK_MM, - MIN_ELEMENT_MM, MapSeries, Orientation, PAGES, ScaleBarStyle, ScaleUnits, TextAlign, TickSide, fit_scale, line_angle, line_at_angle, - line_length, + MAX_GRID_WIDTH, MAX_GUIDES, MAX_LEGEND_COLUMNS, MAX_LEGEND_LABEL_CHARS, MAX_LEGEND_LABELS, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, + MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, MAX_TICK_MM, MAX_UNIT_LABEL_CHARS, MIN_ELEMENT_MM, MapSeries, Orientation, PAGES, + SCALE_LABEL_SIZE, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, TextAlign, TickSide, UnitLabelPosition, fit_scale, + line_angle, line_at_angle, line_length, }; use rustgis_map::report::StatKind; use rustgis_map::symbology::{Dash, MAX_DASH_STEP, MAX_DASH_STEPS}; @@ -107,10 +108,10 @@ pub fn commands() -> Vec { 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}"#, ), C::new("layout.addElement", "Add Element", "Publish › Map Surrounds", add_element).inputs(element_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( - r##"{"layout"?, "kind": "northArrow"|"scaleBar"|"legend"|"colorbar"|"text"|"dynamicText"|"picture"|"table"|"chart"|"rectangle" (a neatline framing the page unless any of x, y, w, h is given)|"ellipse"|"circle"|"line"|"arrow"|"extentIndicator"|"grid", "frame"?: element id (default: the first map frame), "of"?: frame id (extentIndicator, which also takes "color" and "width" in points, default red and 2), "text"?, "size"?, "color"?: "#RRGGBB"|"#RRGGBBAA" (text, dynamicText, line, arrow, rectangle, ellipse, circle: its outline; extentIndicator; grid; scaleBar; legend, colorbar, table, chart: the ink of its text and lines, default #222222, a chart's bars and a colorbar's colours keeping theirs, and a table drawn without its white cells; refused for other kinds), "bold"?: bool (text), "italic"?: bool, "align"?: "left"|"center"|"right", "letterSpacing"?: points, -5 to 50 (text, dynamicText), "rotation"?: degrees clockwise about the box's centre, 90 reading top to bottom and -90 bottom to top, kept within -180 to 180 (text, dynamicText; refused for other kinds), "wrap"?: bool (text, dynamicText: broken into lines at spaces to fit the box's width when drawn, after its dynamic text is filled in, a word wider than the box broken across lines; default false, lines breaking only at the text's own line breaks; refused for other kinds), "font"?: "sans"|"serif"|an installed font family's name, as labels.fonts lists them (text, dynamicText; 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), "fallback"?: "sans"|"serif" (a named font's, where it isn't installed; default its own class, else sans), "title"?: legend title (default "Legend"); chart: its own title ("" for none; default: its field, or the statistic of its field by the group), "allClasses"?: bool (legend: every class, not only those the frame draws), "hideOther"?: bool (legend: leave out ), "showNoData"?: bool (legend: include Graduated Colors’ missing-value symbol; default false), "exclude"?: [layer names] (legend: layers it leaves out though the map draws them), "columns"?: 1..3 (legend: the columns its rows are laid in; default 1), "textSize"?: points, 4 to 100 (legend: its layers' names and classes' labels, its title, rows, swatches and gaps following in proportion and a point symbol keeping the size the map draws it at; default 9; refused outside that range, and for other kinds unless null, as showNoData is), "orientation"?: "horizontal"|"vertical" (colorbar; chart: bars running across, the default, or columns standing up, each label centred under its column), "ticks"?: 2..21 (colorbar: labelled values, ends included), "tickSide"?: "below"|"above"|"right"|"left" (colorbar), "reverse"?: bool (colorbar: high values first), "fill"?: "#RRGGBBAA" (rectangle, ellipse, circle, northArrow; scaleBar: the alternating bar's light divisions, default white; refused for other kinds), "width"?: outline width in points (rectangle, ellipse, circle; 0 for none) or line width in points (line, grid), "radius"?: mm, 0 to 50 (rectangle: rounded corners), "dash"?: [points, …] (line, arrow, and a rectangle's, ellipse's or circle's outline: dash, gap, … in turn, as layer.lineStrokes takes it, at most 8, each 0 to 500; an arrow's heads stay solid; [] or null for solid; refused, null too, for other kinds), "dir"?: "horizontal"|"vertical"|"falling"|"rising" (line), "head"?: "none"|"end"|"start"|"both" (line; default "end" for an arrow), "angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "length"?: mm (line, arrow), "image"?: base64, "path"?: picture file, "layer"?: (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists), "field"?: (chart: a numeric field, default the layer's first; any field when it groups and counts, default then the field it groups by), "label"?: a field (chart: each bar's label when not grouped), "group"?: a field (chart: a bar per value of this field, its statistic of field over that value's features; blank values make one "(blank)" bar; default none, a bar per feature), "statistic"?: "sum" (the default)|"count" (features, numbers or not)|"mean"|"min"|"max" (chart, grouped), "order"?: "descending" (the default: largest first)|"ascending"|"category" (by label, A to Z)|"layer" (as the features come) (chart), "bars"?: 1..100 (chart: the most bars drawn, default 20), "other"?: bool (chart: the bars past "bars" gathered in a last Other bar, its statistic over their features, their sum when not grouped, last whatever the order; default false: left out, which a warning says, as it says features with no number left out), "stack"?: a field (chart, grouped by another field, summing or counting: each bar split by this field's values, a stretch per value in the key over the bars, the values its bars show by their total, largest first (A to Z when ordered by category), past 8 values 7 and a grey Other, which a warning counts; in the palette diagrams take, or with classes in the colour each value's features share on the map, a value with several keeping its palette colour, which a warning counts; values written are the bar's total; default none), "values"?: bool (chart: each bar's value written past its end, its thousands apart with commas; default false), "decimals"?: "auto" (the default: up to 2, the zeros they end in dropped)|0..6 (chart: its values' decimals), "barColor"?: "#RRGGBB"|"#RRGGBBAA" (chart: its bars' colour, default #3B82C4), "classes"?: bool (chart: each bar in the colour its features have on the map, by the layer's symbology classes: a bar per feature its feature's, a grouped bar the colour its features share; a bar whose features have several, which a warning counts, and an Other bar keep barColor; default false), "labelAlign"?: "left" (the default)|"right" (chart: bars running across have their labels at the left of their column, or at its right against the bars) (label, group, statistic, order, bars, other, stack, values, decimals, barColor, classes and labelAlign refused for other kinds), "rows"?, "step"?: degrees, or a measured grid's units (metres) (0 picks one), "type"?: "graticule" (latitudes and longitudes, default) | "measured" (eastings and northings in a projected system), "crs"?: a measured grid's coordinate system: EPSG:25832, WKT or a PROJ string ("" or none: the map's when projected, else the UTM zone at the frame's centre), "short"?: bool (a measured grid's labels as their kilometres' last two digits, 43 for 543000), "mgrs"?: bool (a measured grid labelled as MGRS: each 100 km square named with its grid zone designation, 32T MT, and the lines by their kilometres' last two digits; its crs a WGS 84 UTM zone by EPSG code, EPSG:32601–32660 or 32701–32760, or none: the map's when it is one, else the zone at the frame's centre), "labels"?: bool (grid) | {"": "