From 1453616c550191d1c862ed91c4ef661bfa0d0f98 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:07:02 -0600 Subject: [PATCH 01/23] test(render): pin how a plain layout text draws, is measured and exports A text with none of the coming block settings is pinned by hashes of main's drawing, its cut-off check, its SVG and its PDF, in the built-in face in a child process. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout.rs | 80 +++++++++++++++++++++++++++++++++++++ crates/render/src/svg.rs | 40 +++++++++++++++++++ 2 files changed, 120 insertions(+) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 2b132528b3..7bc490699e 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -5055,6 +5055,42 @@ pub fn map_index(maps: &[rustgis_map::Map], name: &str) -> Option { maps.iter().position(|map| map.name.eq_ignore_ascii_case(name)) } +/// Pages of one text each with none of the block settings, in the combinations main draws: each +/// alignment, wrapped or not, turned 0, 90, -90 or 33 degrees, spaced 0 or 3 points (bold, and +/// italic when turned 33), in a box that holds its lines and one that cuts them; and two texts +/// across the page's right and bottom edges. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn plain_text_pages() -> Vec { + let text = "Population counts\nfrom the 2020 census; boundaries simplified for print\nPage {page} of {pages}"; + let page = |at: (f64, f64, f64, f64), f: &dyn Fn(&mut ElementKind)| { + let mut l = Layout::new("Plain", 120.0, 80.0); + let mut kind = ElementKind::text(text, 11.0, Rgba::rgb(0, 0, 0), false); + f(&mut kind); + l.add("Note", at, kind); + l + }; + let mut pages = Vec::new(); + for align in TextAlign::ALL { + for wrap in [false, true] { + for turn in [0.0, 90.0, -90.0, 33.0] { + for spacing in [0.0, 3.0] { + for h in [40.0, 9.0] { + pages.push(page((10.0, 10.0, 60.0, h), &|k| { + if let ElementKind::Text { align: a, wrap: w, rotation, letter_spacing, italic, bold, .. } = k { + (*a, *w, *rotation, *letter_spacing) = (align, wrap, turn, spacing); + (*italic, *bold) = (turn == 33.0, spacing > 0.0); + } + })); + } + } + } + } + } + pages.push(page((90.0, 10.0, 60.0, 30.0), &|_| {})); + pages.push(page((10.0, 74.0, 60.0, 30.0), &|_| {})); + pages +} + #[expect(clippy::disallowed_methods, reason = "a thread the system refuses fails the test, as it should")] #[cfg(test)] mod tests { @@ -9657,6 +9693,12 @@ Elaboração: RustGIS", pms.iter().flat_map(|p| p.data().iter()).fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) } + /// 64-bit FNV-1a over one byte slice. + #[cfg(not(target_arch = "wasm32"))] + fn fnv_bytes(b: &[u8]) -> u64 { + b.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. #[cfg(not(target_arch = "wasm32"))] fn draw_default(style: ScaleBarStyle, units: ScaleUnits, divisions: usize, ground: f64, w: u32, ppp: f64, comma: bool) -> Pixmap { @@ -9668,6 +9710,44 @@ Elaboração: RustGIS", pm } + /// How [`plain_texts_draw_as_before`]'s pages drew, and what their cut-off check found, before + /// texts had a block alignment, line spacing or case; in the built-in face. + #[cfg(not(target_arch = "wasm32"))] + const PINNED_TEXT_PIXELS: u64 = 0x0556_a0ef_54c0_2e87; + #[cfg(not(target_arch = "wasm32"))] + const PINNED_TEXT_LOSSES: u64 = 0x26af_01ce_67e5_7cfd; + + /// A text with none of the block settings draws, and is measured for lines that don't fit and ink + /// off the page, exactly as main did, at 96 and 300 dpi: in a process of its own, told to use the + /// built-in face before any text. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn plain_texts_draw_as_before() { + if std::env::var_os("RUSTGIS_TEXT_PIN_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "layout::tests::plain_texts_draw_as_before", "--nocapture"]) + .env("RUSTGIS_TEXT_PIN_CHILD", "1") + .env("RUSTGIS_BUILTIN_FONTS", "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); + return; + } + let info = PageInfo { page: 2, pages: 3, page_name: String::new() }; + let (mut drawn, mut measured) = (Vec::new(), String::new()); + for (i, l) in crate::layout::plain_text_pages().iter().enumerate() { + for dpi in if i < 8 { &[96.0, 300.0][..] } else { &[96.0][..] } { + drawn.push(render(l, &mut [], *dpi, &info).unwrap()); + measured.push_str(&format!("{:?}\n", text_losses(l, &[], *dpi, &info))); + } + } + // The pages exercise both checks. + assert!(measured.contains("below_box: true") && measured.contains("off_page: true"), "{measured}"); + let losses = fnv_bytes(measured.as_bytes()); + assert_eq!((fnv(&drawn), losses), (PINNED_TEXT_PIXELS, PINNED_TEXT_LOSSES), "{:#x} {:#x}", fnv(&drawn), losses); + } + /// How [`scale_bars_without_details_draw_as_before`]'s bars drew before scale bars had details, /// their labels in the built-in face. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index bcc91fe2a3..781692c89b 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -701,4 +701,44 @@ mod tests { let turned = svg(90.0, Some(b)); assert!(turned.contains(r#"stroke-width="0.265" transform="rotate(90 50 45)"/>"#), "turned about the box's centre: {turned}"); } + + /// 64-bit FNV-1a over a byte slice. + #[cfg(not(target_arch = "wasm32"))] + fn fnv(b: &[u8]) -> u64 { + b.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) + } + + /// How [`plain_texts_export_as_before`]'s pages were written as SVG and as a vector PDF before + /// texts had a block alignment, line spacing or case; in the built-in face. + #[cfg(not(target_arch = "wasm32"))] + const PINNED_TEXT_SVG: u64 = 0xf2dd_eccc_ab7b_44bc; + #[cfg(not(target_arch = "wasm32"))] + const PINNED_TEXT_PDF: u64 = 0xf770_433e_0662_5b2e; + + /// The SVG and the vector PDF of a text with none of the block settings are byte for byte main's: + /// in a process of its own, told to use the built-in face before any text. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn plain_texts_export_as_before() { + if std::env::var_os("RUSTGIS_TEXT_EXPORT_PIN_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "svg::tests::plain_texts_export_as_before", "--nocapture"]) + .env("RUSTGIS_TEXT_EXPORT_PIN_CHILD", "1") + .env("RUSTGIS_BUILTIN_FONTS", "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); + return; + } + let info = PageInfo { page: 2, pages: 3, page_name: String::new() }; + let (mut svg, mut pdf) = (Vec::new(), Vec::new()); + for l in crate::layout::plain_text_pages() { + svg.extend(layout_svg(&l, &mut [], 72.0, &info).unwrap().0.into_bytes()); + let (drawing, _) = crate::layout::render_drawing(&l, &mut [], 150.0, &info).unwrap(); + pdf.extend(crate::pdf::write(&[crate::pdf::Page::drawing(drawing, l.width, l.height)], "Plain")); + } + let (s, p) = (fnv(&svg), fnv(&pdf)); + assert_eq!((s, p), (PINNED_TEXT_SVG, PINNED_TEXT_PDF), "{s:#x} {p:#x}"); + } } From b42fe40e788defa160f67e3db8cfecb070f9a0b8 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:26:20 -0600 Subject: [PATCH 02/23] feat(layout): a text's block alignment, line spacing and case in the layout model Saved only when set, so a text saved before saves byte for byte; a hand-edited value out of range, of the wrong kind or not a name is brought into range and counted when a layout is read. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout.rs | 15 +- crates/engine/src/tests.rs | 3 + crates/map/src/layout.rs | 305 +++++++++++++++++++++++++++++++- crates/render/src/layout.rs | 8 +- crates/render/src/svg.rs | 2 +- 5 files changed, 323 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index b4ebd65277..174d680b93 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -8,11 +8,12 @@ use std::sync::LazyLock; use rustgis_geom::{Coord, Extent}; use rustgis_map::layout::{ Arrange, ArrowStyle, Background, CHART_BAR, CHART_BARS, CHART_OUTLINE, ChartOrder, ChartOutline, CoordFormat, ElementKind, FontFamily, - FrameShape, GRID_LABEL_PT, Grid, GridEdges, GridKind, GridStyle, Guides, LAYOUT_TEXT_SIZE, Layout, LineDir, LineHead, MAX_CHART_BARS, - MAX_CHART_DECIMALS, MAX_CHART_OUTLINE_WIDTH, MAX_COLORBAR_TICKS, MAX_GRID_WIDTH, MAX_GUIDES, MAX_LEGEND_COLUMNS, + FrameShape, GRID_LABEL_PT, Grid, GridEdges, GridKind, GridStyle, Guides, LAYOUT_TEXT_SIZE, LINE_SPACING, Layout, LineDir, LineHead, + MAX_CHART_BARS, MAX_CHART_DECIMALS, MAX_CHART_OUTLINE_WIDTH, MAX_COLORBAR_TICKS, 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_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, - ScaleLabelPosition, ScaleUnits, TextAlign, TickSide, UnitLabelPosition, fit_scale, line_angle, line_at_angle, line_length, + ScaleLabelPosition, ScaleUnits, TextAlign, TextCase, TextVAlign, 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}; @@ -593,6 +594,9 @@ fn pub_text_in(text: String, size: f64, color: Rgba, bold: bool, align: TextAlig font_name: None, rotation: 0.0, wrap: false, + valign: TextVAlign::Top, + line_spacing: LINE_SPACING, + case: TextCase::None, } } @@ -3877,6 +3881,9 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { font_name, rotation, wrap, + valign: TextVAlign::Top, + line_spacing: LINE_SPACING, + case: TextCase::None, }; (if kind == "text" { "Text" } else { "Dynamic Text" }, place(p, l, (15.0, 12.0, 120.0, (size * 0.5).max(8.0)))?, k) } @@ -5611,7 +5618,7 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { } } match &mut e.kind { - ElementKind::Text { text, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap } => { + ElementKind::Text { text, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap, .. } => { if let Some(((i, a, l), (f, n))) = new_text_style { (*italic, *align, *letter_spacing, *font, *font_name) = (i, a, l, f, n); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5d59f560ed..987512eb0b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -58277,6 +58277,9 @@ fn the_footer_lines_up_with_a_legend_at_the_right() { font_name: None, rotation: 0.0, wrap: false, + valign: Default::default(), + line_spacing: rustgis_map::layout::LINE_SPACING, + case: Default::default(), }; let card = || ElementKind::Rectangle { fill: rustgis_map::Rgba::new(0, 0, 0, 0), diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index 6a7f41f2b8..795a541e0d 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -497,6 +497,191 @@ fn is_left(a: &TextAlign) -> bool { *a == TextAlign::Left } +/// Where a text element's block of lines sits down its box. +/// +/// `Invalid` is what a file's unknown name or wrong kind of value is read as; it is never kept: +/// [`Layout::clamp`] sends it to the default and counts the element, and a save writes the +/// default's name for it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TextVAlign { + /// From the top of the box. + #[default] + Top, + /// Centred in the box. + Middle, + /// Down to the bottom of the box. + Bottom, + /// A value read from a file that is not a name; repaired to the default on load. + #[doc(hidden)] + Invalid, +} + +impl TextVAlign { + pub const ALL: [TextVAlign; 3] = [TextVAlign::Top, TextVAlign::Middle, TextVAlign::Bottom]; + + pub fn code(self) -> &'static str { + match self { + TextVAlign::Top | TextVAlign::Invalid => "top", + TextVAlign::Middle => "middle", + TextVAlign::Bottom => "bottom", + } + } + + pub fn label(self) -> &'static str { + match self { + TextVAlign::Top | TextVAlign::Invalid => "Top", + TextVAlign::Middle => "Middle", + TextVAlign::Bottom => "Bottom", + } + } + + /// `top`, `middle` or `bottom` in any case, trimmed; `center` and `centre` read as middle. + pub fn from_name(s: &str) -> Option { + let s = s.trim(); + TextVAlign::ALL + .into_iter() + .find(|v| v.code().eq_ignore_ascii_case(s)) + .or((s.eq_ignore_ascii_case("centre") || s.eq_ignore_ascii_case("center")).then_some(TextVAlign::Middle)) + } + + /// This value, or the default where it is [`TextVAlign::Invalid`]. + pub fn kept(self) -> TextVAlign { + if self == TextVAlign::Invalid { TextVAlign::default() } else { self } + } +} + +impl Serialize for TextVAlign { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.kept().code()) + } +} + +impl<'de> Deserialize<'de> for TextVAlign { + /// A name as [`TextVAlign::from_name`] reads it; null as the default; anything else (an + /// unknown name, a number, a list) as `Invalid`, so the read never fails and `Layout::clamp` + /// repairs and counts it. + fn deserialize>(d: D) -> Result { + let v: Option = Deserialize::deserialize(d)?; + Ok(match v { + None | Some(serde_json::Value::Null) => TextVAlign::default(), + Some(serde_json::Value::String(s)) => TextVAlign::from_name(&s).unwrap_or(TextVAlign::Invalid), + Some(_) => TextVAlign::Invalid, + }) + } +} + +fn is_top(v: &TextVAlign) -> bool { + *v == TextVAlign::Top +} + +/// The case a text element is drawn in. +/// +/// `Invalid` is what a file's unknown name or wrong kind of value is read as; it is never kept: +/// [`Layout::clamp`] sends it to the default and counts the element, and a save writes the +/// default's name for it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TextCase { + /// As typed. + #[default] + None, + /// All upper case. + Upper, + /// All lower case. + Lower, + /// A value read from a file that is not a name; repaired to the default on load. + #[doc(hidden)] + Invalid, +} + +impl TextCase { + pub const ALL: [TextCase; 3] = [TextCase::None, TextCase::Upper, TextCase::Lower]; + + pub fn code(self) -> &'static str { + match self { + TextCase::None | TextCase::Invalid => "none", + TextCase::Upper => "upper", + TextCase::Lower => "lower", + } + } + + pub fn label(self) -> &'static str { + match self { + TextCase::None | TextCase::Invalid => "As typed", + TextCase::Upper => "UPPER CASE", + TextCase::Lower => "lower case", + } + } + + /// `none`, `upper` or `lower` in any case, trimmed. + pub fn from_name(s: &str) -> Option { + let s = s.trim(); + TextCase::ALL.into_iter().find(|v| v.code().eq_ignore_ascii_case(s)) + } + + /// This value, or the default where it is [`TextCase::Invalid`]. + pub fn kept(self) -> TextCase { + if self == TextCase::Invalid { TextCase::default() } else { self } + } + + /// `s` in this case (full Unicode case mapping: `ß` is `SS` in upper case). + pub fn apply(self, s: String) -> String { + match self.kept() { + TextCase::Upper => s.to_uppercase(), + TextCase::Lower => s.to_lowercase(), + _ => s, + } + } +} + +impl Serialize for TextCase { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.kept().code()) + } +} + +impl<'de> Deserialize<'de> for TextCase { + /// A name as [`TextCase::from_name`] reads it; null as the default; anything else as + /// `Invalid`, so the read never fails and `Layout::clamp` repairs and counts it. + fn deserialize>(d: D) -> Result { + let v: Option = Deserialize::deserialize(d)?; + Ok(match v { + None | Some(serde_json::Value::Null) => TextCase::default(), + Some(serde_json::Value::String(s)) => TextCase::from_name(&s).unwrap_or(TextCase::Invalid), + Some(_) => TextCase::Invalid, + }) + } +} + +fn is_no_case(v: &TextCase) -> bool { + *v == TextCase::None +} + +/// The usual spacing between a text's lines, as a multiple of it. +pub const LINE_SPACING: f64 = 1.0; +/// The tightest and widest a text's line spacing may be, as multiples of the usual. +pub const MIN_LINE_SPACING: f64 = 0.5; +pub const MAX_LINE_SPACING: f64 = 3.0; + +fn line_spacing() -> f64 { + LINE_SPACING +} + +fn is_line_spacing(v: &f64) -> bool { + *v == LINE_SPACING +} + +/// A text's line spacing as a file holds it: a number as it is (out of range is for +/// `Layout::clamp`), null as the usual, anything else (a string, a flag, a list, an object) as NaN, +/// which `Layout::clamp` brings back to the usual and counts. +fn de_line_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v: Option = Deserialize::deserialize(d)?; + Ok(match v { + None | Some(serde_json::Value::Null) => LINE_SPACING, + Some(serde_json::Value::Number(n)) => n.as_f64().unwrap_or(f64::NAN), + Some(_) => f64::NAN, + }) +} + /// The most layers a legend leaves out. pub const MAX_LEGEND_EXCLUDED: usize = 1000; @@ -1267,6 +1452,18 @@ pub enum ElementKind { /// line break. Left out when off, so layouts saved before keep their bytes. #[serde(default, skip_serializing_if = "is_false")] wrap: bool, + /// Where its block of lines sits down the (unturned) box. Left out when top, so layouts + /// saved before keep their bytes. + #[serde(default, skip_serializing_if = "is_top")] + valign: TextVAlign, + /// The space between its lines, as a multiple of the usual ([`MIN_LINE_SPACING`] to + /// [`MAX_LINE_SPACING`]). Left out when usual, so layouts saved before keep their bytes. + #[serde(default = "line_spacing", skip_serializing_if = "is_line_spacing", deserialize_with = "de_line_spacing")] + line_spacing: f64, + /// Its words in upper or lower case when drawn, after its dynamic text is filled in. Left + /// out when as typed, so layouts saved before keep their bytes. + #[serde(default, skip_serializing_if = "is_no_case")] + case: TextCase, }, Picture { /// Base64 PNG or JPEG. @@ -1658,6 +1855,9 @@ impl ElementKind { font_name: None, rotation: 0.0, wrap: false, + valign: TextVAlign::Top, + line_spacing: LINE_SPACING, + case: TextCase::None, } } @@ -1686,6 +1886,17 @@ impl ElementKind { } } + /// Whether this is a text whose block alignment, line spacing or case is not the default, once + /// brought into range as [`Layout::clamp`] does: what a layout file needs a newer reader for. + pub fn text_uses_block(&self) -> bool { + let ElementKind::Text { valign, line_spacing, case, .. } = self else { + return false; + }; + valign.kept() != TextVAlign::Top + || case.kept() != TextCase::None + || finite_or(*line_spacing, LINE_SPACING).clamp(MIN_LINE_SPACING, MAX_LINE_SPACING) != LINE_SPACING + } + /// 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 or a fit. Its text size /// isn't one: [`ElementKind::has_custom_text_size`] tells that. @@ -2956,8 +3167,12 @@ impl Layout { label.truncate(end); } } - ElementKind::Text { text, size, letter_spacing, rotation: turn, .. } => { + ElementKind::Text { text, size, letter_spacing, rotation: turn, valign, line_spacing, case, .. } => { *turn = rotation(*turn); + // A file's unknown name or wrong kind of value is read as a marker: back to the default. + *valign = valign.kept(); + *case = case.kept(); + *line_spacing = finite_or(*line_spacing, LINE_SPACING).clamp(MIN_LINE_SPACING, MAX_LINE_SPACING); *size = finite_or(*size, 12.0).clamp(*crate::graphics::FONT_SIZE.start(), *crate::graphics::FONT_SIZE.end()); *letter_spacing = finite_or(*letter_spacing, 0.0).clamp(MIN_LETTER_SPACING, MAX_LETTER_SPACING); let end = text.char_indices().nth(5000).map_or(text.len(), |(i, _)| i); @@ -4733,6 +4948,94 @@ mod tests { assert!(!text.takes_ink() && text.ink_mut().is_none(), "a text's colour is its own option"); } + /// A text's block alignment, line spacing and case: left out of the file at their defaults, so a + /// text saved before saves byte for byte; written and read back when set; and a hand-edited value + /// out of range, of the wrong kind or not a name loads, brought into range and counted. + #[test] + fn text_block_settings_save_only_when_set_and_load_into_range() { + use serde_json::json; + for plain in [ + r#"{"Text":{"text":"a","size":10.0,"color":[0,0,0,255],"bold":false}}"#, + r#"{"Text":{"text":"a\nb","size":12.0,"color":[31,41,55,255],"bold":true,"italic":true,"align":"Center","letter_spacing":2.0,"font":"Serif","font_name":"Georgia","rotation":90.0,"wrap":true}}"#, + ] { + let k: ElementKind = serde_json::from_str(plain).unwrap(); + assert_eq!(serde_json::to_string(&k).unwrap(), plain); + assert!(!k.text_uses_block()); + } + let mut set = ElementKind::text("a", 10.0, Rgba::rgb(0, 0, 0), false); + if let ElementKind::Text { valign, line_spacing, case, .. } = &mut set { + (*valign, *line_spacing, *case) = (TextVAlign::Bottom, 1.5, TextCase::Upper); + } + let s = serde_json::to_string(&set).unwrap(); + assert!(s.ends_with(r#""bold":false,"valign":"bottom","line_spacing":1.5,"case":"upper"}}"#), "{s}"); + assert_eq!(serde_json::from_str::(&s).unwrap(), set); + assert!(set.text_uses_block()); + for (name, v) in [ + (" MIDDLE ", TextVAlign::Middle), + ("centre", TextVAlign::Middle), + ("Center", TextVAlign::Middle), + ("Top", TextVAlign::Top), + ("bottom", TextVAlign::Bottom), + ] { + assert_eq!(TextVAlign::from_name(name), Some(v), "{name}"); + } + assert_eq!((TextVAlign::from_name("baseline"), TextCase::from_name("title")), (None, None)); + assert_eq!(TextCase::from_name(" Upper "), Some(TextCase::Upper)); + assert_eq!(TextCase::Upper.apply("Straße {9}".into()), "STRASSE {9}"); + assert_eq!(TextCase::Lower.apply("ÉTÉ".into()), "été"); + assert_eq!(TextCase::None.apply("As Typed".into()), "As Typed"); + // A hand-edited layout. + let extras = [ + json!({"line_spacing": 9}), // 2: to 3, said + json!({"line_spacing": 0.1}), // 3: to 0.5, said + json!({"line_spacing": "1.5"}), // 4: no number: 1, said + json!({"line_spacing": [2]}), // 5: 1, said + json!({"valign": "sideways"}), // 6: top, said + json!({"valign": 7}), // 7: top, said + json!({"case": "title"}), // 8: none, said + json!({"case": {"x": 1}}), // 9: none, said + json!({"valign": "Middle", "case": "UPPER", "line_spacing": 2}), // 10: kept, not said + json!({"valign": null, "case": null, "line_spacing": null}), // 11: defaults, not said + json!({"valign": "centre", "line_spacing": 3.0}), // 12: kept, not said + ]; + let elements: Vec<_> = extras + .iter() + .enumerate() + .map(|(i, extra)| { + let mut t = json!({"text": "a", "size": 10.0, "color": [0, 0, 0, 255], "bold": false}); + t.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + json!({"id": i + 2, "name": "t", "x": 0, "y": 0, "w": 10, "h": 10, "kind": {"Text": t}}) + }) + .collect(); + let mut l: Layout = serde_json::from_value(json!({"name": "x", "width": 100, "height": 100, "elements": elements})).unwrap(); + let repairs = l.clamp(); + let block = |id| match &l.element(id).unwrap().kind { + ElementKind::Text { valign, line_spacing, case, .. } => (*valign, *line_spacing, *case), + k => panic!("{k:?}"), + }; + use {TextCase as C, TextVAlign as V}; + let want = [ + (2, (V::Top, 3.0, C::None)), + (3, (V::Top, 0.5, C::None)), + (4, (V::Top, 1.0, C::None)), + (5, (V::Top, 1.0, C::None)), + (6, (V::Top, 1.0, C::None)), + (7, (V::Top, 1.0, C::None)), + (8, (V::Top, 1.0, C::None)), + (9, (V::Top, 1.0, C::None)), + (10, (V::Middle, 2.0, C::Upper)), + (11, (V::Top, 1.0, C::None)), + (12, (V::Middle, 3.0, C::None)), + ]; + for (id, b) in want { + assert_eq!(block(id), b, "{id}"); + } + assert_eq!((repairs.elements_adjusted, repairs.elements_cut), (8, 0)); + // Repaired to the defaults, they save nothing; no marker is ever written. + let saved = serde_json::to_string(&l).unwrap(); + assert!(!saved.contains("sideways") && !saved.contains("title") && saved.matches("\"valign\"").count() == 2, "{saved}"); + } + #[test] fn scale_bars_without_details_save_as_before() { // As main writes a plain bar: colour and fill always, nothing new. diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 7bc490699e..b992440025 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -376,9 +376,9 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option let mut labels_cut = false; // `fits`: how many of its lines the element draws, when it decides that itself. let (s, size, face, align, spacing, rotation, title, broken, fits) = match &e.kind { - ElementKind::Text { text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap } - if color.a() > 0 => - { + ElementKind::Text { + text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap, .. + } if color.a() > 0 => { let style = text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing); let s = expand(t, layout, info, first); // Its lines as they are drawn: a wrapped text's, broken to its box. @@ -899,7 +899,7 @@ fn draw_page( None => placeholder(&mut pm, r, "Colorbar", ppp), } } - ElementKind::Text { text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap } => { + ElementKind::Text { text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap, .. } => { let first = layout.first_frame().and_then(frame); let s = expand(t, layout, info, first.and_then(|f| maps.get(f.1).map(|m| (m, f.2)))); let style = text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing); diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 781692c89b..ad63d42987 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -95,7 +95,7 @@ fn elements( background(&mut s, e); let (x, y, w, h) = (e.x, e.y, e.w, e.h); match &e.kind { - ElementKind::Text { text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap } => { + ElementKind::Text { text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap, .. } => { let first = layout.first_frame().and_then(|id| layout.element(id)).and_then(|f| match &f.kind { ElementKind::MapFrame { map, center, scale, bearing, pitch, .. } => { let m = maps.iter().find(|m| m.name.eq_ignore_ascii_case(map))?; From 699a911bd76176ad31c85abae3413ce8fd26cb77 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:54:59 -0600 Subject: [PATCH 03/23] feat(render): a layout text's block at the top, middle or bottom of its box, its line spacing and case Case applies after the tokens fill in and before the wrap. A block taller than its box is drawn from the top, so its first lines are kept and the cut-off check counts the same lines left out whatever the alignment; it steps by the spaced pitch, as the page draws. A plain text draws and is measured as before, pinned. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout.rs | 380 +++++++++++++++++++++++++++++++++--- crates/render/src/svg.rs | 8 +- 2 files changed, 359 insertions(+), 29 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index b992440025..c0b1f7b179 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -9,8 +9,8 @@ use rustgis_data::query::{Env, SeriesPage}; use rustgis_geom::{Coord, Extent}; use rustgis_map::layout::{ ArrowStyle, ChartLook, ColorScale, ElementKind, FrameShape, GRID_LABEL_PT, Grid, GridKind, INK, Layout, LineHead, MAX_LEGEND_COLUMNS, - Orientation, PT_PER_MM, SCALE_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, TextAlign, TickSide, - UnitLabelPosition, frame_camera, layout_text_scale, + Orientation, PT_PER_MM, SCALE_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, TextAlign, TextCase, TextVAlign, + TickSide, UnitLabelPosition, frame_camera, layout_text_scale, }; use rustgis_map::symbology::LegendEntry; use rustgis_map::{Map, Rgba}; @@ -338,7 +338,11 @@ fn bar_labels_cut( Some((off_page, bar.cramped, bar.unit_cut)) } -/// The texts cut off, of the whole page or of the element `only`. +/// The texts cut off, of the whole page or of the element `only`. A text's lines are the ones the +/// page draws ([`drawn_text`]), placed as [`text_block`] places them: its block shifted down its +/// box by its alignment and stepped by its spaced pitch. A block taller than its box starts at its +/// top whatever its alignment, so the same trailing lines are left out and counted as for a text +/// at the top. fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option) -> Vec { let (w, h, k) = page_geometry(layout, dpi); let ppp = (k / PT_PER_MM) as f32; @@ -375,22 +379,58 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option // A colorbar's labels left out for want of height, said with its title (#2638). let mut labels_cut = false; // `fits`: how many of its lines the element draws, when it decides that itself. - let (s, size, face, align, spacing, rotation, title, broken, fits) = match &e.kind { + let (s, size, face, align, spacing, rotation, title, broken, fits, block) = match &e.kind { ElementKind::Text { - text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap, .. + text: t, + size, + color, + bold, + italic, + align, + letter_spacing, + font, + font_name, + rotation, + wrap, + valign, + line_spacing, + case, + .. } if color.a() > 0 => { - let style = text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing); - let s = expand(t, layout, info, first); - // Its lines as they are drawn: a wrapped text's, broken to its box. - let s = if *wrap { wrapped(&s, e.w, *size, style) } else { s }; - (s, *size as f32, style.face, *align, *letter_spacing as f32, *rotation as f32, false, *wrap, None) + let style = + text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing).with_block(*valign, *line_spacing); + // Its lines as they are drawn: in its case, a wrapped text's broken to its box. + let s = drawn_text(expand(t, layout, info, first), *case, *wrap, e.w, *size, style); + ( + s, + *size as f32, + style.face, + *align, + *letter_spacing as f32, + *rotation as f32, + false, + *wrap, + None, + (style.valign, style.line_spacing_kept()), + ) } // Its title at the size it is drawn at, its legend's text size (#2581). ElementKind::Legend { title, frame, text_size, .. } => { let ElementKind::MapFrame { map, .. } = &layout.element(*frame)?.kind else { return None }; map_index(maps, map)?; let size = LEGEND_TITLE_PT * legend_size(*text_size); - (title.clone(), size, text::Face { bold: true, ..Default::default() }, TextAlign::Left, 0.0, 0.0, true, false, None) + ( + title.clone(), + size, + text::Face { bold: true, ..Default::default() }, + TextAlign::Left, + 0.0, + 0.0, + true, + false, + None, + (TextVAlign::Top, 1.0), + ) } // A colorbar's title in the lines it is drawn in (#2493), when it draws one: its // frame's map has a raster with a colour scale (else it draws a placeholder). @@ -419,13 +459,31 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option return None; } let s = lines.join("\n"); - (s, COLORBAR_TITLE_PT as f32, colorbar_title_style().face, TextAlign::Left, 0.0, 0.0, false, true, Some(fits)) + ( + s, + COLORBAR_TITLE_PT as f32, + colorbar_title_style().face, + TextAlign::Left, + 0.0, + 0.0, + false, + true, + Some(fits), + (TextVAlign::Top, 1.0), + ) } _ => return None, }; let px = size.clamp(2.0, 400.0) * 1.33 * ppp; // A legend's title sits in the middle of its first row, which grows with its size. - let mut cy = r.y() + if title { LEGEND_ROW * (size / LEGEND_TITLE_PT) * ppp / 2.0 } else { px * 0.6 }; + // A text's first line, where its block alignment puts it ([`block_shift`]). + let mut cy = if title { + r.y() + LEGEND_ROW * (size / LEGEND_TITLE_PT) * ppp / 2.0 + } else { + let n = s.lines().take(200).count(); + let shift = block_shift(block.0, f64::from(r.height()), f64::from(px), n, f64::from(block.1)) as f32; + r.y() + shift + px * 0.6 + }; let turn = Transform::from_rotate_at(rotation, r.x() + r.width() / 2.0, r.y() + r.height() / 2.0); // Legend titles are drawn on one line, unlike text elements' explicit line breaks. let lines = std::iter::once(s.as_str()).filter(|_| title).chain(s.lines().filter(|_| !title)); @@ -464,7 +522,7 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option turn.map_points(&mut corners); corners.iter().any(|p| p.x < 0.0 || p.y < 0.0 || p.x > w as f32 || p.y > h as f32) }); - cy += px * 1.25; + cy += px * 1.25 * block.1; } // A wrapped text ends at the line past the 200 drawn ([`wrapped`]): it may go on. let at_least = broken && s.lines().nth(200).is_some(); @@ -899,11 +957,29 @@ fn draw_page( None => placeholder(&mut pm, r, "Colorbar", ppp), } } - ElementKind::Text { text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap, .. } => { + ElementKind::Text { + text: t, + size, + color, + bold, + italic, + align, + letter_spacing, + font, + font_name, + rotation, + wrap, + valign, + line_spacing, + case, + .. + } => { let first = layout.first_frame().and_then(frame); + let style = + text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing).with_block(*valign, *line_spacing); + // Its tokens filled in, then its case, then its wrap ([`drawn_text`]). let s = expand(t, layout, info, first.and_then(|f| maps.get(f.1).map(|m| (m, f.2)))); - let style = text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing); - let s = if *wrap { wrapped(&s, e.w, *size, style) } else { s }; + let s = drawn_text(s, *case, *wrap, e.w, *size, style); if *rotation == 0.0 { text_block(&mut pm, r, &s, *size as f32, *color, style, ppp); } else if let Some(area) = text_area(r, &s, *size as f32, style, ppp) { @@ -4391,6 +4467,32 @@ pub(crate) struct TextStyle { pub(crate) align: TextAlign, /// Letter spacing in points. pub(crate) spacing: f32, + /// Where its block of lines sits down its box ([`block_shift`]). + pub(crate) valign: TextVAlign, + /// The distance between its lines, a multiple of the usual (0.5 to 3). + pub(crate) line_spacing: f32, +} + +impl TextStyle { + /// This style with a text's block alignment and line spacing, clamped where they are used: an + /// unknown alignment is the top, a line spacing not a number the usual one, and one outside + /// 0.5..=3 the nearer limit. + pub(crate) fn with_block(self, valign: TextVAlign, line_spacing: f64) -> TextStyle { + // An infinity clamps to the nearer limit; only NaN has none. + let ls = if line_spacing.is_nan() { + rustgis_map::layout::LINE_SPACING + } else { + line_spacing.clamp(rustgis_map::layout::MIN_LINE_SPACING, rustgis_map::layout::MAX_LINE_SPACING) + }; + TextStyle { valign: valign.kept(), line_spacing: ls as f32, ..self } + } + + /// Its line spacing, clamped again where it is used: in 0.5..=3, the usual one when it is not + /// a number. Exactly 1 for the usual spacing, so a plain text is placed as it always was. + fn line_spacing_kept(self) -> f32 { + let (lo, hi) = (rustgis_map::layout::MIN_LINE_SPACING as f32, rustgis_map::layout::MAX_LINE_SPACING as f32); + if self.line_spacing.is_nan() { 1.0 } else { self.line_spacing.clamp(lo, hi) } + } } /// A text element's style: its face in an installed family by name (#762), else its generic one. @@ -4407,7 +4509,7 @@ pub(crate) fn text_style( ) -> TextStyle { let family = font_name.and_then(crate::families::find_ready); let face = text::Face { bold, italic, serif: font == rustgis_map::layout::FontFamily::Serif, family }; - TextStyle { face, align, spacing: letter_spacing as f32 } + TextStyle { face, align, spacing: letter_spacing as f32, valign: TextVAlign::Top, line_spacing: 1.0 } } /// Pixels per millimetre a wrapped text's lines are measured at (300 dpi), whatever the @@ -4431,12 +4533,50 @@ pub(crate) fn wrapped(s: &str, width: f64, size: f64, style: TextStyle) -> Strin crate::report::wrap_lines(s, width * WRAP_PX_PER_MM, measure, 200).join("\n") } +/// A text element's lines as they are drawn, from its text with its tokens filled in ([`expand`]): +/// in its case, then, when it wraps, broken to its box `width_mm` wide ([`wrapped`]), so an upper +/// case text breaks at its own, wider, width. One for the page, its cut-off check and the SVG, so +/// they draw and count the same lines. Those that don't fit its box are left out from the bottom +/// whatever its block alignment: a block taller than its box starts at its top ([`block_shift`]). +pub(crate) fn drawn_text(expanded: String, case: TextCase, wrap: bool, width_mm: f64, size: f64, style: TextStyle) -> String { + let s = case.kept().apply(expanded); + if wrap { wrapped(&s, width_mm, size, style) } else { s } +} + +/// How far down its box of `box_h` pixels a text's block of `lines` lines at `px` pixels, spaced +/// `line_spacing` times the usual, starts: 0 at the top; half the room it leaves in the middle; +/// all of it at the bottom, its last line's pitch ending on the box's bottom edge. A block taller +/// than its box (or with no line) starts at its top whatever its alignment, so its first lines are +/// the ones kept and none is drawn above the box. +pub(crate) fn block_shift(valign: TextVAlign, box_h: f64, px: f64, lines: usize, line_spacing: f64) -> f64 { + if lines == 0 || valign.kept() == TextVAlign::Top { + return 0.0; + } + let block = px * 1.25 * (1.0 + (lines - 1) as f64 * line_spacing); + let free = box_h - block; + // A measure not a number, or past any page, is no room. + if !free.is_finite() || free <= 0.0 { + return 0.0; + } + match valign.kept() { + TextVAlign::Middle => free / 2.0, + TextVAlign::Bottom => free, + _ => 0.0, + } +} + /// A colorbar's title's size in points; it is drawn bold. pub const COLORBAR_TITLE_PT: f64 = 9.0; /// A colorbar's title's style, as [`colorbar_title_lines`] measures it: bold, from the left edge. fn colorbar_title_style() -> TextStyle { - TextStyle { face: text::Face { bold: true, ..Default::default() }, align: TextAlign::Left, spacing: 0.0 } + TextStyle { + face: text::Face { bold: true, ..Default::default() }, + align: TextAlign::Left, + spacing: 0.0, + valign: TextVAlign::Top, + line_spacing: 1.0, + } } /// A colorbar's title's width in mm, its widest line, measured as [`colorbar_title_lines`] breaks @@ -4509,7 +4649,11 @@ fn text_area(r: Rect, s: &str, size: f32, style: TextStyle, ppp: f64) -> Option< }; (x0, x1, lines) = (x0.min(a), x1.max(b), lines + 1); } - let down = (r.height() + px).min(f32::from(lines) * px * 1.25); + // Down to its last line, where its block alignment and line spacing put it. + let shift = + block_shift(style.valign, f64::from(r.height()), f64::from(px), usize::from(lines), f64::from(style.line_spacing_kept())) as f32; + let block = (1.0 + (f32::from(lines) - 1.0) * style.line_spacing_kept()) * px * 1.25; + let down = (r.height() + px).min(shift + block); (lines > 0).then(|| Rect::from_ltrb(x0 - px, -px, x1 + px, down + px)).flatten() } @@ -4555,14 +4699,19 @@ fn draw_turned_box(pm: &mut Canvas, r: Rect, degrees: f32, area: Rect, draw: imp pm.draw_pixmap(0, 0, pic.pixmap().as_ref(), &paint, place, None); } -/// Text in an element: lines split at `\n` from the top, each placed by the style's alignment. A -/// centred or right-aligned line wider than the element runs out past its left edge, as a -/// left-aligned one runs past its right. +/// Text in an element: lines split at `\n`, the block of them at the top, middle or bottom of the +/// box ([`block_shift`]) and spaced by the style's line spacing, each placed by the style's +/// alignment. A block taller than its box starts at its top whatever its alignment, so its first +/// lines are drawn and the ones past the box left out ([`text_losses`] counts them). A centred or +/// right-aligned line wider than the element runs out past its left edge, as a left-aligned one +/// runs past its right. fn text_block(pm: &mut Canvas, r: Rect, s: &str, size: f32, color: Rgba, style: TextStyle, ppp: f64) { let px = size.clamp(2.0, 400.0) * 1.33 * ppp as f32; // Letter spacing is in points, as the size is. let spacing = style.spacing * 1.33 * ppp as f32; - let mut y = r.y() + px * 0.6; + let n = s.lines().take(200).count(); + let shift = block_shift(style.valign, f64::from(r.height()), f64::from(px), n, f64::from(style.line_spacing_kept())) as f32; + let mut y = r.y() + shift + px * 0.6; for line in s.lines().take(200) { if y > r.y() + r.height() + px { break; @@ -4579,7 +4728,7 @@ fn text_block(pm: &mut Canvas, r: Rect, s: &str, size: f32, color: Rgba, style: } }; text::styled_at(pm, line, left, y, px, color, style.face, spacing); - y += px * 1.25; + y += px * 1.25 * style.line_spacing_kept(); } } @@ -7869,7 +8018,8 @@ mod tests { /// an image export and a print break a text alike. #[test] fn a_wrapped_text_breaks_alike_at_every_resolution() { - let style = TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0 }; + let style = + TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, line_spacing: 1.0 }; let lines = wrapped(NOTE, 40.0, 12.0, style); assert!(lines.lines().count() > 3, "{lines}"); assert!(lines.lines().all(|l| !l.starts_with(' ') && !l.ends_with(' ')), "{lines:?}"); @@ -7929,7 +8079,8 @@ mod tests { #[test] fn a_turned_texts_picture_covers_its_lines() { let r = Rect::from_xywh(0.0, 0.0, 2000.0, 1000.0).unwrap(); - let plain = TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0 }; + let plain = + TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, line_spacing: 1.0 }; let px = 14.0 * 1.33; let area = |align| text_area(r, "Fonte: IBGE", 14.0, TextStyle { align, ..plain }, 1.0).unwrap(); let left = area(TextAlign::Left); @@ -8004,7 +8155,8 @@ Elaboração: RustGIS", /// as before. #[test] fn text_takes_italic_alignment_and_letter_spacing() { - let plain = TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0 }; + let plain = + TextStyle { face: text::Face::default(), align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, line_spacing: 1.0 }; let base = styled_line(plain); let (l, r, ..) = text_ink(&base); assert!(l < 4, "left-aligned starts at the left: {l}"); @@ -8064,6 +8216,178 @@ Elaboração: RustGIS", assert!(r <= 300 && l < r, "inked {l}..{r}"); } + /// A 100 × 100 mm page with `text` at 12 pt in black in (10, 10, 40, `h`) mm, its kind changed + /// by `f`. + fn block_page(text: &str, h: f64, f: &dyn Fn(&mut ElementKind)) -> Layout { + let mut l = Layout::new("L", 100.0, 100.0); + let mut kind = ElementKind::text(text, 12.0, Rgba::rgb(0, 0, 0), false); + f(&mut kind); + l.add("Block", (10.0, 10.0, 40.0, h), kind); + l + } + + /// Sets a text's block alignment, line spacing and case. + fn set_block(k: &mut ElementKind, v: TextVAlign, ls: f64, c: TextCase) { + if let ElementKind::Text { valign, line_spacing, case, .. } = k { + (*valign, *line_spacing, *case) = (v, ls, c); + } + } + + /// The rows with a dark pixel, from the top. + fn ink_rows(pm: &Pixmap) -> Vec { + (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| rgb(pm, x, y).0 < 128)).collect() + } + + /// How many pixels are dark. + fn dark_count(pm: &Pixmap) -> usize { + (0..pm.height()).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).filter(|&(x, y)| rgb(pm, x, y).0 < 128).count() + } + + /// A text's block sits at the top of its box, as texts always have, in its middle, or with its + /// last line on its bottom edge; the block itself is the same, moved. + #[test] + fn a_text_block_sits_at_the_top_middle_or_bottom_of_its_box() { + let draw = |v: TextVAlign| { + render(&block_page("one\ntwo\nthree", 60.0, &|k| set_block(k, v, 1.0, TextCase::None)), &mut [], 96.0, &PageInfo::default()) + .unwrap() + }; + let (top, mid, bottom) = + (ink_rows(&draw(TextVAlign::Top)), ink_rows(&draw(TextVAlign::Middle)), ink_rows(&draw(TextVAlign::Bottom))); + let plain = ink_rows(&render(&block_page("one\ntwo\nthree", 60.0, &|_| {}), &mut [], 96.0, &PageInfo::default()).unwrap()); + assert_eq!(top, plain, "top is today's drawing"); + let span = |r: &[u32]| r[r.len() - 1] - r[0]; + assert_eq!((span(&mid), span(&bottom)), (span(&top), span(&top)), "the same block, moved"); + let (box_top, box_bottom) = ((10.0 * 96.0 / 25.4) as u32, (70.0 * 96.0 / 25.4) as u32); + assert!(box_bottom - bottom[bottom.len() - 1] <= 12, "bottom: last ink row {} of the box's {box_bottom}", bottom[bottom.len() - 1]); + let (above, below) = (mid[0] - box_top, box_bottom - mid[mid.len() - 1]); + assert!(above.abs_diff(below) <= 8, "middle: {above} above, {below} below"); + } + + /// Line spacing multiplies the distance between lines: twice as far apart at 2, half at 0.5. + #[test] + fn line_spacing_spreads_the_lines_by_its_multiple() { + let span = |ls: f64| { + let pm = render( + &block_page("one\ntwo\nthree", 60.0, &|k| set_block(k, TextVAlign::Top, ls, TextCase::None)), + &mut [], + 96.0, + &PageInfo::default(), + ) + .unwrap(); + let r = ink_rows(&pm); + (r[r.len() - 1] - r[0]) as f64 + }; + // The usual pitch in pixels at 96 dpi, a layout point a pixel there. + let pitch = 12.0 * 1.33 * 1.25; + assert!(((span(2.0) - span(1.0)) - 2.0 * pitch).abs() <= 2.0, "{} {}", span(2.0), span(1.0)); + assert!(((span(1.0) - span(0.5)) - pitch).abs() <= 2.0, "{} {}", span(1.0), span(0.5)); + } + + /// A block taller than its box is drawn from the top whatever its alignment: its first lines + /// are kept, the same lines left out and said, and none is drawn above the box. + #[test] + fn a_block_taller_than_its_box_keeps_its_first_lines_whatever_its_valign() { + let info = PageInfo::default(); + let page = |v| block_page("one\ntwo\nthree\nfour\nfive", 7.0, &|k| set_block(k, v, 1.0, TextCase::None)); + let top = page(TextVAlign::Top); + let loss = text_losses(&top, &[], 96.0, &info); + assert_eq!(loss.iter().map(|l| l.left_out).collect::>(), [3]); + for v in [TextVAlign::Middle, TextVAlign::Bottom] { + let l = page(v); + assert_eq!(render(&l, &mut [], 96.0, &info).unwrap().data(), render(&top, &mut [], 96.0, &info).unwrap().data(), "{v:?}"); + assert_eq!(text_losses(&l, &[], 96.0, &info), loss, "{v:?}"); + assert_eq!(lines_left_out_notice(&text_losses(&l, &[], 96.0, &info)[0]), lines_left_out_notice(&loss[0])); + } + } + + /// The cut-off check steps by the spaced pitch, as the page draws: a wider spacing leaves lines + /// out of a box that held them, a tighter one draws lines a box cut. + #[test] + fn line_spacing_changes_the_lines_left_out() { + let info = PageInfo::default(); + let left_out = |h: f64, ls: f64| { + let l = block_page("one\ntwo\nthree\nfour\nfive", h, &|k| set_block(k, TextVAlign::Top, ls, TextCase::None)); + text_losses(&l, &[], 96.0, &info).first().map_or(0, |l| l.left_out) + }; + assert_eq!((left_out(25.0, 1.0), left_out(25.0, 2.0)), (0, 2)); + assert_eq!((left_out(12.0, 1.0), left_out(12.0, 0.5)), (2, 0)); + } + + /// Case applies once the tokens are filled in, and before the wrap, which breaks the wider + /// words. + #[test] + fn case_applies_after_the_tokens_and_before_the_wrap() { + let info = PageInfo { page: 2, pages: 3, page_name: String::new() }; + let draw = |t: &str, c| render(&block_page(t, 20.0, &|k| set_block(k, TextVAlign::Top, 1.0, c)), &mut [], 96.0, &info).unwrap(); + assert_eq!(draw("Page {page} of {pages}", TextCase::Upper).data(), draw("PAGE 2 OF 3", TextCase::None).data()); + assert_eq!(draw("PAGE {page} OF {pages}", TextCase::Lower).data(), draw("page 2 of 3", TextCase::None).data()); + let style = text_style(false, false, rustgis_map::layout::FontFamily::Sans, None, TextAlign::Left, 0.0); + let s = "boundaries simplified for print from the census".to_string(); + let lines = |c| drawn_text(s.clone(), c, true, 40.0, 12.0, style).lines().count(); + assert!(lines(TextCase::Upper) > lines(TextCase::Lower), "{} {}", lines(TextCase::Upper), lines(TextCase::Lower)); + assert_eq!(drawn_text(s.clone(), TextCase::None, false, 40.0, 12.0, style), s, "unwrapped and as typed: unchanged"); + } + + /// A turned text's picture covers its lines where its block alignment and spacing put them. + #[test] + fn a_turned_bottom_aligned_text_is_drawn_whole() { + let info = PageInfo::default(); + let ink = |v, ls| { + let pm = render( + &block_page("one\ntwo\nthree", 60.0, &|k| { + set_block(k, v, ls, TextCase::None); + if let ElementKind::Text { rotation, .. } = k { + *rotation = 90.0; + } + }), + &mut [], + 96.0, + &info, + ) + .unwrap(); + (dark_count(&pm), ink_bounds(&pm)) + }; + let (top, moved) = (ink(TextVAlign::Top, 1.0), ink(TextVAlign::Bottom, 1.5)); + // Within a tenth: a 12 pt text of some 290 dark pixels shifted by part of a pixel shades + // its edges differently (3 % here); a line of it left out is far more. + assert!(top.0.abs_diff(moved.0) * 10 <= top.0, "every letter drawn: {} and {}", top.0, moved.0); + assert_ne!(top.1, moved.1, "the block moved"); + } + + /// A block alignment or line spacing that reaches the page unrepaired is clamped where it is + /// used: an unknown alignment draws at the top, a spacing not a number at the usual one, one + /// out of range at the nearer limit; none moves a line to a place not a number. + #[test] + fn hostile_text_block_settings_draw_clamped() { + let style = text_style(false, false, rustgis_map::layout::FontFamily::Sans, None, TextAlign::Left, 0.0); + let kept = |v, ls: f64| { + let s = style.with_block(v, ls); + (s.valign, s.line_spacing) + }; + assert_eq!(kept(TextVAlign::Invalid, f64::NAN), (TextVAlign::Top, 1.0)); + assert_eq!(kept(TextVAlign::Bottom, 9.0), (TextVAlign::Bottom, 3.0)); + assert_eq!(kept(TextVAlign::Middle, f64::INFINITY), (TextVAlign::Middle, 3.0)); + assert_eq!(kept(TextVAlign::Middle, f64::NEG_INFINITY), (TextVAlign::Middle, 0.5)); + assert_eq!(kept(TextVAlign::Top, 0.1), (TextVAlign::Top, 0.5)); + for (v, box_h, px, ls) in [ + (TextVAlign::Bottom, f64::NAN, 10.0, 1.0), + (TextVAlign::Middle, 100.0, f64::NAN, 1.0), + (TextVAlign::Bottom, 100.0, 10.0, f64::NAN), + (TextVAlign::Bottom, f64::INFINITY, 10.0, 1.0), + (TextVAlign::Invalid, 100.0, 10.0, 1.0), + ] { + assert_eq!(block_shift(v, box_h, px, 3, ls), 0.0, "{v:?} {box_h} {px} {ls}"); + } + assert_eq!(block_shift(TextVAlign::Bottom, 100.0, 10.0, 0, 1.0), 0.0, "no line"); + let info = PageInfo::default(); + let draw = + |v, ls| render(&block_page("one\ntwo", 60.0, &|k| set_block(k, v, ls, TextCase::Invalid)), &mut [], 96.0, &info).unwrap(); + assert_eq!(draw(TextVAlign::Invalid, f64::NAN).data(), draw(TextVAlign::Top, 1.0).data()); + assert_eq!(draw(TextVAlign::Bottom, 1e300).data(), draw(TextVAlign::Bottom, 3.0).data()); + let l = block_page("one\ntwo", 60.0, &|k| set_block(k, TextVAlign::Bottom, f64::NAN, TextCase::Invalid)); + assert!(text_losses(&l, &[], 96.0, &info).is_empty()); + } + /// The extent indicator is drawn in its own colour and width (#213): red and 2 pt until set. #[test] fn extent_indicators_take_their_colour_and_width() { diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index ad63d42987..50c23b0437 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -660,7 +660,13 @@ mod tests { }; let plain = svg(false); assert!(!plain.contains(" 3, "{lines}"); From 55c3aca859b503b1f4a7a4ed5c725a6b6dd8ae7c Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:11:53 -0600 Subject: [PATCH 04/23] test(render): pin where a layout text's block and case are reported off the page Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout.rs | 102 ++++++++++++++++++++++++++++-------- 1 file changed, 80 insertions(+), 22 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index c0b1f7b179..f6d2fab90f 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -4478,20 +4478,24 @@ impl TextStyle { /// unknown alignment is the top, a line spacing not a number the usual one, and one outside /// 0.5..=3 the nearer limit. pub(crate) fn with_block(self, valign: TextVAlign, line_spacing: f64) -> TextStyle { - // An infinity clamps to the nearer limit; only NaN has none. - let ls = if line_spacing.is_nan() { - rustgis_map::layout::LINE_SPACING - } else { - line_spacing.clamp(rustgis_map::layout::MIN_LINE_SPACING, rustgis_map::layout::MAX_LINE_SPACING) - }; - TextStyle { valign: valign.kept(), line_spacing: ls as f32, ..self } + TextStyle { valign: valign.kept(), line_spacing: kept_line_spacing(line_spacing) as f32, ..self } } - /// Its line spacing, clamped again where it is used: in 0.5..=3, the usual one when it is not - /// a number. Exactly 1 for the usual spacing, so a plain text is placed as it always was. + /// Its line spacing, clamped again where it is used ([`kept_line_spacing`]). Exactly 1 for the + /// usual spacing (an `f32` goes to `f64` and back unchanged), so a plain text is placed as it + /// always was. fn line_spacing_kept(self) -> f32 { - let (lo, hi) = (rustgis_map::layout::MIN_LINE_SPACING as f32, rustgis_map::layout::MAX_LINE_SPACING as f32); - if self.line_spacing.is_nan() { 1.0 } else { self.line_spacing.clamp(lo, hi) } + kept_line_spacing(f64::from(self.line_spacing)) as f32 + } +} + +/// A line spacing as it is drawn: the usual one when it is not a number, else clamped to 0.5..=3 +/// (an infinity to the nearer limit). +fn kept_line_spacing(ls: f64) -> f64 { + if ls.is_nan() { + rustgis_map::layout::LINE_SPACING + } else { + ls.clamp(rustgis_map::layout::MIN_LINE_SPACING, rustgis_map::layout::MAX_LINE_SPACING) } } @@ -4625,7 +4629,8 @@ fn colorbar_bar_room(ppp: f32, orientation: Orientation) -> f32 { } } -/// The distance between two lines of text at `size` points, in mm, as [`text_block`] sets them. +/// The distance between two lines of text at `size` points, in mm, at the usual line spacing (1), +/// as [`text_block`] sets them there; a text's line spacing multiplies it. pub fn line_pitch_mm(size: f64) -> f64 { size.clamp(2.0, 400.0) * 1.33 * 1.25 * 25.4 / 96.0 } @@ -8238,9 +8243,10 @@ Elaboração: RustGIS", (0..pm.height()).filter(|&y| (0..pm.width()).any(|x| rgb(pm, x, y).0 < 128)).collect() } - /// How many pixels are dark. - fn dark_count(pm: &Pixmap) -> usize { - (0..pm.height()).flat_map(|y| (0..pm.width()).map(move |x| (x, y))).filter(|&(x, y)| rgb(pm, x, y).0 < 128).count() + /// How many separate runs of columns with a dark pixel there are, from the left. + fn ink_column_runs(pm: &Pixmap) -> usize { + let inked: Vec = (0..pm.width()).map(|x| (0..pm.height()).any(|y| rgb(pm, x, y).0 < 128)).collect(); + inked.windows(2).filter(|w| !w[0] && w[1]).count() + usize::from(inked.first() == Some(&true)) } /// A text's block sits at the top of its box, as texts always have, in its middle, or with its @@ -8256,7 +8262,10 @@ Elaboração: RustGIS", let plain = ink_rows(&render(&block_page("one\ntwo\nthree", 60.0, &|_| {}), &mut [], 96.0, &PageInfo::default()).unwrap()); assert_eq!(top, plain, "top is today's drawing"); let span = |r: &[u32]| r[r.len() - 1] - r[0]; - assert_eq!((span(&mid), span(&bottom)), (span(&top), span(&top)), "the same block, moved"); + // Moved by part of a pixel, its edge rows may shade past the threshold one row more or less. + for moved in [&mid, &bottom] { + assert!(span(moved).abs_diff(span(&top)) <= 1, "the same block, moved: {} and {}", span(moved), span(&top)); + } let (box_top, box_bottom) = ((10.0 * 96.0 / 25.4) as u32, (70.0 * 96.0 / 25.4) as u32); assert!(box_bottom - bottom[bottom.len() - 1] <= 12, "bottom: last ink row {} of the box's {box_bottom}", bottom[bottom.len() - 1]); let (above, below) = (mid[0] - box_top, box_bottom - mid[mid.len() - 1]); @@ -8345,13 +8354,62 @@ Elaboração: RustGIS", &info, ) .unwrap(); - (dark_count(&pm), ink_bounds(&pm)) + (ink_bounds(&pm), ink_column_runs(&pm)) }; - let (top, moved) = (ink(TextVAlign::Top, 1.0), ink(TextVAlign::Bottom, 1.5)); - // Within a tenth: a 12 pt text of some 290 dark pixels shifted by part of a pixel shades - // its edges differently (3 % here); a line of it left out is far more. - assert!(top.0.abs_diff(moved.0) * 10 <= top.0, "every letter drawn: {} and {}", top.0, moved.0); - assert_ne!(top.1, moved.1, "the block moved"); + // Spaced alike, so only the alignment differs. Turned a quarter clockwise, the box's + // down runs leftwards across the page: its lines are runs of inked columns. + let ((tl, tt, tr, tb), top_runs) = ink(TextVAlign::Top, 1.5); + let ((bl, bt, br, bb), bottom_runs) = ink(TextVAlign::Bottom, 1.5); + assert_eq!((top_runs, bottom_runs), (3, 3), "a run of columns a line, all three drawn"); + assert!((tr - tl).abs_diff(br - bl) <= 2, "the same block across: {tl}..{tr} and {bl}..{br}"); + assert!((tb - tt).abs_diff(bb - bt) <= 2, "the same lines along: {tt}..{tb} and {bt}..{bb}"); + // Moved left by the room the block leaves: the box's 60 mm less three lines at 1.5, + // 12 pt × 1.33 × 1.25 × (1 + 2 × 1.5) = 79.8 px, of 226.8 px: 147.0 px. + let free = 60.0 * 96.0 / 25.4 - 12.0 * 1.33 * 1.25 * (1.0 + 2.0 * 1.5); + for (t, b) in [(tl, bl), (tr, br)] { + assert!((f64::from(t) - f64::from(b) - free).abs() <= 2.0, "moved {} px of {free:.1}", f64::from(t) - f64::from(b)); + } + } + + /// Where a text's block and case put its ink decides whether it runs off the page: a box + /// hanging past the page's bottom, its one line at the box's top, middle or bottom; and a line + /// near the page's right edge in upper case, its letters wider. + #[test] + fn a_text_block_and_case_are_said_off_the_page_where_they_put_the_ink() { + let info = PageInfo::default(); + // The 100 mm page is 378.0 px tall at 96 dpi; the box (10, 80, 40, 30) mm runs from 302.4 + // to 415.7 px. Its one line of 12 pt (15.96 px a line, a pitch of 19.95) has its middle + // 9.6 px under where the block starts, the block 19.95 px tall in a box of 113.4: at the + // top at 312.0 px, in the middle 46.7 px lower at 358.7, at the bottom 93.4 px lower at + // 405.4, below the page's 378.0 whatever the font's letters (some 8 px each way). + let hanging = |v| { + let mut l = Layout::new("L", 100.0, 100.0); + let mut kind = ElementKind::text("one", 12.0, Rgba::rgb(0, 0, 0), false); + set_block(&mut kind, v, 1.0, TextCase::None); + l.add("Hanging", (10.0, 80.0, 40.0, 30.0), kind); + text_losses(&l, &[], 96.0, &info) + }; + assert_eq!(hanging(TextVAlign::Top), [], "at the top, on the page"); + assert_eq!(hanging(TextVAlign::Middle), [], "in the middle, still on the page"); + let bottom = hanging(TextVAlign::Bottom); + assert!(bottom.len() == 1 && bottom[0].off_page && bottom[0].left_out == 0, "{bottom:?}"); + assert!(off_page_notice(&bottom[0]).is_some()); + // The page is 378.0 px wide; the box starts at 83 mm, 313.7 px, 64.3 px from its edge. + // Ten letters `lflflflflf` of 12 pt (an em of 15.96 px) take some 0.25 em each as typed, + // about 40 px, and some 0.58 em in upper case (`LFLFLFLFLF`), about 93 px: on the page as + // typed with room for 1.6 times as wide letters, past its edge in upper case at 0.69 times + // as wide ones. + let near_edge = |c| { + let mut l = Layout::new("L", 100.0, 100.0); + let mut kind = ElementKind::text("lflflflflf", 12.0, Rgba::rgb(0, 0, 0), false); + set_block(&mut kind, TextVAlign::Top, 1.0, c); + l.add("Edge", (83.0, 50.0, 10.0, 10.0), kind); + text_losses(&l, &[], 96.0, &info) + }; + assert_eq!(near_edge(TextCase::None), [], "as typed, on the page"); + let upper = near_edge(TextCase::Upper); + assert!(upper.len() == 1 && upper[0].off_page && upper[0].left_out == 0, "{upper:?}"); + assert!(off_page_notice(&upper[0]).is_some()); } /// A block alignment or line spacing that reaches the page unrepaired is clamped where it is From 40081ce78f9f822abaffbaacba2c4a0ae38e013d Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:23:03 -0600 Subject: [PATCH 05/23] feat(render): a layout text's block, line spacing and case in SVG, as the page draws them Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout.rs | 2 +- crates/render/src/svg.rs | 104 +++++++++++++++++++++++++++++++----- 2 files changed, 92 insertions(+), 14 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index f6d2fab90f..84ca1ddef0 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -4484,7 +4484,7 @@ impl TextStyle { /// Its line spacing, clamped again where it is used ([`kept_line_spacing`]). Exactly 1 for the /// usual spacing (an `f32` goes to `f64` and back unchanged), so a plain text is placed as it /// always was. - fn line_spacing_kept(self) -> f32 { + pub(crate) fn line_spacing_kept(self) -> f32 { kept_line_spacing(f64::from(self.line_spacing)) as f32 } } diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 50c23b0437..8c4212de51 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -95,7 +95,22 @@ fn elements( background(&mut s, e); let (x, y, w, h) = (e.x, e.y, e.w, e.h); match &e.kind { - ElementKind::Text { text: t, size, color, bold, italic, align, letter_spacing, font, font_name, rotation, wrap, .. } => { + ElementKind::Text { + text: t, + size, + color, + bold, + italic, + align, + letter_spacing, + font, + font_name, + rotation, + wrap, + valign, + line_spacing, + case, + } => { let first = layout.first_frame().and_then(|id| layout.element(id)).and_then(|f| match &f.kind { ElementKind::MapFrame { map, center, scale, bearing, pitch, .. } => { let m = maps.iter().find(|m| m.name.eq_ignore_ascii_case(map))?; @@ -103,17 +118,19 @@ fn elements( } _ => None, }); - let text = expand(t, layout, info, first); - // A wrapped text in the lines the page breaks it into (#2346), each its own line. - let text = if *wrap { - let style = crate::layout::text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing); - crate::layout::wrapped(&text, w, *size, style) - } else { - text - }; - // As the page draws it: the size in points, lines 1.25 apart, the first baseline - // 0.6 of the size below the top, lines past the frame left out. + let style = crate::layout::text_style(*bold, *italic, *font, font_name.as_deref(), *align, *letter_spacing) + .with_block(*valign, *line_spacing); + // Its tokens filled in, then its case, then, wrapped, the lines the page breaks it + // into (#2346), each its own line ([`crate::layout::drawn_text`]). + let text = crate::layout::drawn_text(expand(t, layout, info, first), *case, *wrap, w, *size, style); + // As the page draws it: the size in points, the block at the top, middle or bottom + // of the box (from the top when taller than it), lines 1.25 em times the line + // spacing apart, the first baseline 0.6 of the size below the block's top, lines + // past the frame left out. let em = size.clamp(2.0, 400.0) * 1.33 / PT_PER_MM; + let ls = f64::from(style.line_spacing_kept()); + let n = text.lines().take(200).count(); + let top = y + crate::layout::block_shift(style.valign, h, em, n, ls); let (anchor, tx) = match align { TextAlign::Left => ("start", x), TextAlign::Center => ("middle", x + w / 2.0), @@ -123,7 +140,7 @@ fn elements( .lines() .take(200) .enumerate() - .map(|(i, l)| (y + em * (0.6 + 1.25 * i as f64), l)) + .map(|(i, l)| (top + em * (0.6 + 1.25 * ls * i as f64), l)) .take_while(|(ly, _)| *ly <= y + h + em) .collect(); // A named family first (#762), quoted as CSS has it (its own backslashes and @@ -137,7 +154,7 @@ fn elements( s, r#" Vec<(f64, String)> { + svg.split("').nth(1)?.split('<').next()?.to_string())) + }) + .collect() + }; + let got = spans(&page("one\ntwo\nthree", 60.0, TextVAlign::Bottom, 1.5, TextCase::Upper)); + assert_eq!(got.iter().map(|s| s.1.as_str()).collect::>(), ["ONE", "TWO", "THREE"]); + let em = 10.0 * 1.33 / PT_PER_MM; + assert!(((got[1].0 - got[0].0) - em * 1.25 * 1.5).abs() < 0.01, "{got:?}"); + assert!((got[2].0 - (70.0 - em * 1.25 + em * 0.6)).abs() < 0.01, "the last on the bottom: {got:?}"); + let tall = "one\ntwo\nthree\nfour\nfive"; + let from_top = spans(&page(tall, 9.0, TextVAlign::Top, 1.0, TextCase::None)); + assert!(!from_top.is_empty(), "two lines fit"); + assert_eq!(spans(&page(tall, 9.0, TextVAlign::Bottom, 1.0, TextCase::None)), from_top, "taller than its box: from the top"); + } + + /// The vector PDF records the block as the page draws it: a block's PDF differs from the plain + /// text's, and the plain one is still main's (`plain_texts_export_as_before`). + #[test] + fn a_text_block_reaches_the_pdf() { + use rustgis_map::layout::{TextCase, TextVAlign}; + let pdf = |v: TextVAlign, ls: f64, c: TextCase| { + let mut l = Layout::new("PDF", 100.0, 80.0); + let mut kind = ElementKind::text("one\ntwo\nthree", 10.0, rustgis_map::Rgba::rgb(0, 0, 0), false); + if let ElementKind::Text { valign, line_spacing, case, .. } = &mut kind { + (*valign, *line_spacing, *case) = (v, ls, c); + } + l.add("Text", (30.0, 10.0, 30.0, 60.0), kind); + let (drawing, _) = crate::layout::render_drawing(&l, &mut [], 150.0, &PageInfo::default()).unwrap(); + crate::pdf::write(&[crate::pdf::Page::drawing(drawing, l.width, l.height)], "Block") + }; + let plain = pdf(TextVAlign::Top, 1.0, TextCase::None); + let block = pdf(TextVAlign::Bottom, 1.5, TextCase::Upper); + assert!(plain.starts_with(b"%PDF") && block.starts_with(b"%PDF"), "both write"); + assert_ne!(plain, block, "the block's case, shift and spacing reach the PDF"); + // Each setting alone changes what is recorded. + for (v, ls, c) in + [(TextVAlign::Bottom, 1.0, TextCase::None), (TextVAlign::Top, 1.5, TextCase::None), (TextVAlign::Top, 1.0, TextCase::Upper)] + { + assert_ne!(pdf(v, ls, c), plain, "{v:?} {ls} {c:?}"); + } + } + /// An element's background (#2257) is a `` of its own under the element, its box grown /// by the padding, turned with a turned text; an element with none has none. #[test] From 928f9e2fce671730c17a3fbf40caabc42c997021 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:58:22 -0600 Subject: [PATCH 06/23] feat(layout): a text's block alignment, line spacing and case through layout.addElement and layout.update Bad values are refused before anything changes; other elements refuse the keys with one message; null leaves them as they are. A wider spacing or a case that leaves lines out or takes ink off the page is said at once. Projects, layout files and saved commands that use them require layout-text-block. Co-Authored-By: Claude Fable 5.2 --- crates/engine/command-surface.txt | 4 +- crates/engine/src/cmd/layout.rs | 101 +++++++++--- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 91 +++++++++++ crates/engine/src/tests.rs | 187 ++++++++++++++++++++++ crates/engine/src/tests/layout_files.rs | 28 ++++ docs/maintaining.md | 9 ++ schema/fixtures/layout_text_block.rgis | 1 + schema/project.schema.json | 2 + 9 files changed, 401 insertions(+), 23 deletions(-) create mode 100644 schema/fixtures/layout_text_block.rgis diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index d8fbdf0ba1..f6505d3e40 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -282,7 +282,7 @@ layer.transparency layer? value layer.visibility layer? visible? layer.zoomTo layer? layout.activate name layout -layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? font? fallback? title? allClasses? hideOther? showNoData? exclude? columns? textSize? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? +layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? columns? textSize? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background? layout.addFrame layout? shape? points? map? x? y? w? h? layout.arrange layout? element to layout.arrangement favourite? save? arrangement? remove? @@ -304,7 +304,7 @@ layout.save layout? path layout.series layout? layer nameField? frame? margin? off? layout.seriesPage layout? page layout.seriesRefresh layout? -layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? columns? textSize? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? background? +layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? columns? textSize? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? background? locator.find locator? text limit? zoom? map.activate name map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 174d680b93..32ad733158 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -10,10 +10,10 @@ use rustgis_map::layout::{ Arrange, ArrowStyle, Background, CHART_BAR, CHART_BARS, CHART_OUTLINE, ChartOrder, ChartOutline, CoordFormat, ElementKind, FontFamily, FrameShape, GRID_LABEL_PT, Grid, GridEdges, GridKind, GridStyle, Guides, LAYOUT_TEXT_SIZE, LINE_SPACING, Layout, LineDir, LineHead, MAX_CHART_BARS, MAX_CHART_DECIMALS, MAX_CHART_OUTLINE_WIDTH, MAX_COLORBAR_TICKS, 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_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, - ScaleLabelPosition, ScaleUnits, TextAlign, TextCase, TextVAlign, TickSide, UnitLabelPosition, fit_scale, line_angle, line_at_angle, - line_length, + MAX_LEGEND_LABEL_CHARS, MAX_LEGEND_LABELS, MAX_LINE_SPACING, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, + MAX_SCALE_SUBDIVISIONS, MAX_TICK_MM, MAX_UNIT_LABEL_CHARS, MIN_ELEMENT_MM, MIN_LINE_SPACING, MapSeries, Orientation, PAGES, + SCALE_BAR_TEXT_PT, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, TextAlign, TextCase, TextVAlign, 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}; @@ -118,10 +118,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; scaleBar: its labels, the room over the bar and between them following, the bar keeping its size; default 8; 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: a chart's values up to 2, the zeros they end in dropped; a scale bar's labels each the decimals it needs, as before)|0..6 (chart: its values' decimals)|0..3 (scaleBar: its labels' decimals, fixed, with the thousands set apart), "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), "mirror"?: bool (chart: drawn as its mirror image, its text reading as ever: bars running across from the right, their labels at the right, or columns hanging from the top, their labels over them; beside a chart drawn the usual way the two face each other; default false), "max"?: a number above 0|"auto" (chart: the value at the far end of its bars' room, so charts given the same one share a scale; a bar past it runs to that end, which a warning counts; default "auto", its bars' own), "hideLabels"?: bool (chart: its labels left out, their room given to the bars; default false), "barOutline"?: {"color"?: "#RRGGBB"|"#RRGGBBAA" (default #222222), "width"?: points, 0 to 5 (default 0.5; 0 for none)} (chart: a line round each bar, or each stretch of a stacked one; default none) (label, group, statistic, order, bars, other, stack, values, decimals, barColor, classes, labelAlign, mirror, max, hideLabels and barOutline refused for other kinds unless null, as showNoData is, a scaleBar's decimals aside), "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) | {"": ""), "{amp}"); + // Not a value: the plain text, with nothing not a number written. + let plain = page("one\ntwo\nthree", 60.0, TextVAlign::Top, 1.0, TextCase::None); + for odd in [ + page("one\ntwo\nthree", 60.0, TextVAlign::Invalid, f64::NAN, TextCase::Invalid), + page("one\ntwo\nthree", 60.0, TextVAlign::Top, f64::INFINITY, TextCase::None), + ] { + assert_eq!(odd, plain); + assert!(!odd.contains("NaN") && !odd.contains("inf"), "{odd}"); + } } /// The vector PDF records the block as the page draws it: a block's PDF differs from the plain - /// text's, and the plain one is still main's (`plain_texts_export_as_before`). + /// text's, an upper-case text's is the same as one typed in capitals, and the plain one is still + /// main's (`plain_texts_export_as_before`). #[test] fn a_text_block_reaches_the_pdf() { use rustgis_map::layout::{TextCase, TextVAlign}; - let pdf = |v: TextVAlign, ls: f64, c: TextCase| { + let pdf_of = |text: &str, v: TextVAlign, ls: f64, c: TextCase| { let mut l = Layout::new("PDF", 100.0, 80.0); - let mut kind = ElementKind::text("one\ntwo\nthree", 10.0, rustgis_map::Rgba::rgb(0, 0, 0), false); + let mut kind = ElementKind::text(text, 10.0, rustgis_map::Rgba::rgb(0, 0, 0), false); if let ElementKind::Text { valign, line_spacing, case, .. } = &mut kind { (*valign, *line_spacing, *case) = (v, ls, c); } @@ -742,6 +771,7 @@ mod tests { let (drawing, _) = crate::layout::render_drawing(&l, &mut [], 150.0, &PageInfo::default()).unwrap(); crate::pdf::write(&[crate::pdf::Page::drawing(drawing, l.width, l.height)], "Block") }; + let pdf = |v: TextVAlign, ls: f64, c: TextCase| pdf_of("one\ntwo\nthree", v, ls, c); let plain = pdf(TextVAlign::Top, 1.0, TextCase::None); let block = pdf(TextVAlign::Bottom, 1.5, TextCase::Upper); assert!(plain.starts_with(b"%PDF") && block.starts_with(b"%PDF"), "both write"); @@ -752,6 +782,8 @@ mod tests { { assert_ne!(pdf(v, ls, c), plain, "{v:?} {ls} {c:?}"); } + let typed = pdf_of("ONE\nTWO\nTHREE", TextVAlign::Top, 1.0, TextCase::None); + assert!(pdf(TextVAlign::Top, 1.0, TextCase::Upper) == typed, "upper case records the capitals as typed"); } /// An element's background (#2257) is a `` of its own under the element, its box grown From d6cafbc1a7972ef2d96467efc89e01bf1d2d7d3f Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:15:25 -0600 Subject: [PATCH 13/23] refactor(engine): one reader for a text's block settings in commands and capabilities The commands' reader of `valign`, `lineSpacing` and `case` is now `text_block_settings` (it shared a name with the renderer's line drawer), and the `layout-text-block` capability check reads each key through it instead of parsing them again by hand, so the two cannot drift. Each key is still read on its own, so a refused key does not hide another one set, as before. The off-page part of the line spacing test starts from mixed-case words, so lower case is a change it proves, and `refit_scale_box`'s doc comment is wrapped to the file's width. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout.rs | 33 ++++++++++++----------- crates/engine/src/project_capabilities.rs | 26 +++++++++--------- crates/engine/src/tests.rs | 6 ++--- 3 files changed, 34 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 32ad733158..0ffb0f3532 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -3873,7 +3873,7 @@ fn add_element(s: &mut Session, p: &Value) -> CmdResult { let (font, font_name) = text_font(p, (FontFamily::Sans, None))?; let rotation = text_rotation(p)?.unwrap_or(0.0); let wrap = text_wrap(p)?.unwrap_or(false); - let (valign, line_spacing, case) = text_block(p, (TextVAlign::Top, LINE_SPACING, TextCase::None))?; + let (valign, line_spacing, case) = text_block_settings(p, (TextVAlign::Top, LINE_SPACING, TextCase::None))?; let k = ElementKind::Text { text, size, @@ -4383,8 +4383,9 @@ fn gives_text_block(p: &Value) -> bool { /// or null: `valign` and `case` a name as [`TextVAlign::from_name`] and [`TextCase::from_name`] /// read it, `lineSpacing` a number (or a numeric string) from [`MIN_LINE_SPACING`] to /// [`MAX_LINE_SPACING`]. Anything else is refused, so nothing changes, rather than drawn otherwise -/// than asked. -fn text_block(p: &Value, current: (TextVAlign, f64, TextCase)) -> Result<(TextVAlign, f64, TextCase), String> { +/// than asked. The one reader of these keys: the commands and their capability check +/// (`command_uses_text_block`) both read them here. +pub(crate) fn text_block_settings(p: &Value, current: (TextVAlign, f64, TextCase)) -> Result<(TextVAlign, f64, TextCase), String> { let (mut valign, mut spacing, mut case) = current; if gives(p, "valign") { valign = ps(p, "valign").and_then(TextVAlign::from_name).ok_or("valign is top, middle or bottom")?; @@ -5513,7 +5514,7 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { }; // A text's block alignment, line spacing and case, checked before anything changes. let new_block = match kind_now { - Some(ElementKind::Text { valign, line_spacing, case, .. }) => Some(text_block(p, (*valign, *line_spacing, *case))?), + Some(ElementKind::Text { valign, line_spacing, case, .. }) => Some(text_block_settings(p, (*valign, *line_spacing, *case))?), _ if gives_text_block(p) => return Err(ONLY_TEXT_BLOCK.into()), _ => None, }; @@ -6033,19 +6034,19 @@ fn frame_view_changed(s: &mut Session, li: usize, frame: u32, basis: Option<&Box /// A publication's scale bar box measured again after its frame's scale, width, centre or map /// changed (#1379, #2581), each measured on its own map and centre: -/// the "Scale Box", the "Scale Bar" of `frame` and the "Scale" under it, as a publication lays them -/// out (one place, one width, none locked), take the width that bar and the text under it (its -/// tokens filled as the page draws them, measured as drawn) now need, kept on the side of the +/// the "Scale Box", the "Scale Bar" of `frame` and the "Scale" under it, as a publication lays +/// them out (one place, one width, none locked), take the width that bar and the text under it +/// (its tokens filled as the page draws them, measured as drawn) now need, kept on the side of the /// frame they are nearer. A layout without them, with them moved apart, with that text spaced out, -/// in upper or lower case or in another font, naming a map series page (which differs from page to page), or of a frame -/// other than the first (whose map the page fills the text from) is left as it is; so is a text -/// longer than the widest box a publication gives. Only a 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) 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. +/// in upper or lower case or in another font, naming a map series page (which differs from page to +/// page), or of a frame other than the first (whose map the page fills the text from) is left as +/// it is; so is a text longer than the widest box a publication gives. Only a 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) 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. fn refit_scale_box(s: &mut Session, li: usize, before: &BoxBasis) { let frame = before.frame; let Some(now) = scale_box_basis(s, li).filter(|b| b.frame == frame) else { return }; diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index c5b7caa60d..649e855213 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -382,21 +382,23 @@ fn text_blocks(e: &rustgis_map::layout::Element) -> bool { /// A layout command that gives a text a block alignment, line spacing or case off its default: /// an older reader ignores `valign`, `lineSpacing` and `case` and draws the text at the top, at -/// the usual spacing and as typed. Each is read as the command reads it, so the defaults -/// (`"top"`, `1` or `"1"`, `"none"`, in any case) and `null`, which leaves a text as it is, keep a -/// text as an older reader draws it. A value the command refuses needs nothing either: the command -/// changes nothing. Only a text takes the keys, so a `layout.update` is read by them alone. A -/// `layout.import` requires it for such a text once its layout is read into range, so a name it -/// doesn't know or a spacing that isn't a number, read as the default, needs nothing. +/// the usual spacing and as typed. Each is read on its own by the command's own reader +/// ([`crate::cmd::layout::text_block_settings`]), so the defaults (`"top"`, `1` or `"1"`, `"none"`, +/// in any case) and `null`, which leaves a text as it is, keep a text as an older reader draws it. +/// A value the command refuses needs nothing either: the command changes nothing. Only a text +/// takes the keys, so a `layout.update` is read by them alone. A `layout.import` requires it for +/// such a text once its layout is read into range, so a name it doesn't know or a spacing that +/// isn't a number, read as the default, needs nothing. fn command_uses_text_block(id: &str, params: &Value) -> bool { - use rustgis_map::layout::{LINE_SPACING, MAX_LINE_SPACING, MIN_LINE_SPACING, TextCase, TextVAlign}; + use rustgis_map::layout::{LINE_SPACING, TextCase, TextVAlign}; match id { "layout.addElement" | "layout.update" => { - let name = |k: &str| params.get(k).and_then(Value::as_str); - name("valign").and_then(TextVAlign::from_name).is_some_and(|v| v != TextVAlign::Top) - || crate::cmd::f(params, "lineSpacing") - .is_some_and(|v| (MIN_LINE_SPACING..=MAX_LINE_SPACING).contains(&v) && v != LINE_SPACING) - || name("case").and_then(TextCase::from_name).is_some_and(|v| v != TextCase::None) + let usual = (TextVAlign::Top, LINE_SPACING, TextCase::None); + // Each key on its own, so one the command refuses doesn't hide another one set. + ["valign", "lineSpacing", "case"].into_iter().any(|k| { + let one = Value::Object(params.get(k).into_iter().map(|v| (k.to_string(), v.clone())).collect()); + crate::cmd::layout::text_block_settings(&one, usual).is_ok_and(|set| set != usual) + }) } "layout.import" => imported_layout_uses(params, &["\"valign\"", "\"line_spacing\"", "\"case\""], text_blocks), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_text_block)), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c3e9a1c15d..561be1d84d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12616,10 +12616,10 @@ fn layout_update_says_the_lines_a_wider_line_spacing_leaves_out() { s.run("layout.update", &json!({"element": id, "lineSpacing": 1})).unwrap(); assert_eq!(said(&s, mark), "", "back at the usual spacing they all fit"); // Upper case widens an unwrapped line past the page's right edge: its box placed so the line - // as typed ends inside the page and in upper case past it. - let words = "the quick brown fox jumps"; + // in lower case ends inside the page and in upper case past it. + let words = "The Quick Brown Fox Jumps"; let width = |s: &str| crate::render::report::width_mm(s, 12.0, false); - let (lower, upper) = (width(words), width(&words.to_uppercase())); + let (lower, upper) = (width(&words.to_lowercase()), width(&words.to_uppercase())); assert!(upper - lower > 4.0, "{lower} {upper}"); let x = 297.0 - (lower + upper) / 2.0; let line = add(&mut s, json!({"kind": "text", "text": words, "size": 12, "x": x, "y": 100, "w": 10, "h": 10})); From eb2d92a1b06ec12bd28865bae853674bb7d5a460 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:19:50 -0600 Subject: [PATCH 14/23] test(ui): the Format pane's text block rows by their words, defaults and limits The tests click "Upper case" and "Lower case" by the words shown rather than through the model's labels. The undo test also reads, through the accessibility tree, that the pane opens on Top, As typed and a spacing of 1, and that a spacing of 5 set as assistive technology does is kept at 3 in one undo step. The Format pane's local holding the line spacing is `line_sp`, not `lines`. Co-Authored-By: Claude Fable 5.2 --- crates/ui-egui/src/layoutview.rs | 41 +++++++++++++++++++++----------- crates/ui-egui/src/textform.rs | 2 +- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index 07b750d951..9688559102 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -2684,7 +2684,7 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { let mut buf = app.layout.typing.remove(&key).unwrap_or_else(|| text.clone()); let (mut sz, mut c, mut bb) = (*size, crate::theme::c32(*color), *bold); let (mut it, mut al, mut ls, mut fam, mut named) = (*italic, *align, *letter_spacing, *font, font_name.clone()); - let (mut wr, mut va, mut lines, mut cs) = (*wrap, valign.kept(), *line_spacing, case.kept()); + let (mut wr, mut va, mut line_sp, mut cs) = (*wrap, valign.kept(), *line_spacing, case.kept()); let tokens = [rustgis_engine::map::graphics::TOKENS, rustgis_engine::map::layout::PAGE_TOKENS]; let warning = app .layout @@ -2703,7 +2703,7 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { wrap: Some(&mut wr), warning, valign: Some(&mut va), - line_spacing: Some(&mut lines), + line_spacing: Some(&mut line_sp), case: Some(&mut cs), letter_spacing: Some(&mut ls), font: Some(&mut fam), @@ -2741,7 +2741,7 @@ fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: usize) { update(app, json!({"valign": va.code()})); } if settled.line_spacing { - update(app, json!({"lineSpacing": lines})); + update(app, json!({"lineSpacing": line_sp})); } if settled.case { update(app, json!({"case": cs.code()})); @@ -3988,8 +3988,9 @@ mod tests { assert!(!wraps(h.state())); } - /// A text element's Vertical alignment, Line spacing and Case in the Format pane: each change one - /// undo step, the same value picked again none. + /// A text element's Vertical alignment, Line spacing and Case in the Format pane: shown at their + /// defaults on opening, each change one undo step, the same value picked again none, a spacing + /// past the widest set at the widest. #[test] fn a_texts_block_alignment_line_spacing_and_case_are_one_undo_step_each() { use egui::accesskit::{Action, ActionData, ActionRequest, Role}; @@ -4021,6 +4022,9 @@ mod tests { // Opening the pane sends nothing, and shows a plain text's defaults. assert_eq!(h.state().session.undo_depth(), depth, "opening the pane changed nothing"); assert_eq!(block(h.state()), (TextVAlign::Top, 1.0, TextCase::None)); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Vertical alignment").value().as_deref(), Some("Top")); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Case").value().as_deref(), Some("As typed")); + assert_eq!(h.get_by_role_and_label(Role::SpinButton, "Line spacing").accesskit_node().numeric_value(), Some(1.0)); let pick = |h: &mut egui_kittest::Harness<'_, RustGisApp>, list: &str, item: &str| { h.get_by_role_and_label(Role::ComboBox, list).click(); h.run_steps(2); @@ -4032,22 +4036,31 @@ mod tests { assert_eq!(h.state().session.undo_depth(), depth + 1, "one step"); pick(&mut h, "Vertical alignment", "Middle"); assert_eq!(h.state().session.undo_depth(), depth + 1, "the same item again is no step"); - pick(&mut h, "Case", TextCase::Lower.label()); + pick(&mut h, "Case", "Lower case"); assert_eq!(block(h.state()).2, TextCase::Lower); assert_eq!(h.state().session.undo_depth(), depth + 2); // The spacing set as assistive technology does. - let (node, tree) = h.get_by_role_and_label(Role::SpinButton, "Line spacing").accesskit_node().locate(); - h.event(egui::Event::AccessKitActionRequest(ActionRequest { - action: Action::SetValue, - target_tree: tree, - target_node: node, - data: Some(ActionData::NumericValue(1.5)), - })); - h.run_steps(3); + let set_spacing = |h: &mut egui_kittest::Harness<'_, RustGisApp>, v: f64| { + let (node, tree) = h.get_by_role_and_label(Role::SpinButton, "Line spacing").accesskit_node().locate(); + h.event(egui::Event::AccessKitActionRequest(ActionRequest { + action: Action::SetValue, + target_tree: tree, + target_node: node, + data: Some(ActionData::NumericValue(v)), + })); + h.run_steps(3); + }; + set_spacing(&mut h, 1.5); assert_eq!(block(h.state()), (TextVAlign::Middle, 1.5, TextCase::Lower)); assert_eq!(h.state().session.undo_depth(), depth + 3); h.state_mut().run("edit.undo", json!({})).unwrap(); assert_eq!(block(h.state()), (TextVAlign::Middle, 1.0, TextCase::Lower), "one step undoes the spacing alone"); + // Past the widest: set at the widest, in one step. + h.run_steps(3); + let before = h.state().session.undo_depth(); + set_spacing(&mut h, 5.0); + assert_eq!(block(h.state()), (TextVAlign::Middle, 3.0, TextCase::Lower)); + assert_eq!(h.state().session.undo_depth(), before + 1, "one step"); } /// The Format pane tells lines below a text's box from lines past the 200 a text draws, and diff --git a/crates/ui-egui/src/textform.rs b/crates/ui-egui/src/textform.rs index df66acf397..49330ed6a2 100644 --- a/crates/ui-egui/src/textform.rs +++ b/crates/ui-egui/src/textform.rs @@ -565,7 +565,7 @@ mod tests { h.run(); h.get_by_role_and_label(Role::ComboBox, "Case").click(); h.run(); - h.get_by_label(TextCase::Upper.label()).click(); + h.get_by_label("Upper case").click(); h.run(); assert_eq!((h.state().valign, h.state().case), (TextVAlign::Bottom, TextCase::Upper)); assert_eq!(h.state().settled, ["valign", "case"]); From bcee86a6eb3cbc03d174b3dc7ca4c1a79dc8c23c Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:19:50 -0600 Subject: [PATCH 15/23] docs(layout): the text block paragraph after the font paragraph The Vertical alignment, Line spacing and Case paragraph now follows the font paragraph ("...no font file goes into it."), so the font sentence no longer reads as if it belonged to text blocks, and the text clipping paragraph is wrapped again without its short line. Co-Authored-By: Claude Fable 5.2 --- docs/user-guide/layouts.md | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 698bde4ce1..cd6f5b55b7 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -472,16 +472,15 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu don't fit when they set a text, its size, font or fallback font, bold, italic, alignment, spacing, line spacing, case, wrap or box, or show it, and the Format pane shows the count under **Wrap to the box** (a text wrapped past the 200 lines a text draws counts them as "or more"). A - text draws - 200 lines at most, whatever its box: lines past them are said apart, with the advice to split - the text into more than one, since a taller box doesn't draw them. A text whose ink crosses the - page's edge is said in a notice of its own when one of these commands puts it there, so a text - both cut below its box and past the edge is told each: `layout.addElement` and `layout.update` add a text whose ink - crosses it, set what its lines or box are, show it, move it (`x`, `y`), turn it (`rotation`) or - set its vertical alignment (`valign`), and `layout.duplicateElement` copies it past the edge, and - each advises moving it inside the page, resizing it or reducing its size. A move, a turn, an - alignment or a copy alone says only that, not the - lines again; a text turned within the page, or with no letter or ink to show, says nothing. + text draws 200 lines at most, whatever its box: lines past them are said apart, with the advice + to split the text into more than one, since a taller box doesn't draw them. A text whose ink + crosses the page's edge is said in a notice of its own when one of these commands puts it there, + so a text both cut below its box and past the edge is told each: `layout.addElement` and + `layout.update` add a text whose ink crosses it, set what its lines or box are, show it, move it + (`x`, `y`), turn it (`rotation`) or set its vertical alignment (`valign`), and + `layout.duplicateElement` copies it past the edge, and each advises moving it inside the page, + resizing it or reducing its size. A move, a turn, an alignment or a copy alone says only that, not + the lines again; a text turned within the page, or with no letter or ink to show, says nothing. Resizing the page (`layout.page`) measures no text, so a text a smaller page cuts is told only by the export and the layout view. - **Text** and **Dynamic Text**: `{date}`, `{time}`, `{scale}`, `{map}`, `{crs}`, `{page}`, @@ -530,6 +529,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu commands, the Format pane and the export notice above say so. Scripts set `"wrap": true` on `layout.addElement` and `layout.update`. A project with a wrapped text needs this release or a later one to open. + Scripts give the family's name: `"font": "Garamond"`, with `"fallback": "serif"` if wanted; + `labels.fonts` lists the installed families. The project keeps the name, never a file. A PDF + sets its text in the letters' own outlines, so it shows the family wherever it is opened, and + the text can still be searched and copied; no font file goes into it. **Vertical alignment** puts a text's block of lines at the **Top** of its box (the default, as texts always were), in its **Middle**, or at its **Bottom**, its last line on the box's lower edge: a caption under a picture, a note at a panel's foot. A block taller than its box is drawn @@ -545,11 +548,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu a setting put back to its default is no longer saved. A project that uses them can't be opened by an older RustGIS, and a layout file (`.rgislayout`) with such a text lists them in its header, so an older RustGIS refuses it as well. - Scripts give the family's name: `"font": "Garamond"`, with `"fallback": "serif"` if wanted; - `labels.fonts` lists the installed families. The project keeps the name, never a file. A PDF - sets its text in the letters' own outlines, so it shows the family wherever it is opened, and - the text can still be searched and copied; no font file goes into it. **Picture** places a PNG - or JPEG. + **Picture** places a PNG or JPEG. - **Map Series**: one page per feature of an index layer; see [Map series](#map-series) for setup, page names, scales and a locator. - Click an element to select it, drag to move, drag its handles to resize, and edit it in the From a1ae013da018fab097225913c4d368588dbfea1c Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:59:14 -0600 Subject: [PATCH 16/23] fix(layout): a publication's scale box is measured from its text in its case The box was left as it was for a "Scale" text in upper or lower case, so an upper case line could run past it. The text is now measured as it is drawn, tokens filled and then cased, and a change of case measures the box again. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout.rs | 19 +++++++------ crates/engine/src/tests.rs | 50 ++++++++++++++++++++++----------- 2 files changed, 43 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index bfd001215d..9687f8e04c 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -5966,7 +5966,7 @@ fn update(s: &mut Session, p: &Value) -> CmdResult { let restyled = id == basis.bar_id && BAR_FIT_KEYS.iter().any(|k| p.get(*k).is_some()); // Its frame's centre and map fill the text's tokens and set the bar's ground too. (id == basis.frame && given(&["scale", "w", "center", "map"])) - || (id == basis.text_id && given(&["text", "size", "bold"])) + || (id == basis.text_id && given(&["text", "size", "bold", "case"])) || restyled }); // A map frame drawn at another view: its scale bars' lengths and labels change (#2581). @@ -6028,7 +6028,7 @@ const PLACED_OVER_MAP: [&str; 3] = ["Legend Box", "Locator", "North Arrow"]; /// What a publication's scale bar box is measured from: its frame (id, map, centre, scale, width), /// its bar (id, and the bar as it is set: every setting changes its labels or their room) and the -/// text under the bar (id, text, size, boldness). +/// text under the bar (id, text, size, boldness, case). #[derive(Clone)] struct BoxBasis { frame: u32, @@ -6042,15 +6042,16 @@ struct BoxBasis { text: String, size: f64, bold: bool, + case: TextCase, } /// The text under a publication's scale bar as the page draws it from `b`: `{scale}` filled as -/// `layout.publication` fills it, the other tokens from the frame's map. +/// `layout.publication` fills it, the other tokens from the frame's map, then in its case. fn basis_text(l: &Layout, m: &rustgis_map::Map, b: &BoxBasis) -> String { let info = crate::render::layout::PageInfo { page: 1, pages: 1, page_name: String::new() }; let cam = rustgis_map::layout::frame_camera(m, b.center, b.scale, 0.0, 0.0); let text = b.text.replace("{scale}", &crate::render::layout::scale_ratio_text(b.scale, l.decimal_comma)); - crate::render::layout::expand(&text, l, &info, Some((m, cam))) + b.case.kept().apply(crate::render::layout::expand(&text, l, &info, Some((m, cam)))) } /// The automatic width (mm) of a publication's scale bar box measured from `b`: the one @@ -6076,7 +6077,7 @@ fn scale_box_basis(s: &Session, li: usize) -> Option { let l = s.project.layouts.get(li)?; let named = |name: &str| l.elements.iter().find(|e| e.name == name); let (bar, written) = (named("Scale Bar")?, named("Scale")?); - let (ElementKind::ScaleBar { frame, .. }, ElementKind::Text { text, size, bold, .. }) = (&bar.kind, &written.kind) else { + let (ElementKind::ScaleBar { frame, .. }, ElementKind::Text { text, size, bold, case, .. }) = (&bar.kind, &written.kind) else { return None; }; let fr = l.element(*frame)?; @@ -6093,6 +6094,7 @@ fn scale_box_basis(s: &Session, li: usize) -> Option { text: text.clone(), size: *size, bold: *bold, + case: *case, }) } @@ -6118,8 +6120,8 @@ fn frame_view_changed(s: &mut Session, li: usize, frame: u32, basis: Option<&Box /// the "Scale Box", the "Scale Bar" of `frame` and the "Scale" under it, as a publication lays /// them out (one place, one width, none locked), take the width that bar and the text under it /// (its tokens filled as the page draws them, measured as drawn) now need, kept on the side of the -/// frame they are nearer. A layout without them, with them moved apart, with that text spaced out, -/// in upper or lower case or in another font, naming a map series page (which differs from page to +/// frame they are nearer, the text measured in its case. A layout without them, with them moved +/// apart, with that text spaced out or in another font, naming a map series page (which differs from page to /// page), or of a frame other than the first (whose map the page fills the text from) is left as /// it is; so is a text longer than the widest box a publication gives. Only a box as wide as /// `before` (what it was measured from before the change: its frame, bar and text) is measured @@ -6138,13 +6140,12 @@ fn refit_scale_box(s: &mut Session, li: usize, before: &BoxBasis) { let (Some(m), Some(was)) = (map_of(&now), map_of(before)) else { return }; let named = |name: &str| l.elements.iter().find(|e| e.name == name); let (Some(boxed), Some(bar), Some(text)) = (named("Scale Box"), named("Scale Bar"), named("Scale")) else { return }; - let (ElementKind::ScaleBar { frame: of, .. }, ElementKind::Text { text: written, letter_spacing, font, font_name, case, .. }) = + let (ElementKind::ScaleBar { frame: of, .. }, ElementKind::Text { text: written, letter_spacing, font, font_name, .. }) = (&bar.kind, &text.kind) else { return; }; if *letter_spacing != 0.0 - || case.kept() != TextCase::None || *font != FontFamily::Sans || font_name.is_some() || (l.series.is_some() && written.contains("{page")) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 66aa91aafd..16d1ac5438 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12910,32 +12910,48 @@ fn a_publication_scale_box_follows_a_detailed_bar() { assert!((boxed(&s) - hand).abs() < 1e-9, "set by hand, kept plain again: {} vs {hand}", boxed(&s)); } -/// A publication's scale box isn't measured again for a "Scale" text drawn in upper or lower case, -/// which a box measured for the text as typed would not hold, as it isn't for one spaced out: -/// its frame drawn at another scale keeps the box's width. +/// A publication's scale bar box is measured from the text under its bar in the case it is drawn +/// in: upper case, which widens the line, widens the box, and the box goes back with the case. #[test] -fn a_publication_scale_box_keeps_its_width_for_a_cased_scale_text() { - use rustgis_map::layout::ElementKind; +fn a_publication_scale_box_follows_its_scale_text_into_its_case() { 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 frame = s.project.layouts[li].first_frame().unwrap(); let auto = |s: &Session| crate::cmd::layout::scale_box_auto(s, li).expect("an automatic box"); let boxed = |s: &Session| named(s, "Scale Box").w; - let scale = match &s.project.layouts[li].element(frame).unwrap().kind { - ElementKind::MapFrame { scale, .. } => *scale, + let text = named(&s, "Scale"); + let size = match &text.kind { + rustgis_map::layout::ElementKind::Text { size, .. } => *size, k => panic!("{k:?}"), }; - // Plain, the frame at another scale measures the box again. - s.run("layout.update", &json!({"layout": li, "element": frame, "scale": scale * 2.0})).unwrap(); - assert!((boxed(&s) - auto(&s)).abs() < 0.01, "plain, refitted: {} vs {}", boxed(&s), auto(&s)); - // In upper case, it keeps its width though the plain text's box would now be another. - s.run("layout.update", &json!({"layout": li, "element": named(&s, "Scale").id, "case": "upper"})).unwrap(); - let kept = boxed(&s); - s.run("layout.update", &json!({"layout": li, "element": frame, "scale": scale * 5.0})).unwrap(); - assert!((auto(&s) - kept).abs() > 0.01, "the plain text's box would change: {} vs {kept}", auto(&s)); - assert!((boxed(&s) - kept).abs() < 1e-9, "cased, kept: {} vs {kept}", boxed(&s)); + // The box as the bar alone sets it, and the widest one a publication gives (0.3 of its frame). + let bar = boxed(&s); + let frame = s.project.layouts[li].first_frame().unwrap(); + let widest = (s.project.layouts[li].element(frame).unwrap().w * 0.3).max(25.0); + assert!(widest - bar > 2.0, "room between the bar's box and the widest: {bar} to {widest}"); + // A line, measured as the box measures it (a millimetre each side), that in upper case is + // wider than the bar and still within the widest box: found by adding narrow letters, so it + // holds in any face. + let wide = |t: &str| crate::render::report::width_mm(t, size as f32, false) + 2.0; + let line = (0..400) + .map(|n| format!("{}{}", "a".repeat(20), "i".repeat(n))) + .find(|t| wide(&t.to_uppercase()) > bar + 1.0) + .expect("a line wider than the bar"); + let (typed_w, upper_w) = (wide(&line), wide(&line.to_uppercase())); + assert!(upper_w < widest - 0.2 && typed_w < upper_w - 0.5, "{typed_w} then {upper_w} in {bar} to {widest}"); + s.run("layout.update", &json!({"layout": li, "element": text.id, "text": line})).unwrap(); + let typed = boxed(&s); + assert!((typed - auto(&s)).abs() < 0.01 && (typed - typed_w.max(bar)).abs() < 0.01, "as typed: {typed} vs {}", auto(&s)); + // In upper case the same line is wider, and so is the box, with the bar and the text in it. + s.run("layout.update", &json!({"layout": li, "element": text.id, "case": "upper"})).unwrap(); + let upper = boxed(&s); + assert!((upper - upper_w).abs() < 0.01 && upper > typed + 0.4, "upper case widens the box: {upper} vs {upper_w}, typed {typed}"); + assert!((upper - auto(&s)).abs() < 0.01, "upper, refitted: {upper} vs {}", auto(&s)); + assert!((named(&s, "Scale").w - upper).abs() < 1e-9 && (named(&s, "Scale Bar").w - upper).abs() < 1e-9); + // Back as typed, back to its width. + s.run("layout.update", &json!({"layout": li, "element": text.id, "case": "none"})).unwrap(); + assert!((boxed(&s) - typed).abs() < 0.01, "as typed again: {} vs {typed}", boxed(&s)); } /// A layout element refuses a colour, fill or outline its kind doesn't draw, before anything From 48ad38d68449a1cd48949b7283f84b8f2a1bc758 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:59:14 -0600 Subject: [PATCH 17/23] docs(engine): a block key on another kind of element counts for the text block capability Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/project_capabilities.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 649e855213..6664ca9597 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -385,8 +385,10 @@ fn text_blocks(e: &rustgis_map::layout::Element) -> bool { /// the usual spacing and as typed. Each is read on its own by the command's own reader /// ([`crate::cmd::layout::text_block_settings`]), so the defaults (`"top"`, `1` or `"1"`, `"none"`, /// in any case) and `null`, which leaves a text as it is, keep a text as an older reader draws it. -/// A value the command refuses needs nothing either: the command changes nothing. Only a text -/// takes the keys, so a `layout.update` is read by them alone. A `layout.import` requires it for +/// A value the command refuses on a text needs nothing either: the command changes nothing. The +/// keys are read here alone, so a block key given to another kind counts too, though its command +/// refuses it: an over-count that asks for the capability sooner, never a missing one. A +/// `layout.import` requires it for /// such a text once its layout is read into range, so a name it doesn't know or a spacing that /// isn't a number, read as the default, needs nothing. fn command_uses_text_block(id: &str, params: &Value) -> bool { From b26aa6459028e4ac3338d333e44ce732adeb07bf Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:13:50 -0600 Subject: [PATCH 18/23] perf(render): a turned text's picture starts at its block, not at its box's top A turned text in the middle or at the bottom of a tall box was drawn in a picture as tall as the box, which shares the picture's pixel budget with the empty room over the text. Top-aligned text is unchanged. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 87cad9ac00..83288406b7 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -4629,8 +4629,8 @@ pub fn line_pitch_mm(size: f64) -> f64 { /// The part of a text element's box (pixels, from its top-left corner) [`text_block`] inks, a line's /// height more each way: across, its lines as each is aligned (past the box where one overruns -/// it); down, its lines, or the box and the line [`text_block`] still draws past it. `None` when -/// it has no line. +/// it); down, its lines from where its block starts ([`block_shift`]), or the box and the line +/// [`text_block`] still draws past it. `None` when it has no line. fn text_area(r: Rect, s: &str, size: f32, style: TextStyle, ppp: f64) -> Option { let px = size.clamp(2.0, 400.0) * 1.33 * ppp as f32; let spacing = style.spacing * 1.33 * ppp as f32; @@ -4650,7 +4650,7 @@ fn text_area(r: Rect, s: &str, size: f32, style: TextStyle, ppp: f64) -> Option< let shift = block_shift(style.valign, f64::from(r.height()), f64::from(px), usize::from(lines), f64::from(style.line_spacing)) as f32; let block = (1.0 + (f32::from(lines) - 1.0) * style.line_spacing) * px * 1.25; let down = (r.height() + px).min(shift + block); - (lines > 0).then(|| Rect::from_ltrb(x0 - px, -px, x1 + px, down + px)).flatten() + (lines > 0).then(|| Rect::from_ltrb(x0 - px, shift - px, x1 + px, down + px)).flatten() } /// Draws with `draw` (given the box to draw in and how many of the page's pixels one of its own From e068d541e5f69c7662b83029619ecd9a491206ee Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:18:46 -0600 Subject: [PATCH 19/23] docs(engine): reflow the text block capability's comment Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/project_capabilities.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 6664ca9597..437efddf24 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -388,9 +388,8 @@ fn text_blocks(e: &rustgis_map::layout::Element) -> bool { /// A value the command refuses on a text needs nothing either: the command changes nothing. The /// keys are read here alone, so a block key given to another kind counts too, though its command /// refuses it: an over-count that asks for the capability sooner, never a missing one. A -/// `layout.import` requires it for -/// such a text once its layout is read into range, so a name it doesn't know or a spacing that -/// isn't a number, read as the default, needs nothing. +/// `layout.import` requires it for such a text once its layout is read into range, so a name it +/// doesn't know or a spacing that isn't a number, read as the default, needs nothing. fn command_uses_text_block(id: &str, params: &Value) -> bool { use rustgis_map::layout::{LINE_SPACING, TextCase, TextVAlign}; match id { From 49f4a15b720365ee5fa28b212a483b86797598b5 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:35:41 -0600 Subject: [PATCH 20/23] refactor(render): the usual line spacing by its constant; the print-layout skill names all three text block keys Co-Authored-By: Claude Fable 5.2 --- crates/assistant/skills/print-layout/SKILL.md | 2 +- crates/render/src/layout.rs | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index d0b2475b28..0e2c092285 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -28,7 +28,7 @@ description: Make a printable page layout — map frame, title, legend, north ar `"valign"` (`"top"`, `"middle"`, `"bottom"`), `"lineSpacing"` (0.5–3, default 1) and `"case"` (`"none"`, `"upper"`, `"lower"`; applied when drawn, the text kept as typed). `"grid"` adds a graticule to the frame (`"style": "ticks"` for neatline ticks, `"format": "dms"`, `"edges"`). -5. Adjust with `layout.update` (`{"element": id, "x", "y", "w", "h", "text", "size", "bold", "valign"}`). The ids come from the +5. Adjust with `layout.update` (`{"element": id, "x", "y", "w", "h", "text", "size", "bold", "valign", "lineSpacing", "case"}`). The ids come from the results of the earlier calls. 6. `layout.export` `{"path": "map.pdf"}`, or `.png` with a `dpi` (300 for print). Exporting writes a file, so the user is asked first. `layout.close` goes back to the map. diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 83288406b7..d2a9d86e4e 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -429,7 +429,7 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option true, false, None, - (TextVAlign::Top, 1.0), + (TextVAlign::Top, USUAL_LINE_SPACING), ) } // A colorbar's title in the lines it is drawn in (#2493), when it draws one: its @@ -469,7 +469,7 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option false, true, Some(fits), - (TextVAlign::Top, 1.0), + (TextVAlign::Top, USUAL_LINE_SPACING), ) } _ => return None, @@ -4498,7 +4498,7 @@ pub(crate) fn text_style( ) -> TextStyle { let family = font_name.and_then(crate::families::find_ready); let face = text::Face { bold, italic, serif: font == rustgis_map::layout::FontFamily::Serif, family }; - TextStyle { face, align, spacing: letter_spacing as f32, valign: TextVAlign::Top, line_spacing: 1.0 } + TextStyle { face, align, spacing: letter_spacing as f32, valign: TextVAlign::Top, line_spacing: USUAL_LINE_SPACING } } /// Pixels per millimetre a wrapped text's lines are measured at (300 dpi), whatever the @@ -4571,7 +4571,7 @@ fn colorbar_title_style() -> TextStyle { align: TextAlign::Left, spacing: 0.0, valign: TextVAlign::Top, - line_spacing: 1.0, + line_spacing: USUAL_LINE_SPACING, } } @@ -4621,6 +4621,9 @@ fn colorbar_bar_room(ppp: f32, orientation: Orientation) -> f32 { } } +/// The usual line spacing ([`rustgis_map::layout::LINE_SPACING`]) as the drawing holds it. +const USUAL_LINE_SPACING: f32 = rustgis_map::layout::LINE_SPACING as f32; + /// The distance between two lines of text at `size` points, in mm, at the usual line spacing (1), /// as [`text_block`] sets them there; a text's line spacing multiplies it. pub fn line_pitch_mm(size: f64) -> f64 { From c5af47b0412ff4db91bfa0e49dd5918acf61c199 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:45:08 -0600 Subject: [PATCH 21/23] docs: reflow comments to the files' width Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout.rs | 18 +++++++++--------- crates/map/src/layout.rs | 3 ++- crates/ui-egui/src/textform.rs | 4 ++-- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 9687f8e04c..a6eff90529 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -6121,15 +6121,15 @@ fn frame_view_changed(s: &mut Session, li: usize, frame: u32, basis: Option<&Box /// them out (one place, one width, none locked), take the width that bar and the text under it /// (its tokens filled as the page draws them, measured as drawn) now need, kept on the side of the /// frame they are nearer, the text measured in its case. A layout without them, with them moved -/// apart, with that text spaced out or in another font, naming a map series page (which differs from page to -/// page), or of a frame other than the first (whose map the page fills the text from) is left as -/// it is; so is a text longer than the widest box a publication gives. Only a 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) 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. +/// apart, with that text spaced out or in another font, naming a map series page (which differs +/// from page to page), or of a frame other than the first (whose map the page fills the text +/// from) is left as it is; so is a text longer than the widest box a publication gives. Only a +/// 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) +/// 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. fn refit_scale_box(s: &mut Session, li: usize, before: &BoxBasis) { let frame = before.frame; let Some(now) = scale_box_basis(s, li).filter(|b| b.frame == frame) else { return }; diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index 4853ee2801..eb6505c9ab 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -3180,7 +3180,8 @@ impl Layout { } ElementKind::Text { text, size, letter_spacing, rotation: turn, valign, line_spacing, case, .. } => { *turn = rotation(*turn); - // A file's unknown name or wrong kind of value is read as a marker: back to the default. + // A file's unknown name or wrong kind of value is read as a marker: back to the + // default. *valign = valign.kept(); *case = case.kept(); *line_spacing = line_spacing_in_range(*line_spacing); diff --git a/crates/ui-egui/src/textform.rs b/crates/ui-egui/src/textform.rs index 49330ed6a2..881657a47e 100644 --- a/crates/ui-egui/src/textform.rs +++ b/crates/ui-egui/src/textform.rs @@ -543,8 +543,8 @@ mod tests { assert_eq!(h.state().settled, ["italic"]); } - /// A layout text's Vertical alignment, Line spacing and Case show only where they are lent (not on a - /// text graphic); picking another item settles it, picking the current one doesn't. + /// A layout text's Vertical alignment, Line spacing and Case show only where they are lent (not + /// on a text graphic); picking another item settles it, picking the current one doesn't. #[test] fn block_rows_show_only_when_lent_and_are_settled() { let mut h = harness(Form { text: "T".into(), size: 12.0, styled: true, line_spacing: 1.0, ..Form::default() }); From fba8cf243f7a9d8c9678922acb36d2ba20eefb9f Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:52:17 -0600 Subject: [PATCH 22/23] docs(render): say which pages the plain text pin draws at 300 dpi Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index d2a9d86e4e..694c9a317a 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -10095,8 +10095,9 @@ Elaboração: RustGIS", const PINNED_TEXT_LOSSES: u64 = 0x26af_01ce_67e5_7cfd; /// A text with none of the block settings draws, and is measured for lines that don't fit and ink - /// off the page, exactly as main did, at 96 and 300 dpi: in a process of its own, told to use the - /// built-in face before any text. + /// off the page, exactly as main did: every page at 96 dpi, and the first eight (left-aligned, + /// unwrapped, upright and turned a quarter) at 300 dpi too, which is enough to hold the scaling + /// of the line pitch. In a process of its own, told to use the built-in face before any text. #[cfg(not(target_arch = "wasm32"))] #[test] fn plain_texts_draw_as_before() { From b230fd5c991f4d968be7a3095ffd5efb5673ab69 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:12:12 -0600 Subject: [PATCH 23/23] fix(render): a text cut at the 200 lines it draws starts at the top of its box The block's shift was worked out from the lines kept, so a text of more lines than a text draws, in a box the first 200 fit, was moved down as if it were whole. One function now gives the shift to the page, its cut-off check, a turned text's picture and the SVG, and a cut text gets none. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout.rs | 59 +++++++++++++++++++++++++++++++++---- crates/render/src/svg.rs | 3 +- 2 files changed, 55 insertions(+), 7 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 694c9a317a..ba64990cff 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -480,8 +480,7 @@ fn losses(layout: &Layout, maps: &[Map], dpi: f64, info: &PageInfo, only: Option let mut cy = if title { r.y() + LEGEND_ROW * (size / LEGEND_TITLE_PT) * ppp / 2.0 } else { - let n = s.lines().take(200).count(); - let shift = block_shift(block.0, f64::from(r.height()), f64::from(px), n, f64::from(block.1)) as f32; + let shift = text_shift(block.0, f64::from(r.height()), f64::from(px), &s, f64::from(block.1)) as f32; r.y() + shift + px * 0.6 }; let turn = Transform::from_rotate_at(rotation, r.x() + r.width() / 2.0, r.y() + r.height() / 2.0); @@ -4532,6 +4531,18 @@ pub(crate) fn drawn_text(expanded: String, case: TextCase, wrap: bool, width_mm: if wrap { wrapped(&s, width_mm, size, style) } else { s } } +/// The most lines a text draws. +const MAX_TEXT_LINES: usize = 200; + +/// [`block_shift`] for the text `s` as it is drawn ([`drawn_text`]), by its lines. A text of more +/// lines than a text draws is cut at them, so it starts at the top like any block that doesn't fit +/// its box, though the lines kept would: one rule for the page, its cut-off check, a turned text's +/// picture and the SVG. +pub(crate) fn text_shift(valign: TextVAlign, box_h: f64, px: f64, s: &str, line_spacing: f64) -> f64 { + let lines = s.lines().take(MAX_TEXT_LINES + 1).count(); + if lines > MAX_TEXT_LINES { 0.0 } else { block_shift(valign, box_h, px, lines, line_spacing) } +} + /// How far down its box of `box_h` pixels a text's block of `lines` lines at `px` pixels, spaced /// `line_spacing` times the usual, starts: 0 at the top; half the room it leaves in the middle; /// all of it at the bottom, its last line's pitch ending on the box's bottom edge. A block taller @@ -4650,7 +4661,7 @@ fn text_area(r: Rect, s: &str, size: f32, style: TextStyle, ppp: f64) -> Option< (x0, x1, lines) = (x0.min(a), x1.max(b), lines + 1); } // Down to its last line, where its block alignment and line spacing put it. - let shift = block_shift(style.valign, f64::from(r.height()), f64::from(px), usize::from(lines), f64::from(style.line_spacing)) as f32; + let shift = text_shift(style.valign, f64::from(r.height()), f64::from(px), s, f64::from(style.line_spacing)) as f32; let block = (1.0 + (f32::from(lines) - 1.0) * style.line_spacing) * px * 1.25; let down = (r.height() + px).min(shift + block); (lines > 0).then(|| Rect::from_ltrb(x0 - px, shift - px, x1 + px, down + px)).flatten() @@ -4708,8 +4719,7 @@ fn text_block(pm: &mut Canvas, r: Rect, s: &str, size: f32, color: Rgba, style: let px = size.clamp(2.0, 400.0) * 1.33 * ppp as f32; // Letter spacing is in points, as the size is. let spacing = style.spacing * 1.33 * ppp as f32; - let n = s.lines().take(200).count(); - let shift = block_shift(style.valign, f64::from(r.height()), f64::from(px), n, f64::from(style.line_spacing)) as f32; + let shift = text_shift(style.valign, f64::from(r.height()), f64::from(px), s, f64::from(style.line_spacing)) as f32; let mut y = r.y() + shift + px * 0.6; for line in s.lines().take(200) { if y > r.y() + r.height() + px { @@ -8303,6 +8313,45 @@ Elaboração: RustGIS", } } + /// A text of more lines than a text draws is cut at them, so it is drawn from the top whatever + /// its alignment, though the lines kept would fit its box; one of exactly that many, all + /// drawn, is still aligned. + #[test] + fn a_text_cut_at_the_most_lines_it_draws_starts_at_the_top() { + let info = PageInfo::default(); + // 2 pt lines are 0.88 mm apart: 200 of them fill 176 mm of a 200 mm box. + let page = |lines: usize, v| { + let text = (0..lines).map(|i| format!("line {i}")).collect::>().join( + " +", + ); + let mut l = Layout::new("L", 100.0, 300.0); + let mut kind = ElementKind::text(&text, 2.0, Rgba::rgb(0, 0, 0), false); + set_block(&mut kind, v, 1.0, TextCase::None); + l.add("Block", (10.0, 10.0, 40.0, 200.0), kind); + l + }; + let drawn = |l: &Layout| render(l, &mut [], 96.0, &info).unwrap(); + let top = page(300, TextVAlign::Top); + for v in [TextVAlign::Middle, TextVAlign::Bottom] { + let l = page(300, v); + assert_eq!(drawn(&l).data(), drawn(&top).data(), "{v:?}"); + assert_eq!(text_losses(&l, &[], 96.0, &info), text_losses(&top, &[], 96.0, &info), "{v:?}"); + let svg = |l: &Layout| crate::svg::layout_svg(l, &mut [], 96.0, &info).unwrap().0; + assert_eq!(svg(&l), svg(&top), "{v:?}"); + assert_ne!(drawn(&page(200, v)).data(), drawn(&page(200, TextVAlign::Top)).data(), "{v:?}: all drawn, aligned"); + } + let text = |n: usize| { + vec!["x"; n].join( + " +", + ) + }; + assert_eq!(text_shift(TextVAlign::Bottom, 5000.0, 10.0, &text(201), 1.0), 0.0); + assert_eq!(text_shift(TextVAlign::Bottom, 5000.0, 10.0, &text(200), 1.0), block_shift(TextVAlign::Bottom, 5000.0, 10.0, 200, 1.0)); + assert!(text_shift(TextVAlign::Bottom, 5000.0, 10.0, &text(200), 1.0) > 0.0); + } + /// The cut-off check steps by the spaced pitch, as the page draws: a wider spacing leaves lines /// out of a box that held them, a tighter one draws lines a box cut. #[test] diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 81d4ef1c28..2bef015f66 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -129,8 +129,7 @@ fn elements( // past the frame left out. let em = size.clamp(2.0, 400.0) * 1.33 / PT_PER_MM; let ls = f64::from(style.line_spacing); - let n = text.lines().take(200).count(); - let top = y + crate::layout::block_shift(style.valign, h, em, n, ls); + let top = y + crate::layout::text_shift(style.valign, h, em, &text, ls); let (anchor, tx) = match align { TextAlign::Left => ("start", x), TextAlign::Center => ("middle", x + w / 2.0),