From 6898dcae95d2bd91d600b46211c7f99b20ff1ecf Mon Sep 17 00:00:00 2001 From: strebdom Date: Tue, 1 Dec 2026 19:03:44 +0100 Subject: [PATCH 1/8] feat(map): QGIS layouts' scale bars, north arrows and map overviews come in showing their map's frame (piece 12b of #882) - Scale bars as RustGIS's nearest style, with their units, divisions, label placement, text size, font, colours and unit label; a numeric one as a text printing {scale}. - North arrows (pictures following a map) as RustGIS's arrow. - Map overviews as extent indicators of the frame they outline. - Each linked to the frame its map item became on its page; one whose map isn't there is left out. - What differs from QGIS's drawing is noted, counted over the layouts. - The corpus gains layout-surrounds.qgs (QGIS 4.4.0). --- crates/engine/src/tests/qgis_layouts.rs | 37 + crates/map/src/qgis/layout.rs | 111 +- crates/map/src/qgis/layout/surround.rs | 327 +++ crates/map/src/qgis/layout_surround_tests.rs | 348 +++ crates/map/src/qgis/layout_tests.rs | 16 +- crates/map/src/qgis/mod.rs | 2 + crates/map/src/qgis/tests.rs | 2 +- crates/map/testdata/qgis/README.md | 4 +- .../map/testdata/qgis/generated/generate.py | 75 + .../qgis/generated/qgs/layout-surrounds.qgs | 2615 +++++++++++++++++ docs/user-guide/workspace.md | 12 +- 11 files changed, 3515 insertions(+), 34 deletions(-) create mode 100644 crates/map/src/qgis/layout/surround.rs create mode 100644 crates/map/src/qgis/layout_surround_tests.rs create mode 100644 crates/map/testdata/qgis/generated/qgs/layout-surrounds.qgs diff --git a/crates/engine/src/tests/qgis_layouts.rs b/crates/engine/src/tests/qgis_layouts.rs index abf209c2f4..b7ef54bdd3 100644 --- a/crates/engine/src/tests/qgis_layouts.rs +++ b/crates/engine/src/tests/qgis_layouts.rs @@ -217,3 +217,40 @@ fn a_long_layout_name_numbered_keeps_its_page_and_says_the_cut() { let answer = s.run("project.importQgis", &sheets()).unwrap(); assert!(!said(&answer), "{answer}"); } + +/// A QGIS layout's scale bar, north arrow and map overview come in showing the frames the import +/// made, inline and from a copy, and the layout exports. +#[test] +fn a_layouts_surrounds_show_the_imported_frames() { + let text = r#"TEPSG:2056 + + + + + + "#; + let check = |s: &Session| { + let l = s.project.layouts.iter().find(|l| l.name == "Surrounds").unwrap(); + let frames: Vec = l.elements.iter().filter(|e| matches!(e.kind, ElementKind::MapFrame { .. })).map(|e| e.id).collect(); + let (overview, main) = (frames[0], frames[1]); + assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::ScaleBar { frame, .. } if frame == main))); + assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::NorthArrow { frame, .. } if frame == main))); + let shown = l.elements.iter().find(|e| e.id == overview).unwrap().kind.extent_indicators(); + assert_eq!(shown.iter().map(|i| i.of).collect::>(), [main]); + }; + let mut s = Session::new(Project::default()); + s.run("project.importQgis", &json!({"text": text})).unwrap(); + check(&s); + let dir = std::env::temp_dir().join(format!("rustgis-qgis-surrounds-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let png = dir.join("surrounds.png"); + s.run("layout.export", &json!({"layout": "Surrounds", "path": png.display().to_string(), "dpi": 36})).unwrap(); + assert!(std::fs::metadata(&png).unwrap().len() > 0); + let _ = std::fs::remove_dir_all(&dir); + // From a copy. + let mut s = Session::new(Project::default()); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &json!({"text": text})).unwrap(); + let done = read.run(&Control::new()).unwrap(); + crate::cmd::reads::read_land(&mut s, done).unwrap(); + check(&s); +} diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index 84d2691ae8..dbe34b170b 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -73,7 +73,6 @@ pub struct LayoutPicture { #[derive(Default)] pub(super) struct Tally { legends: usize, - scale_bars: usize, north_arrows: usize, tables: usize, html: usize, @@ -83,7 +82,6 @@ pub(super) struct Tally { groups: usize, map_backgrounds: usize, grids: usize, - overviews: usize, atlases: usize, locked_layers: usize, turned_items: usize, @@ -154,8 +152,43 @@ pub(super) struct Tally { /// Labels whose margins leave their text less than an element can be across or down, its box /// widened to it. tiny_text: usize, + /// The QGIS layout being read's map items, as (uuid, layout, element), and the elements + /// waiting for one's frame ([`surround::link`]). + maps: Vec<(String, usize, u32)>, + /// The map items that will come in, by (uuid, layout) ([`surround::known_maps`]). + known: Vec<(String, usize)>, + /// Overviews past what a frame outlines, and scale bars' text bold, italic, underlined, + /// buffered or shadowed. + overviews_past: usize, + bar_text_styles: usize, + linked: Vec, + /// Scale bars and north arrows whose map isn't on their page, left out; overviews of a map + /// not on theirs, not drawn. + unlinked: usize, + overviews_unlinked: usize, + /// Overviews' fills (drawn as their outlines), and overviews inverted or centring their map. + overview_fills: usize, + overview_ways: usize, + /// North arrows to true north or offset from the map's. + true_north: usize, + /// Numeric scale bars of a map other than their layout's first, printing its scale. + numeric_other: usize, + /// Numeric scale bars, printing the scale in RustGIS's format. + numeric_formats: usize, + /// Scale bars as RustGIS's nearest: their style, colours, units, divisions (past RustGIS's), + /// subdivisions, fixed division values, placement, and text sizes (past a layout's). + bar_styles: usize, + bar_colors: usize, + bar_units: usize, + bar_divisions: usize, + bar_subdivisions: usize, + bar_values: usize, + bar_layout: usize, + bar_text_sizes: usize, } +mod surround; + /// `text` written into a label as it reads: its braces as parentheses, as a brace starts one of /// RustGIS's tokens (`{date}`). fn as_written(text: &str) -> String { @@ -295,9 +328,14 @@ fn read_layout(node: Node, dir: &str, title: &Title, room: usize, tally: &mut Ta // `@layout_name` prints the QGIS layout's name as far as a text holds, not the layout's. let pages = Pages::new(pages, entries.max(1), given.chars().take(MAX_TEXT).collect()); tally.titled.clear(); + tally.maps.clear(); + tally.linked.clear(); + tally.known = surround::known_maps(&items, &pages, dpi); for (_, _, item) in items { read_item(item, &pages, &mut layouts, &multiframes, dir, dpi, tally); } + // Its scale bars, north arrows and overviews, each with its map's frame on its page. + surround::link(&mut layouts, tally); // A page without a map shows the project's title as written (a frame shows its map's name). // Its text is cut to what a text holds after that, and a cut said. for (page, element, n, whole, stopped) in std::mem::take(&mut tally.titled) { @@ -496,10 +534,6 @@ fn read_item( tally.legends += 1; return; } - SCALE_BAR => { - tally.scale_bars += 1; - return; - } GROUP => { tally.groups += 1; return; @@ -517,7 +551,7 @@ fn read_item( } return; } - MAP | PICTURE | LABEL | SHAPE | POLYGON | POLYLINE => {} + MAP | PICTURE | LABEL | SHAPE | POLYGON | POLYLINE | SCALE_BAR => {} other => { tally.other += 1; if !other.is_empty() && tally.other_kinds.len() < 8 && !tally.other_kinds.iter().any(|k| k == other) { @@ -532,6 +566,10 @@ fn read_item( return; }; // A picture is counted where it would come in (one that can't is said as such). + // A scale bar whose map isn't on its page is left out first, said as that. + if kind == SCALE_BAR && !surround::bar_on_page(item, &place, tally) { + return; + } if kind != PICTURE && target.layout.elements.len() >= MAX_ELEMENTS { tally.over += elements_needed(item, kind); return; @@ -553,6 +591,7 @@ fn read_item( LABEL => label_item(item, &place, (id, &pages.name), fade, target, tally), PICTURE => picture_item(item, &place, id, dir, fade, target, tally), SHAPE => shape_item(item, &place, id, fade, target, tally), + SCALE_BAR => surround::scale_bar_item(item, &place, id, fade, target, tally), _ => line_item(item, kind, &place, id, fade, target, tally), } // Counted for what came in: a picture's said by the engine once its image reads. @@ -563,6 +602,8 @@ fn read_item( // Narrower than an element can be across or down: widened to it (a line's edges are counted // as they are drawn). let tiny = !matches!(kind, POLYLINE | POLYGON) && (place.w < crate::layout::MIN_ELEMENT_MM || place.h < crate::layout::MIN_ELEMENT_MM); + // A picture's notes wait for its image (a north arrow, also a QGIS picture, is not one). + let picture = target.layout.elements.get(first).is_some_and(|e| matches!(e.kind, ElementKind::Picture { .. })); let counts = [ (id_cut, &mut tally.cut_names, "pictures' ids longer than 100 characters, cut to fit"), (pixels, &mut tally.pixels, "picture positions in pixels, read at the layout's print resolution"), @@ -570,14 +611,14 @@ fn read_item( (tiny, &mut tally.tiny, "pictures less than 0.05 mm across or down, widened to it"), (blended, &mut tally.blended, "pictures' blending modes, drawn normally"), (data_defined, &mut tally.data_defined, "pictures with settings set by expressions, drawn as set"), - (opacity < 1.0 && matches!(kind, MAP | PICTURE), &mut tally.translucent, "translucent pictures, drawn opaque"), + (opacity < 1.0 && (kind == MAP || picture), &mut tally.translucent, "translucent pictures, drawn opaque"), (shown && !exported, &mut tally.not_exported, "pictures left out of exports, kept hidden"), ]; for (set, count, picture_note) in counts { if !(added && set) { continue; } - if kind == PICTURE { + if picture { if let Some(p) = target.pictures.last_mut() { p.notes.push(picture_note); } @@ -661,14 +702,7 @@ fn map_item(item: Node, place: &Placed, id: Option, target: &mut Project }; let crs = child(item, "crs").and_then(super::crs_of); tally.own_crs += usize::from(crs.is_some()); - for c in item.children() { - let shown = c.attribute("show") != Some("0"); - if c.has_tag_name("ComposerMapGrid") && shown { - tally.grids += 1; - } else if c.has_tag_name("ComposerMapOverview") && shown { - tally.overviews += 1; - } - } + tally.grids += item.children().filter(|c| c.has_tag_name("ComposerMapGrid") && c.attribute("show") != Some("0")).count(); if item.attribute("keepLayerSet") == Some("true") || item.attribute("followPreset") == Some("true") { tally.locked_layers += 1; } @@ -706,6 +740,11 @@ fn map_item(item: Node, place: &Placed, id: Option, target: &mut Project } let element = target.layout.add(name_or(id, "Map"), (place.x, place.y, place.w, place.h), kind); target.frames.push(LayoutFrame { element, extent, crs }); + // The surrounds and overviews of its map find its frame by its id. + if let Some(uuid) = item.attribute("uuid").map(str::trim).filter(|u| !u.is_empty()) { + tally.maps.push((uuid.to_string(), place.page, element)); + } + surround::overviews(item, place.page, element, tally); } /// A label, `id` its name and `layout` its QGIS layout's. @@ -977,7 +1016,7 @@ fn picture_item( ) { let file = item.attribute("file").map(str::trim).unwrap_or_default(); if item.attribute("mapUuid").is_some_and(|m| !m.trim().is_empty()) && item.attribute("northMode").is_some() { - tally.north_arrows += 1; + surround::north_arrow(item, place, id, fade, target, tally); return; } if file.is_empty() { @@ -1217,13 +1256,14 @@ impl Tally { pub(super) fn say(&self, report: &mut Report) { let skipped = [ (self.legends, "legends"), - (self.scale_bars, "scale bars"), - (self.north_arrows, "north arrows (pictures turned with a map)"), + (self.unlinked, "scale bars and north arrows whose map isn't on their page, or is left out"), + (self.overviews_unlinked, "map overviews of their own map or of a map not on their page"), + (self.overviews_past, &format!("map overviews past the {} a frame outlines", crate::layout::MAX_EXTENT_INDICATORS)), + (self.bar_subdivisions, "scale bars' subdivisions"), (self.tables, "attribute tables"), (self.html, "HTML frames"), (self.markers, "marker items"), (self.grids, "map grids"), - (self.overviews, "map overviews"), (self.atlases, "atlases"), (self.svg, "SVG pictures (RustGIS's pictures are PNG or JPEG)"), (self.no_picture, "pictures that name no file"), @@ -1267,9 +1307,36 @@ impl Tally { } let approximated = [ (self.groups, "item groups, their items kept on their own"), + (self.north_arrows, "north arrows (pictures turned with a map), drawn as RustGIS's arrow"), + (self.true_north, "north arrows to true north or offset from the map's, pointing to the map's north"), + (self.overview_fills, "map overviews' fills, drawn as their outlines"), + (self.overview_ways, "map overviews inverted, centring their map, blended or dashed, drawn as plain outlines"), + (self.bar_text_styles, "scale bars' text bold, italic, underlined, buffered or shadowed, drawn plain"), + (self.numeric_formats, "numeric scale bars, printing the scale in RustGIS's format (1:25,000)"), + (self.numeric_other, "numeric scale bars of a map other than their layout's first, printing the first's scale"), + (self.bar_styles, "scale bars of a double box, hollow, ticks down or across, or another style, in RustGIS's nearest"), + (self.bar_colors, "scale bars whose lines, labels and dark divisions differ in colour, drawn in one"), + ( + self.bar_units, + "scale bars in map units, degrees, yards, nautical miles, centimetres or millimetres, in RustGIS's choice of units", + ), + ( + self.bar_divisions, + &format!( + "scale bars' divisions brought within RustGIS's (1 to {}, {} before zero)", + crate::layout::MAX_SCALE_DIVISIONS, + crate::layout::MAX_SCALE_BEFORE_ZERO + ), + ), + (self.bar_values, "scale bars' fixed values of a division, chosen anew to fit their box"), + ( + self.bar_layout, + "scale bars' heights, line widths, alignment in their box or labels over their divisions' middles, as RustGIS draws them", + ), + (self.bar_text_sizes, "scale bars' text sizes outside 4 to 100 pt, drawn at the nearest"), (self.map_backgrounds, "map items' background colours, drawn as the map's own"), (self.locked_layers, "map items showing a set of layers or a map theme of their own, showing the map's layers"), - (self.turned_items, "turned maps and shapes, drawn upright"), + (self.turned_items, "turned maps, shapes, scale bars and north arrows, drawn upright"), (self.blended, "items' blending modes, drawn normally"), (self.translucent, "translucent maps, drawn opaque"), (self.data_defined, "items with settings set by expressions, drawn as set"), diff --git a/crates/map/src/qgis/layout/surround.rs b/crates/map/src/qgis/layout/surround.rs new file mode 100644 index 0000000000..fd5c6650fc --- /dev/null +++ b/crates/map/src/qgis/layout/surround.rs @@ -0,0 +1,327 @@ +//! A QGIS layout's surrounds tied to a map (piece 12b of #882): scale bars, north arrows and map +//! overviews, each linked, once its QGIS layout is read, to the frame its map item became on its +//! page. One whose map isn't on its page is left out, said. + +use super::*; +use crate::layout::{ + ExtentIndicator, LAYOUT_TEXT_SIZE, MAX_EXTENT_INDICATORS, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DIVISIONS, MAX_UNIT_LABEL_CHARS, +}; +use crate::layout::{ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits}; + +/// What an element links to its map item as. +pub(super) enum Link { + /// A scale bar or a north arrow: its `frame`. + Surround, + /// A numeric scale bar, a text printing `{scale}`: the layout's first frame's scale. + Numeric, + /// A map overview on the element (a frame): an extent indicator of its map's frame. + Overview { color: Rgba, width: f64 }, +} + +/// An element waiting for the frame of a map item (by its `uuid`) on its page. +pub(super) struct Linked { + pub(super) page: usize, + pub(super) element: u32, + pub(super) map: String, + pub(super) link: Link, +} + +/// The QGIS layout's map items that will come in, by (uuid, layout): those with an id, an extent +/// and a place, looked at before its items are read, so that a surround whose map isn't on its +/// page is left out (said) before anything else of it is counted. +pub(super) fn known_maps(items: &[(f64, usize, Node)], pages: &Pages, dpi: f64) -> Vec<(String, usize)> { + items + .iter() + .map(|(_, _, n)| *n) + .filter(|n| n.attribute("type") == Some(MAP) && child(*n, "Extent").is_some()) + .filter_map(|n| { + let uuid = n.attribute("uuid").map(str::trim).filter(|u| !u.is_empty())?; + // Where it lands, counted nowhere: its own reading counts it. + let place = placed(n, pages, dpi, &mut Tally::default())?; + Some((uuid.to_string(), place.page)) + }) + .collect() +} + +/// Whether map item `uuid` comes in on layout `page`. +fn on_page(tally: &Tally, uuid: &str, page: usize) -> bool { + !uuid.is_empty() && tally.known.iter().any(|(u, p)| u == uuid && *p == page) +} + +/// Links each element of the QGIS layout just read to the frame its map item became on its page +/// (`tally.maps`); one whose map was left out after all (a full layout) is left out too, said. +pub(super) fn link(layouts: &mut [ProjectLayout], tally: &mut Tally) { + let maps = std::mem::take(&mut tally.maps); + for l in std::mem::take(&mut tally.linked) { + let Some(target) = layouts.get_mut(l.page) else { continue }; + let frame = (!l.map.is_empty()).then(|| maps.iter().find(|(m, page, _)| *m == l.map && *page == l.page)).flatten().map(|m| m.2); + match (l.link, frame) { + (Link::Overview { color, width }, Some(of)) if of != l.element => { + if let Some(e) = target.layout.element_mut(l.element) { + let mut shown = e.kind.extent_indicators(); + // A frame outlines no more than a layout keeps; the others said. + if shown.len() >= MAX_EXTENT_INDICATORS { + tally.overviews_past += 1; + continue; + } + shown.push(ExtentIndicator { of, color, width }); + e.kind.set_extent_indicators(shown); + } + } + (Link::Overview { .. }, _) => tally.overviews_unlinked += 1, + (Link::Surround, Some(of)) => { + if let Some(e) = target.layout.element_mut(l.element) + && let ElementKind::ScaleBar { frame, .. } | ElementKind::NorthArrow { frame, .. } = &mut e.kind + { + *frame = of; + } + } + (Link::Numeric, Some(of)) => { + // `{scale}` prints the layout's first frame's scale. + tally.numeric_other += usize::from(target.layout.first_frame() != Some(of)); + } + (Link::Surround | Link::Numeric, None) => { + target.layout.remove(l.element); + tally.unlinked += 1; + } + } + } +} + +/// A map item's overviews (`ComposerMapOverview`), each an extent indicator of the frame its map +/// (`frameMap`) became, linked once the layout is read: its outline's colour and width, or, with +/// no outline, its fill's colour opaque. +pub(super) fn overviews(item: Node, page: usize, element: u32, tally: &mut Tally) { + let own = item.attribute("uuid").map(str::trim).unwrap_or_default(); + for o in item.children().filter(|c| c.has_tag_name("ComposerMapOverview") && c.attribute("show") != Some("0")) { + let map = o.attribute("frameMap").map(str::trim).unwrap_or_default().to_string(); + // Of its own map, or of one not on its page: not drawn, said, and nothing else of it. + if map == own || !on_page(tally, &map, page) { + tally.overviews_unlinked += 1; + continue; + } + let (fill, outline, width, dash) = fill_of(o, &|c| c, &mut tally.notes); + let (color, width) = if outline.a() > 0 && width > 0.0 { (outline, width) } else { (fill.with_alpha(255), INDICATOR_WIDTH) }; + tally.overview_fills += usize::from(fill.a() > 0); + tally.overview_ways += usize::from( + o.attribute("inverted") == Some("1") + || o.attribute("centered") == Some("1") + || num(o, "blendMode").is_some_and(|b| b != 0.0) + || dash.is_some(), + ); + tally.linked.push(Linked { page, element, map, link: Link::Overview { color, width } }); + } +} + +/// A picture following a map's north (`mapUuid`, `northMode`) as a north arrow linked to that +/// map's frame. +pub(super) fn north_arrow( + item: Node, + place: &Placed, + id: Option, + fade: impl Fn(Rgba) -> Rgba, + target: &mut ProjectLayout, + tally: &mut Tally, +) { + let map = item.attribute("mapUuid").map(str::trim).unwrap_or_default().to_string(); + if !on_page(tally, &map, place.page) { + tally.unlinked += 1; + return; + } + if target.layout.elements.len() >= MAX_ELEMENTS { + tally.over += 1; + return; + } + // QGIS's arrow is a picture (an SVG); RustGIS draws its own, in ink faded as the item is. + tally.north_arrows += 1; + tally.turned_items += usize::from(place.turn.rem_euclid(360.0) != 0.0); + // Grid north 0 is the map's; true north 1 and an offset turn it from there. + tally.true_north += usize::from(num(item, "northMode").is_some_and(|m| m != 0.0) || num(item, "northOffset").is_some_and(|o| o != 0.0)); + let mut kind = ElementKind::north_arrow(0); + if let ElementKind::NorthArrow { fill, outline, .. } = &mut kind { + (*fill, *outline) = (fade(*fill), fade(*outline)); + } + let element = target.layout.add(name_or(id, "North arrow"), (place.x, place.y, place.w, place.h), kind); + if let Some(e) = target.layout.element_mut(element) { + e.background = backdrop(item, true, place.dpi, &fade); + } + tally.linked.push(Linked { page: place.page, element, map, link: Link::Surround }); +} + +/// Whether a scale bar's map comes in on its page: one whose map doesn't is left out, said, and +/// nothing else of it counted. +pub(super) fn bar_on_page(item: Node, place: &Placed, tally: &mut Tally) -> bool { + let on = on_page(tally, item.attribute("mapUuid").map(str::trim).unwrap_or_default(), place.page); + tally.unlinked += usize::from(!on); + on +} + +/// A scale bar, linked to its map's frame; a numeric one (`1:25,000`) as a text printing the +/// scale. Its look as RustGIS's nearest, said where it differs. +pub(super) fn scale_bar_item( + item: Node, + place: &Placed, + id: Option, + fade: impl Fn(Rgba) -> Rgba, + target: &mut ProjectLayout, + tally: &mut Tally, +) { + let map = item.attribute("mapUuid").map(str::trim).unwrap_or_default().to_string(); + let (size, text_color, font) = text_style(item, tally); + let turned = place.turn.rem_euclid(360.0) != 0.0; + let style = item.attribute("style").map(str::trim).unwrap_or("Single Box"); + let name = name_or(id, "Scale bar"); + let bounds = (place.x, place.y, place.w, place.h); + if style == "Numeric" { + let mut kind = ElementKind::text("{scale}", size, fade(text_color), false); + if let ElementKind::Text { align, valign, font_name, rotation, .. } = &mut kind { + // Across: left 0, centre 1, right 2; QGIS centres it down its box. + *align = match num(item, "alignment").map_or(0, |a| a as i64) { + 1 => TextAlign::Center, + 2 => TextAlign::Right, + _ => TextAlign::Left, + }; + *valign = TextVAlign::Middle; + *font_name = font; + *rotation = crate::layout::rotation(place.turn); + } + let element = target.layout.add(name, bounds, kind); + if let Some(e) = target.layout.element_mut(element) { + e.background = backdrop(item, true, place.dpi, &fade); + } + // QGIS's number format (`1:25'000.5`) as RustGIS's (`1:25,000`), said. + tally.numeric_formats += 1; + tally.linked.push(Linked { page: place.page, element, map, link: Link::Numeric }); + return; + } + let (style, exact) = match style { + "Single Box" => (ScaleBarStyle::Alternating, true), + "Line Ticks Up" => (ScaleBarStyle::Line, true), + "stepped" => (ScaleBarStyle::Stepped, true), + "Line Ticks Middle" | "Line Ticks Down" => (ScaleBarStyle::Line, false), + // A double box, a hollow bar and a style of a plugin: RustGIS's alternating bar. + _ => (ScaleBarStyle::Alternating, false), + }; + tally.bar_styles += usize::from(!exact); + tally.turned_items += usize::from(turned); + let line = style != ScaleBarStyle::Alternating; + // Its lines' colour (a line's), its dark divisions' and its light ones'. + let stroke = symbol_color(item, "lineSymbol").or_else(|| child(item, "strokeColor").and_then(rgba_of)).unwrap_or(Rgba::rgb(0, 0, 0)); + let dark = symbol_color(item, "fillSymbol1").or_else(|| child(item, "fillColor").and_then(rgba_of)).unwrap_or(Rgba::rgb(0, 0, 0)); + let light = + symbol_color(item, "fillSymbol2").or_else(|| child(item, "fillColor2").and_then(rgba_of)).unwrap_or(Rgba::rgb(255, 255, 255)); + // RustGIS draws a bar's lines, dark divisions and labels in one colour: its dark divisions' + // (a line's lines'); another in QGIS's is drawn in it, said. + let color = if line { stroke } else { dark }; + // Its ticks' (a line's divisions' and subdivisions') colours too. + let ticks = ["divisionLineSymbol", "subdivisionLineSymbol"].iter().filter_map(|t| symbol_color(item, t)).any(|c| line && c != color); + tally.bar_colors += usize::from(text_color != color || (!line && stroke != color) || ticks); + let (units, abbr) = match item.attribute("unitType").map(str::trim).unwrap_or("meters") { + "meters" | "m" => (ScaleUnits::Meters, Some("m")), + "km" | "kilometers" => (ScaleUnits::Kilometers, Some("km")), + "feet" | "ft" => (ScaleUnits::Feet, Some("ft")), + "mi" | "miles" => (ScaleUnits::Miles, Some("mi")), + // Map units, degrees, yards, nautical miles, centimetres, millimetres: RustGIS's choice + // (millimetres to kilometres), said. + _ => (ScaleUnits::Auto, None), + }; + tally.bar_units += usize::from(abbr.is_none()); + // The label QGIS prints for its units: none where it is RustGIS's abbreviation, and none in + // RustGIS's choice of units (its own abbreviation, for what it counts in). + let label = item.attribute("unitLabelString").unwrap_or_default(); + let unit_label = (abbr.is_some() && Some(label) != abbr).then(|| { + tally.cut_texts += usize::from(label.chars().nth(MAX_UNIT_LABEL_CHARS).is_some()); + tally.braces += usize::from(label.contains(['{', '}'])); + as_written(&label.chars().take(MAX_UNIT_LABEL_CHARS).collect::()) + }); + let count = |k: &str, max: usize, least: usize| { + let n = num(item, k).map_or(least as f64, f64::trunc); + (n.clamp(least as f64, max as f64) as usize, !(least as f64..=max as f64).contains(&n)) + }; + let (divisions, more) = count("numSegments", MAX_SCALE_DIVISIONS, 1); + let (before, more_before) = count("numSegmentsLeft", MAX_SCALE_BEFORE_ZERO, 0); + tally.bar_divisions += usize::from(more || more_before); + // Subdivisions of its divisions (drawn by QGIS's line styles): left out, said. + tally.bar_subdivisions += usize::from(line && num(item, "numSubdivisions").is_some_and(|n| n > 1.0)); + // A fixed value a division (`segmentSizeMode` 0): RustGIS picks its own to fit the bar's box. + tally.bar_values += usize::from(num(item, "segmentSizeMode").is_none_or(|m| m == 0.0)); + // Its labels over the middle of their division (1), its bar in the middle or right of its box, + // its height and its lines' width other than RustGIS's (3 mm, 0.3 mm): drawn as RustGIS draws + // a bar. + let width = symbol_number(item, "lineSymbol", "line_width").or_else(|| num(item, "outlineWidth")); + tally.bar_layout += usize::from( + num(item, "labelHorizontalPlacement").is_some_and(|p| p != 0.0) + || num(item, "alignment").is_some_and(|a| a != 0.0) + || num(item, "height").is_some_and(|h| (h - 3.0).abs() > 1e-9) + || width.is_some_and(|w| (w - 0.3).abs() > 1e-9), + ); + let mut kind = ElementKind::scale_bar(0); + if let ElementKind::ScaleBar { + units: u, + divisions: d, + style: s, + color: c, + fill, + text_size, + divisions_before_zero, + label_position, + unit_label: ul, + fit, + font_name, + .. + } = &mut kind + { + (*u, *d, *s, *c, *fill) = (units, divisions, style, fade(color), fade(light)); + *text_size = size.clamp(*LAYOUT_TEXT_SIZE.start(), *LAYOUT_TEXT_SIZE.end()); + *divisions_before_zero = before; + *label_position = if num(item, "labelVerticalPlacement").is_some_and(|p| p == 1.0) { + ScaleLabelPosition::Below + } else { + ScaleLabelPosition::Above + }; + *ul = unit_label; + *fit = ScaleBarFit::AdjustDivisionValue; + *font_name = font; + } + tally.bar_text_sizes += usize::from(!LAYOUT_TEXT_SIZE.contains(&size)); + let element = target.layout.add(name, bounds, kind); + if let Some(e) = target.layout.element_mut(element) { + e.background = backdrop(item, true, place.dpi, &fade); + } + tally.linked.push(Linked { page: place.page, element, map, link: Link::Surround }); +} + +/// A surround's text style (`text-style`): its size in points, colour and installed font; its +/// bold, italic, underline, buffer and shadow, which a scale bar's text lacks, counted. +fn text_style(item: Node, tally: &mut Tally) -> (f64, Rgba, Option) { + let Some(s) = child(item, "text-style") else { return (10.0, Rgba::rgb(0, 0, 0), None) }; + let (bold, italic) = labels::bold_italic(s); + let styled = bold + || italic + || s.attribute("fontUnderline") == Some("1") + || s.attribute("fontStrikeout") == Some("1") + || child(s, "text-buffer").is_some_and(|n| n.attribute("bufferDraw") == Some("1")) + || child(s, "shadow").is_some_and(|n| n.attribute("shadowDraw") == Some("1")) + || child(s, "background").is_some_and(|n| n.attribute("shapeDraw") == Some("1")); + tally.bar_text_styles += usize::from(styled); + let unit = s.attribute("fontSizeUnit").unwrap_or("Point"); + let size = labels::points(num(s, "fontSize").unwrap_or(10.0), unit, "scale bar text sizes", "", &mut tally.notes); + let opacity = num(s, "textOpacity").unwrap_or(1.0).clamp(0.0, 1.0); + let c = s.attribute("textColor").and_then(color).unwrap_or(Rgba::rgb(0, 0, 0)); + let c = c.with_alpha((f64::from(c.a()) * opacity).round() as u8); + let font = s.attribute("fontFamily").map(str::trim).filter(|f| !f.is_empty() && !annotation::generic(f)).map(str::to_string); + (size, c, font) +} + +/// A number of a symbol held under `tag` (its first layer's property `key`). +fn symbol_number(item: Node, tag: &str, key: &str) -> Option { + let layer = child(item, tag)?.descendants().find(|d| d.has_tag_name("layer"))?; + super::super::prop(&super::super::props(layer), key)?.trim().parse::().ok().filter(|v| v.is_finite()) +} + +/// The colour of a symbol held under `tag` (its first layer's fill or line colour). +fn symbol_color(item: Node, tag: &str) -> Option { + let layer = child(item, tag)?.descendants().find(|d| d.has_tag_name("layer"))?; + let props = super::super::props(layer); + super::super::prop(&props, "color").or_else(|| super::super::prop(&props, "line_color")).and_then(color) +} diff --git a/crates/map/src/qgis/layout_surround_tests.rs b/crates/map/src/qgis/layout_surround_tests.rs new file mode 100644 index 0000000000..86cd9ebb26 --- /dev/null +++ b/crates/map/src/qgis/layout_surround_tests.rs @@ -0,0 +1,348 @@ +//! A QGIS layout's surrounds tied to a map (piece 12b of #882): scale bars, north arrows and map +//! overviews, each showing the frame its map item became, written in the shapes QGIS writes them. + +use super::*; +use crate::layout::{ElementKind, ExtentIndicator, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, TextAlign}; + +fn read(text: &str, report: &mut Report) -> Project { + super::read_project(text, "/data/proj", &mut |_, _| Err((super::IMAGE_UNOPENED, false)), report).unwrap() +} + +fn said(report: &Report, part: &str) -> bool { + report.notes.iter().any(|n| n.text.contains(part)) +} + +const PAGE: &str = r#""#; +const TWO_PAGES: &str = r#""#; + +/// A map item of `uuid` at `y` down the layout. +fn map(uuid: &str, y: f64, z: u32, more: &str) -> String { + format!( + r#"{more}"# + ) +} + +/// A scale bar of `map` with these attributes and children. +fn bar(map: &str, attrs: &str, children: &str) -> String { + format!( + r#"{children}"# + ) +} + +fn layout(pages: &str, items: &str) -> String { + format!( + r#"TEPSG:2056{pages}{items}"# + ) +} + +/// The colours of a QGIS 4 scale bar's lines and divisions. +const BAR_COLOURS: &str = r#""#; + +fn bars(l: &crate::layout::Layout) -> Vec<&crate::layout::Element> { + l.elements.iter().filter(|e| matches!(e.kind, ElementKind::ScaleBar { .. })).collect() +} + +/// A scale bar fitted to its box comes in as RustGIS's, showing its map's frame (drawn above it +/// in QGIS's order, so read after it), with nothing said. +#[test] +fn a_scale_bar_comes_in_showing_its_maps_frame() { + let attrs = r#"style="Single Box" unitType="km" unitLabelString="km" numSegments="3" numSegmentsLeft="1" numSubdivisions="1" segmentSizeMode="1" labelVerticalPlacement="1" alignment="0" height="3""#; + let qgs = layout(PAGE, &format!("{}{}", bar("{m}", attrs, BAR_COLOURS), map("{m}", 10.0, 2, ""))); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + let l = &p.layouts[0].layout; + let frame = l.first_frame().unwrap(); + let b = bars(l); + assert_eq!(b.len(), 1); + let ElementKind::ScaleBar { + frame: f, + units, + divisions, + style, + divisions_before_zero, + label_position, + unit_label, + text_size, + fit, + font_name, + color, + fill, + .. + } = &b[0].kind + else { + panic!("not a scale bar") + }; + assert_eq!(*f, frame); + assert_eq!((*units, *divisions, *style, *divisions_before_zero), (ScaleUnits::Kilometers, 3, ScaleBarStyle::Alternating, 1)); + assert_eq!((*label_position, unit_label.clone(), *fit), (ScaleLabelPosition::Below, None, ScaleBarFit::AdjustDivisionValue)); + assert!((text_size - 9.0).abs() < 1e-9); + assert_eq!(font_name.as_deref(), Some("DejaVu Sans")); + assert_eq!((*color, *fill), (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 255, 255))); + assert!(report.notes.is_empty(), "{:?}", report.notes); +} + +/// QGIS's styles as RustGIS's nearest: a single box, ticks up and a stepped line as they are; a +/// double box, a hollow bar, ticks down or across and another style said. +#[test] +fn scale_bar_styles_are_rustgis_nearest() { + let styles = [ + ("Single Box", ScaleBarStyle::Alternating), + ("Line Ticks Up", ScaleBarStyle::Line), + ("stepped", ScaleBarStyle::Stepped), + ("Double Box", ScaleBarStyle::Alternating), + ("hollow", ScaleBarStyle::Alternating), + ("Line Ticks Middle", ScaleBarStyle::Line), + ("Line Ticks Down", ScaleBarStyle::Line), + ("Fancy", ScaleBarStyle::Alternating), + ]; + let items: String = styles.iter().map(|(s, _)| bar("{m}", &format!(r#"style="{s}" segmentSizeMode="1""#), BAR_COLOURS)).collect(); + let mut report = Report::default(); + let p = read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &items)), &mut report); + // Of the same height, QGIS draws them last listed first. + let got: Vec = bars(&p.layouts[0].layout) + .into_iter() + .rev() + .map(|e| match e.kind { + ElementKind::ScaleBar { style, .. } => style, + _ => ScaleBarStyle::Alternating, + }) + .collect(); + assert_eq!(got, styles.map(|(_, s)| s)); + assert!( + said(&report, "scale bars of a double box, hollow, ticks down or across, or another style, in RustGIS's nearest (5)"), + "{:?}", + report.notes + ); +} + +/// Units RustGIS counts in come in as they are, their label kept where it isn't RustGIS's +/// abbreviation; others are RustGIS's choice, said; divisions past RustGIS's, a fixed value a +/// division and subdivisions are said. +#[test] +fn scale_bar_units_and_divisions_are_kept_or_said() { + let one = |attrs: &str| { + let mut report = Report::default(); + let p = read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", attrs, BAR_COLOURS))), &mut report); + let kind = bars(&p.layouts[0].layout)[0].kind.clone(); + (kind, report) + }; + let (kind, report) = one(r#"style="Single Box" segmentSizeMode="1" unitType="km" unitLabelString="Kilometres""#); + assert!(matches!(kind, ElementKind::ScaleBar { units: ScaleUnits::Kilometers, unit_label: Some(ref l), .. } if l == "Kilometres")); + assert!(report.notes.is_empty(), "{:?}", report.notes); + let (kind, report) = one(r#"style="Single Box" segmentSizeMode="1" unitType="nautical miles" unitLabelString="NM""#); + assert!(matches!(kind, ElementKind::ScaleBar { units: ScaleUnits::Auto, .. })); + assert!(said(&report, "in RustGIS's choice of units (1)"), "{:?}", report.notes); + let (kind, report) = one(r#"style="Line Ticks Up" numSegments="20" numSegmentsLeft="4" numSubdivisions="3""#); + assert!(matches!(kind, ElementKind::ScaleBar { divisions: 10, divisions_before_zero: 2, .. })); + assert!(said(&report, "scale bars' divisions brought within RustGIS's (1 to 10, 2 before zero) (1)"), "{:?}", report.notes); + assert!(said(&report, "scale bars' subdivisions (1)"), "{:?}", report.notes); + assert!(said(&report, "scale bars' fixed values of a division, chosen anew to fit their box (1)"), "{:?}", report.notes); +} + +/// A scale bar whose lines, labels and dark divisions differ in colour is drawn in its dark +/// divisions', said. +#[test] +fn a_scale_bar_of_several_colours_is_said() { + let colours = r#""#; + let mut report = Report::default(); + let p = + read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", r#"style="Single Box" segmentSizeMode="1""#, colours))), &mut report); + assert!(matches!(bars(&p.layouts[0].layout)[0].kind, ElementKind::ScaleBar { color, .. } if color == Rgba::rgb(200, 0, 0))); + assert!(said(&report, "scale bars whose lines, labels and dark divisions differ in colour, drawn in one (1)"), "{:?}", report.notes); +} + +/// A numeric scale bar is a text printing the scale; one of a map other than the layout's first +/// prints the first's, said. +#[test] +fn a_numeric_scale_bar_prints_the_scale() { + // `a` drawn first (lowest): the layout's first frame. + let items = format!("{}{}{}", map("{a}", 10.0, 0, ""), map("{b}", 115.0, 1, ""), bar("{a}", r#"style="Numeric" alignment="1""#, "")); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + let text = p.layouts[0].layout.elements.iter().find_map(|e| match &e.kind { + ElementKind::Text { text, align, .. } => Some((text.clone(), *align)), + _ => None, + }); + assert_eq!(text, Some(("{scale}".to_string(), TextAlign::Center))); + assert!(said(&report, "numeric scale bars, printing the scale in RustGIS's format (1:25,000) (1)"), "{:?}", report.notes); + assert!(!said(&report, "numeric scale bars of a map other"), "{:?}", report.notes); + let items = format!("{}{}{}", map("{a}", 10.0, 0, ""), map("{b}", 115.0, 1, ""), bar("{b}", r#"style="Numeric""#, "")); + let mut report = Report::default(); + read(&layout(PAGE, &items), &mut report); + assert!( + said(&report, "numeric scale bars of a map other than their layout's first, printing the first's scale (1)"), + "{:?}", + report.notes + ); +} + +/// A picture following a map's north comes in as a north arrow showing that map's frame, said as +/// RustGIS's arrow; one to true north or offset is said too. +#[test] +fn a_north_arrow_shows_its_maps_frame() { + let arrow = |attrs: &str| { + format!( + r#""# + ) + }; + let mut report = Report::default(); + let p = read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &arrow(r#"northMode="0" northOffset="0""#))), &mut report); + let l = &p.layouts[0].layout; + let frame = l.first_frame().unwrap(); + assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::NorthArrow { frame: f, .. } if f == frame))); + assert!(said(&report, "north arrows (pictures turned with a map), drawn as RustGIS's arrow (1)"), "{:?}", report.notes); + assert!(!said(&report, "true north"), "{:?}", report.notes); + let mut report = Report::default(); + read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &arrow(r#"northMode="1" northOffset="5""#))), &mut report); + assert!(said(&report, "north arrows to true north or offset from the map's, pointing to the map's north (1)"), "{:?}", report.notes); +} + +/// A scale bar or north arrow whose map is on another page, or names none, is left out, said as +/// only that (nothing else of it). +#[test] +fn a_surround_without_its_map_on_its_page_is_left_out() { + let arrow = r#""#; + let items = format!( + "{}{}{}{arrow}", + map("{m}", 230.0, 0, ""), + bar("{m}", r#"style="Double Box" unitType="yd""#, BAR_COLOURS), + bar("", r#"style="Single Box""#, BAR_COLOURS) + ); + let mut report = Report::default(); + let p = read(&layout(TWO_PAGES, &items), &mut report); + assert!(p.layouts.iter().all(|l| bars(&l.layout).is_empty())); + assert!(p.layouts.iter().flat_map(|l| &l.layout.elements).all(|e| !matches!(e.kind, ElementKind::NorthArrow { .. }))); + let texts: Vec<&str> = + report.notes.iter().filter(|n| !n.text.starts_with("print layouts of several pages")).map(|n| n.text.as_str()).collect(); + assert_eq!(texts, ["its print layouts' scale bars and north arrows whose map isn't on their page, or is left out (3)"]); +} + +/// A north arrow's own settings are said as a north arrow's, not given to a picture: a hidden, +/// translucent one is kept hidden and drawn faded; a turned scale bar and arrow are said upright, +/// and a turned numeric scale turns. +#[test] +fn a_north_arrows_settings_are_its_own() { + let arrow = r#""#; + let numeric = r#""#; + let items = format!("{}{arrow}{numeric}", map("{m}", 10.0, 0, "")); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + let l = &p.layouts[0]; + assert!(l.pictures.is_empty()); + let a = l.layout.elements.iter().find(|e| matches!(e.kind, ElementKind::NorthArrow { .. })).unwrap(); + assert!(!a.visible); + assert!(matches!(a.kind, ElementKind::NorthArrow { fill, .. } if fill.a() < 200)); + let n = l.layout.elements.iter().find(|e| matches!(e.kind, ElementKind::Text { .. })).unwrap(); + assert!(matches!(n.kind, ElementKind::Text { rotation, .. } if rotation.abs() > 1.0)); + assert!(said(&report, "turned maps, shapes, scale bars and north arrows, drawn upright (1)"), "{:?}", report.notes); + assert!(!said(&report, "translucent"), "{:?}", report.notes); +} + +/// A scale bar in units RustGIS doesn't count in prints RustGIS's abbreviation, not QGIS's label; +/// its text's bold or buffer, and line widths of its own, are said. +#[test] +fn a_scale_bar_in_other_units_prints_rustgis_abbreviation() { + let attrs = r#"style="Single Box" segmentSizeMode="1" unitType="nautical miles" unitLabelString="NM""#; + let mut report = Report::default(); + let p = read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", attrs, BAR_COLOURS))), &mut report); + assert!(matches!(bars(&p.layouts[0].layout)[0].kind, ElementKind::ScaleBar { units: ScaleUnits::Auto, unit_label: None, .. })); + let styled = bar("{m}", r#"style="Single Box" segmentSizeMode="1" outlineWidth="1.2""#, BAR_COLOURS) + .replace(r#"textColor="0,0,0,255"/>"#, r#"textColor="0,0,0,255" fontWeight="700">"#); + let mut report = Report::default(); + read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &styled)), &mut report); + assert!(said(&report, "scale bars' text bold, italic, underlined, buffered or shadowed, drawn plain (1)"), "{:?}", report.notes); + assert!(said(&report, "scale bars' heights, line widths,"), "{:?}", report.notes); +} + +/// A map overview is an extent indicator of its map's frame, in its outline's colour and width; +/// its fill, and an overview of a map not on its page, said. +#[test] +fn a_map_overview_outlines_its_maps_frame() { + let symbol = |fill: &str| { + format!( + r#""# + ) + }; + let overview = |of: &str, fill: &str| { + format!(r#"{}"#, symbol(fill)) + }; + let items = format!("{}{}", map("{main}", 10.0, 1, ""), map("{ov}", 115.0, 0, &overview("{main}", "255,0,0,0"))); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + let l = &p.layouts[0].layout; + // The overview map drawn first (lowest), the main map over it. + let frames: Vec<&crate::layout::Element> = l.elements.iter().filter(|e| matches!(e.kind, ElementKind::MapFrame { .. })).collect(); + let shown = frames[0].kind.extent_indicators(); + assert_eq!(shown.len(), 1); + assert!(frames[1].kind.extent_indicators().is_empty()); + let ExtentIndicator { of, color, width } = shown[0]; + assert_eq!((of, color), (frames[1].id, Rgba::rgb(0, 0, 200))); + assert!(width > 0.0); + assert!(report.notes.is_empty(), "{:?}", report.notes); + // A filled overview, and one of a map on another page. + let items = format!( + "{}{}{}", + map("{main}", 10.0, 0, ""), + map("{ov}", 115.0, 0, &(overview("{main}", "255,0,0,80") + &overview("{far}", "255,0,0,0"))), + map("{far}", 230.0, 0, "") + ); + let mut report = Report::default(); + read(&layout(TWO_PAGES, &items), &mut report); + assert!(said(&report, "map overviews' fills, drawn as their outlines (1)"), "{:?}", report.notes); + assert!(said(&report, "map overviews of their own map or of a map not on their page (1)"), "{:?}", report.notes); +} + +/// A scale bar past a full layout is counted with the elements it leaves out. +#[test] +fn a_scale_bar_past_a_full_layout_is_counted() { + let mut items = map("{m}", 10.0, 0, ""); + for i in 0..499 { + items.push_str(&format!(r#""#)); + } + items + .push_str(&bar("{m}", r#"style="Single Box" segmentSizeMode="1" zValue="5""#, BAR_COLOURS).replace(r#"zValue="1" style"#, "style")); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + assert!(bars(&p.layouts[0].layout).is_empty()); + assert!(said(&report, "elements past the 500 a layout keeps (1)"), "{:?}", report.notes); +} + +/// The corpus's sheet of surrounds, as QGIS 4.4 wrote it: its scale bars, numeric scale and north +/// arrow show the main map's frame, its overview map outlines it. +#[test] +fn the_corpus_surrounds_show_the_main_map() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("testdata/qgis/generated/qgs"); + let text = std::fs::read_to_string(root.join("layout-surrounds.qgs")).unwrap(); + let mut report = Report::default(); + let p = super::read_project(&text, &root.to_string_lossy(), &mut |_, _| Err((super::IMAGE_UNOPENED, false)), &mut report).unwrap(); + let l = &p.layouts[0].layout; + let frames: Vec<&crate::layout::Element> = l.elements.iter().filter(|e| matches!(e.kind, ElementKind::MapFrame { .. })).collect(); + assert_eq!(frames.len(), 2); + // The main map is the larger. + let (main, overview) = if frames[0].w > frames[1].w { (frames[0], frames[1]) } else { (frames[1], frames[0]) }; + let styles: Vec = bars(l) + .iter() + .filter_map(|e| match e.kind { + ElementKind::ScaleBar { frame, style, units: ScaleUnits::Meters, divisions: 4, .. } if frame == main.id => Some(style), + _ => None, + }) + .collect(); + assert_eq!(styles.len(), 3, "{:?}", l.elements); + for s in [ScaleBarStyle::Alternating, ScaleBarStyle::Line, ScaleBarStyle::Stepped] { + assert!(styles.contains(&s)); + } + assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::NorthArrow { frame, .. } if frame == main.id))); + assert!(l.elements.iter().any(|e| matches!(&e.kind, ElementKind::Text { text, .. } if text == "{scale}"))); + let shown = overview.kind.extent_indicators(); + assert_eq!(shown.len(), 1); + assert_eq!((shown[0].of, shown[0].color), (main.id, Rgba::rgb(200, 0, 0))); + // What it says: the north arrow and the numeric scale's format, nothing more. + let texts: Vec<&str> = report.notes.iter().map(|n| n.text.as_str()).collect(); + assert_eq!( + texts, + [ + "its print layouts' north arrows (pictures turned with a map), drawn as RustGIS's arrow (1)", + "its print layouts' numeric scale bars, printing the scale in RustGIS's format (1:25,000) (1)" + ] + ); +} diff --git a/crates/map/src/qgis/layout_tests.rs b/crates/map/src/qgis/layout_tests.rs index a4954a6677..37bd57750d 100644 --- a/crates/map/src/qgis/layout_tests.rs +++ b/crates/map/src/qgis/layout_tests.rs @@ -126,10 +126,14 @@ fn qgis_layout_items_without_a_place_are_noted() { let mut report = Report::default(); let p = super::read_project(&text, &root.to_string_lossy(), &mut |_, _| Err((super::IMAGE_UNOPENED, false)), &mut report).unwrap(); assert_eq!(p.layouts.len(), 1); + // Its scale bar and north arrow come in, showing its map's frame. + let l = &p.layouts[0].layout; + let frame = l.first_frame().unwrap(); + assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::ScaleBar { frame: f, .. } if f == frame))); + assert!(l.elements.iter().any(|e| matches!(e.kind, ElementKind::NorthArrow { frame: f, .. } if f == frame))); for part in [ "legends (1)", - "scale bars (1)", - "north arrows (pictures turned with a map) (1)", + "north arrows (pictures turned with a map), drawn as RustGIS's arrow (1)", "attribute tables (1)", "HTML frames (1)", "marker items (1)", @@ -529,9 +533,8 @@ fn merged_notes_keep_their_count_past_the_cap() { assert_eq!((closing.count, closing.text.as_str()), (4, "4 more note(s) not listed"), "{closing:?}"); } -/// Pictures that never come in as elements (north arrows, SVGs, no file, a path that doesn't -/// check) aren't counted past a full layout: they are said as what they are; a picture that -/// would come in is. +/// Pictures that never come in as elements (SVGs, no file, a path that doesn't check) aren't +/// counted past a full layout: they are said as what they are; a picture that would come in is. #[test] fn a_full_layout_counts_only_pictures_that_would_come_in() { let mut items = String::new(); @@ -552,8 +555,9 @@ fn a_full_layout_counts_only_pictures_that_would_come_in() { let qgs = format!(r#"{page}{items}"#); let mut report = Report::default(); read(&qgs, &mut report); + // The north arrows' map isn't in the layout: they are said as that, not counted past it. assert!(!said(&report, "elements past the 500"), "{:?}", report.notes); - assert!(said(&report, "north arrows (pictures turned with a map) (3)"), "{:?}", report.notes); + assert!(said(&report, "scale bars and north arrows whose map isn't on their page, or is left out (3)"), "{:?}", report.notes); assert!(said(&report, "pictures that can't be read (1;"), "{:?}", report.notes); // What doesn't come in isn't said as drawn otherwise. assert!(!said(&report, "blending modes"), "{:?}", report.notes); diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 04ce836d93..5ecfa5c71f 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -15,6 +15,8 @@ mod expr; mod labels; mod layout; #[cfg(test)] +mod layout_surround_tests; +#[cfg(test)] mod layout_tests; mod raster; mod renderer; diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 6ed04a936c..e322004508 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -1152,7 +1152,7 @@ fn every_corpus_file_reads() { } } let projects = files("generated/qgs", &["qgs", "qgz"]); - assert_eq!(projects.len(), 39, "project corpus changed: {projects:?}"); + assert_eq!(projects.len(), 40, "project corpus changed: {projects:?}"); for path in &projects { let bytes = std::fs::read(path).unwrap(); let text = if path.extension().is_some_and(|e| e == "qgz") { diff --git a/crates/map/testdata/qgis/README.md b/crates/map/testdata/qgis/README.md index 61cd186d22..1f0e514cf7 100644 --- a/crates/map/testdata/qgis/README.md +++ b/crates/map/testdata/qgis/README.md @@ -10,7 +10,7 @@ no specification of these formats, so the corpus stands in for one: `every_corpu | Folder | What | Licence | |---|---|---| | `generated/qml/` | 126 styles written through QGIS's API (4.2.3; the SVG marker ones 4.4.0), each varying one thing: every symbol layer type with its defaults, raster image markers (a PNG and a JPEG, in a file and embedded; sizes in each unit, rotation, an offset, anchor points, a fixed aspect ratio, opacity, and along a line), SVG markers (an SVG with `param(…)` colours and outline width and one without, in a file and embedded, one from QGIS's own library, which isn't copied here; colours with alpha; sizes in each unit, rotation, an offset, anchor points, a fixed aspect ratio, opacity, and along a line), every renderer (categorized and graduated by expression, rule-based with nested and else rules), every paint effect, data-defined size, angle and colour, labels (every placement, buffer, background, shadow, font, wrap, expression text, offsets, data-defined settings, scale ranges, curved labels, each callout, rule-based labels), layer settings (opacity, blend mode, scale range, reference scale, subset), diagrams (pie, by fields and expressions, a histogram, a stacked bar and a text diagram, two of them sized between two values) and raster renderers (grey, pseudocolour interpolated, discrete and exact, multiband, paletted, hillshade, contour) | Apache-2.0, like RustGIS: made by Dominik Strebel ([@pick2510](https://github.com/pick2510)) for the RustGIS project | -| `generated/qgs/` | 39 projects: one per provider (OGR, GDAL, memory, delimited text by x/y and WKT, SpatiaLite, virtual (on a file, on another layer, and grouping), WMS, WMTS, XYZ, raster MBTiles, WFS (also with a filter), OGC API Features, WCS, ArcGIS feature, map, image and vector tile services, vector tiles by address, with a MapLibre style, from MBTiles and from PMTiles, PostGIS, SQL Server, GPX waypoints and tracks); project structure (groups, a mutually exclusive group, a map theme, a bookmark, a variable, a relation, a join, a virtual field, time from a field, two styles on a layer); groups nested, hidden, collapsed, empty and drawn as one (a group layer with its opacity and blending); bookmarks (turned, in a group, in degrees), relations (on one pair of fields, on two, a composition, a polymorphic one) and time settings (a span of months; time from a field, from a field for a duration, a fixed range); a layout with every item and an atlas; `layout-sheets.qgs`, print layouts as map sheets (an A4 landscape sheet of two pages with a framed, turned map, a title and a note with an expression, a turned label with a background and frame, a picture, a rounded rectangle, a translucent ellipse, a triangle and a dashed line, items placed in mm, cm, in and pt, a hidden item, one left out of exports and two grouped; and a Letter portrait sheet in inches), written by QGIS 4.4.0; the annotation layer with every item; annotations with their settings (styled marks, lines and a polygon with a hole, text aligned, turned, in HTML and with a buffer, rectangle text with a background and frame or of a fixed size, a picture file and an SVG, text along a line, one switched off, z order, the main annotation layer); `all-styles.qgz`, every style above on its own layer (written before the diagrams were added); `raster-markers.qgs`, each raster image marker style on its own layer, its image files named relative to it; `svg-markers.qgs`, the same for each SVG marker style, written by QGIS 4.4.0 | Apache-2.0 | +| `generated/qgs/` | 40 projects: one per provider (OGR, GDAL, memory, delimited text by x/y and WKT, SpatiaLite, virtual (on a file, on another layer, and grouping), WMS, WMTS, XYZ, raster MBTiles, WFS (also with a filter), OGC API Features, WCS, ArcGIS feature, map, image and vector tile services, vector tiles by address, with a MapLibre style, from MBTiles and from PMTiles, PostGIS, SQL Server, GPX waypoints and tracks); project structure (groups, a mutually exclusive group, a map theme, a bookmark, a variable, a relation, a join, a virtual field, time from a field, two styles on a layer); groups nested, hidden, collapsed, empty and drawn as one (a group layer with its opacity and blending); bookmarks (turned, in a group, in degrees), relations (on one pair of fields, on two, a composition, a polymorphic one) and time settings (a span of months; time from a field, from a field for a duration, a fixed range); a layout with every item and an atlas; `layout-sheets.qgs`, print layouts as map sheets (an A4 landscape sheet of two pages with a framed, turned map, a title and a note with an expression, a turned label with a background and frame, a picture, a rounded rectangle, a translucent ellipse, a triangle and a dashed line, items placed in mm, cm, in and pt, a hidden item, one left out of exports and two grouped; and a Letter portrait sheet in inches), written by QGIS 4.4.0; `layout-surrounds.qgs`, a sheet with the surrounds tied to a map (scale bars of a single box, ticks up and a stepped line fitted to their box, a numeric one, a north arrow following the map, and an overview map outlining its extent), written by QGIS 4.4.0; the annotation layer with every item; annotations with their settings (styled marks, lines and a polygon with a hole, text aligned, turned, in HTML and with a buffer, rectangle text with a background and frame or of a fixed size, a picture file and an SVG, text along a line, one switched off, z order, the main annotation layer); `all-styles.qgz`, every style above on its own layer (written before the diagrams were added); `raster-markers.qgs`, each raster image marker style on its own layer, its image files named relative to it; `svg-markers.qgs`, the same for each SVG marker style, written by QGIS 4.4.0 | Apache-2.0 | | `generated/data/` | The data those files use: `sample.gpkg` (layers `points`, `lines` and `polygons`, 9 made-up features each, fields `id`, `name`, `kind`, `value`, `angle`, `day`), `dem.tif` (3 bands of a linear surface), two CSVs, a GPX file, `picture.png` (a red 40 × 20 picture), `marker.png` (32 × 16, a red square and a blue bar) and `marker.jpg` (24 × 24, green with a yellow corner), the raster image markers' images; `icon.svg` (the same square and bar) and `marker.svg` (a triangle and a rectangle in `param(…)` colours), the SVG markers' images | Apache-2.0 | | `generated/generate.py`, `scrub.py` | The generator, and the step that removes the user's name and absolute paths from what QGIS writes | Apache-2.0 | | `generated/types.txt` | The element types QGIS 4.2.3 knows (symbol layers, renderers, providers, label placements, callouts, annotation and layout items, paint effects): the checklist the corpus was made from. A few have no file yet: the single-colour raster renderer, and the text table, fixed table, elevation profile and chart layout items | Apache-2.0 | @@ -40,7 +40,7 @@ QGIS 4.2.3 wrote the corpus, and 4.4.0 the SVG marker files. The command runs wh installed (here the Flathub Flatpak, whose `/tmp` is private, so it writes under `~/.cache`) and writes the whole corpus again, so copy only the files you mean to replace: for the SVG markers, `data/icon.svg`, `data/marker.svg`, `qml/symbol-svg-marker-*.qml` and `qgs/svg-markers.qgs`; for the map sheets, -`qgs/layout-sheets.qgs`. +`qgs/layout-sheets.qgs` and `qgs/layout-surrounds.qgs`. ```sh mkdir -p ~/.cache/qgis-corpus diff --git a/crates/map/testdata/qgis/generated/generate.py b/crates/map/testdata/qgis/generated/generate.py index 1e4c21cfdd..b60abf7daa 100644 --- a/crates/map/testdata/qgis/generated/generate.py +++ b/crates/map/testdata/qgis/generated/generate.py @@ -1387,6 +1387,81 @@ def __exit__(self, *a): # (After the annotations, which write `picture.png`.) attempt("layout sheets", layout_sheets) + + +# A sheet with the surrounds tied to a map (piece 12b): scale bars in the styles RustGIS draws +# (fitted to their box) and a numeric one, a north arrow following the map, and an overview map +# outlining the main map's extent. QGIS's own export is written to `renders/` for comparing. +def layout_surrounds(): + from qgis.core import QgsLayoutItemPage, QgsLayoutItemScaleBar, QgsLayoutItemMapOverview, QgsLayoutExporter, QgsFillSymbol, QgsTextFormat + from qgis.PyQt.QtGui import QFont + mm = Qgis.LayoutUnit.Millimeters + p = new_project() + p.relationManager().setPolymorphicRelations([]) + p.setTitle("Surrounds") + pts, polys = layer("points"), layer("polygons") + p.addMapLayers([pts, polys]) + lay = QgsPrintLayout(p) + lay.initializeDefaults() + lay.setName("Surrounds") + lay.pageCollection().page(0).setPageSize("A4", QgsLayoutItemPage.Orientation.Landscape) + m = QgsLayoutItemMap(lay) + lay.addLayoutItem(m) + m.attemptMove(QgsLayoutPoint(10, 10, mm)) + m.attemptResize(QgsLayoutSize(180, 130, mm)) + m.setExtent(QgsRectangle(2696300, 1261200, 2698000, 1262475)) + m.setFrameEnabled(True) + ov = QgsLayoutItemMap(lay) + lay.addLayoutItem(ov) + ov.attemptMove(QgsLayoutPoint(200, 10, mm)) + ov.attemptResize(QgsLayoutSize(85, 65, mm)) + ov.setExtent(QgsRectangle(2694000, 1259500, 2700000, 1264000)) + ov.setFrameEnabled(True) + o = QgsLayoutItemMapOverview("Overview", ov) + ov.overviews().addOverview(o) + o.setLinkedMap(m) + o.setFrameSymbol(QgsFillSymbol.createSimple({"style": "no", "outline_color": "200,0,0,255", "outline_width": "0.6"})) + fmt = QgsTextFormat() + fmt.setFont(QFont("DejaVu Sans")) + fmt.setSize(9) + for i, style in enumerate(["Single Box", "Line Ticks Up", "stepped"]): + sb = QgsLayoutItemScaleBar(lay) + lay.addLayoutItem(sb) + sb.setLinkedMap(m) + sb.setStyle(style) + sb.setTextFormat(fmt) + sb.setUnits(Qgis.DistanceUnit.Meters) + sb.setUnitLabel("m") + sb.setNumberOfSegments(4) + sb.setNumberOfSegmentsLeft(0) + sb.setSegmentSizeMode(Qgis.ScaleBarSegmentSizeMode.FitWidth) + sb.setMinimumBarWidth(50) + sb.setMaximumBarWidth(60) + sb.attemptMove(QgsLayoutPoint(10 + i * 80, 150, mm)) + sb.attemptResize(QgsLayoutSize(60, 15, mm)) + num = QgsLayoutItemScaleBar(lay) + lay.addLayoutItem(num) + num.setLinkedMap(m) + num.setStyle("Numeric") + num.setTextFormat(fmt) + num.attemptMove(QgsLayoutPoint(10, 175, mm)) + num.attemptResize(QgsLayoutSize(60, 10, mm)) + na = QgsLayoutItemPicture(lay) + lay.addLayoutItem(na) + na.setLinkedMap(m) + na.setNorthMode(QgsLayoutItemPicture.NorthMode.GridNorth) + na.setPicturePath(":/images/north_arrows/layout_default_north_arrow.svg") + na.attemptMove(QgsLayoutPoint(230, 90, mm)) + na.attemptResize(QgsLayoutSize(20, 25, mm)) + p.layoutManager().addLayout(lay) + save_project(p, "layout-surrounds") + os.makedirs(os.path.join(OUT, "renders"), exist_ok=True) + settings = QgsLayoutExporter.ImageExportSettings() + settings.dpi = 96 + QgsLayoutExporter(lay).exportToImage(os.path.join(OUT, "renders", "Surrounds.png"), settings) + + +attempt("layout surrounds", layout_surrounds) attempt("all styles project", all_styles) diff --git a/crates/map/testdata/qgis/generated/qgs/layout-surrounds.qgs b/crates/map/testdata/qgis/generated/qgs/layout-surrounds.qgs new file mode 100644 index 0000000000..6ee5eed20a --- /dev/null +++ b/crates/map/testdata/qgis/generated/qgs/layout-surrounds.qgs @@ -0,0 +1,2615 @@ + + + + Surrounds + + + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + + + 0 + 0 + + + + + false + + + + + + + + + + + + + + + + points_59dbe2e0_a3e5_4cdb_88b8_991092e451f0 + polygons_211b99f5_83fc_4f19_8756_54bdf0f576cc + + + + + + + + + + + + Annotations_35b0eaf4_8847_4460_8934_03e051895188 + + Annotations + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + + + + + + + + + + + + + + 0 + 0 + + + + + false + + + + + + + 1 + 1 + 1 + 0 + + + + 1 + 0 + + + + + + 2696500 + 1261500 + 2697700 + 1261740 + + + 8.71934207087455881 + 47.49699490745601338 + 8.73531785937520233 + 47.49933040928209493 + + points_59dbe2e0_a3e5_4cdb_88b8_991092e451f0 + ../data/sample.gpkg|layername=points + points + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + + + dataset + + + + + + + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + ogr + + + + + + + + + + 1 + 1 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + 0 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + generatedlayout + + + + + + + + + + + 2696500 + 1261500 + 2697820 + 1261830 + + + 8.71934207087455881 + 47.49697706140925391 + 8.73692999718656971 + 47.50013975136437949 + + polygons_211b99f5_83fc_4f19_8756_54bdf0f576cc + ../data/sample.gpkg|layername=polygons + polygons + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + + + dataset + + + + + + + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + ogr + + + + + + + + + + 1 + 1 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + 0 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + generatedlayout + + + + + + + + + + + + + + + + + 0 + 0 + + + 0 + 0 + + + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 0 + 0 + 255 + 255 + 255 + 255 + + + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 0 + 0 + 255 + 255 + 255 + 255 + + + m2 + m2 + meters + meters + HorizontalMiddle + HorizontalMiddle + + + m2 + m2 + meters + meters + HorizontalMiddle + HorizontalMiddle + + + 5 + 5 + 2.5 + 2.5 + false + false + false + false + false + false + 1 + 1 + 0 + 0 + false + false + false + false + true + true + 0 + 0 + 255,0,0,255,rgb:1,0,0,1 + 255,0,0,255,rgb:1,0,0,1 + + + 5 + 5 + 2.5 + 2.5 + false + false + false + false + false + false + 1 + 1 + 0 + 0 + false + false + false + false + true + true + 0 + 0 + 255,0,0,255,rgb:1,0,0,1 + 255,0,0,255,rgb:1,0,0,1 + + + false + false + + + false + false + + + true + true + 2 + 2 + + + true + true + 2 + 2 + + + 1 + 1 + + + 1 + 1 + + + 0 + 0 + + + 0 + 0 + + + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 0 + 0 + 255 + 255 + 255 + 255 + + + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 0 + 0 + 255 + 255 + 255 + 255 + + + m2 + m2 + meters + meters + HorizontalMiddle + HorizontalMiddle + + + m2 + m2 + meters + meters + HorizontalMiddle + HorizontalMiddle + + + 5 + 5 + 2.5 + 2.5 + false + false + false + false + false + false + 1 + 1 + 0 + 0 + false + false + false + false + true + true + 0 + 0 + 255,0,0,255,rgb:1,0,0,1 + 255,0,0,255,rgb:1,0,0,1 + + + 5 + 5 + 2.5 + 2.5 + false + false + false + false + false + false + 1 + 1 + 0 + 0 + false + false + false + false + true + true + 0 + 0 + 255,0,0,255,rgb:1,0,0,1 + 255,0,0,255,rgb:1,0,0,1 + + + false + false + + + false + false + + + true + true + 2 + 2 + + + true + true + 2 + 2 + + + 1 + 1 + + + 1 + 1 + + + + + + + + + + + + + Surrounds + + + + + + Unknown + 2026-12-01T18:33:28 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + GEOGCRS["WGS 84",ENSEMBLE["World Geodetic System 1984 ensemble",MEMBER["World Geodetic System 1984 (Transit)"],MEMBER["World Geodetic System 1984 (G730)"],MEMBER["World Geodetic System 1984 (G873)"],MEMBER["World Geodetic System 1984 (G1150)"],MEMBER["World Geodetic System 1984 (G1674)"],MEMBER["World Geodetic System 1984 (G1762)"],MEMBER["World Geodetic System 1984 (G2139)"],MEMBER["World Geodetic System 1984 (G2296)"],ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]],ENSEMBLEACCURACY[2.0]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["geodetic latitude (Lat)",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["geodetic longitude (Lon)",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],USAGE[SCOPE["Horizontal component of 3D system."],AREA["World."],BBOX[-90,-180,90,180]],ID["EPSG",4326]] + +proj=longlat +datum=WGS84 +no_defs + 3452 + 4326 + EPSG:4326 + WGS 84 + longlat + EPSG:7030 + true + + + + + + + diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 381e67a9c4..ad278ed6b8 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -440,10 +440,16 @@ older QGIS 3 labels keep their font and colour too; a page keeps its paper's col their PNG or JPEG files, or kept in the project as written (a picture kept inside a `.qgz` isn't read, noted: save it as a file beside the project and point the item at it); rectangles and ellipses with their fill, outline and rounded corners; and lines and polygons as straight -lines along their edges, with arrowheads. Labels' and pictures' backgrounds and frames, a map's +lines along their edges, with arrowheads. Scale bars, north arrows and map overviews show the +frame of the map item they follow, on their page: a scale bar in RustGIS's nearest style (a single +box, ticks or a stepped line), with its units, divisions, label placement, text size and unit +label, and its division values chosen to fit its box (noted when QGIS's were fixed); a numeric +scale bar as a text printing `{scale}`; a north arrow (QGIS's is a picture) as RustGIS's arrow, +noted; an overview as an extent indicator in its outline's colour, its fill noted. One whose map +isn't on its page is left out, noted. Labels' and pictures' backgrounds and frames, a map's frame, hidden items and locked ones carry over. What a layout can't hold is -noted: scale bars, legends, north arrows, tables, HTML and other items, map grids, overviews and -the atlas, SVG pictures, groups (their items kept on their own), turned maps, shapes and pictures +noted: legends, tables, HTML and other items, map grids and +the atlas, SVG pictures, scale bars' subdivisions and other styles, groups (their items kept on their own), turned maps, shapes and pictures (drawn upright), stretched or clipped pictures, a polygon's fill, a map's background colour, label styling RustGIS's text lacks (underlines, buffers, shadows), blending, and settings set by expressions. From 9132db7a6e4b66d3c0689f939898faa9e742013b Mon Sep 17 00:00:00 2001 From: strebdom Date: Tue, 1 Dec 2026 19:31:01 +0100 Subject: [PATCH 2/8] fix(map): QGIS layout surrounds of a map that doesn't come in say only that; numeric sizes, forced bold and switched-off overviews said - A map whose extent doesn't read is known not to come in before its surrounds are read. - A numeric scale bar's text size is kept within 1 to 400 pt, said; forced bold or italic on a scale bar's text is said. - Overviews and grids switched off are said; an overview of a map left out says so. - Maps found by (id, page) in a hash map and set, not by scanning. - The guide says which scale bar values carry over and whose scale a numeric bar prints. --- crates/map/src/qgis/layout.rs | 41 ++++++++++++----- crates/map/src/qgis/layout/surround.rs | 22 +++++++--- crates/map/src/qgis/layout_surround_tests.rs | 46 +++++++++++++++++++- docs/user-guide/workspace.md | 11 +++-- 4 files changed, 97 insertions(+), 23 deletions(-) diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index dbe34b170b..90179352b4 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -152,11 +152,11 @@ pub(super) struct Tally { /// Labels whose margins leave their text less than an element can be across or down, its box /// widened to it. tiny_text: usize, - /// The QGIS layout being read's map items, as (uuid, layout, element), and the elements + /// The QGIS layout being read's map items, by (uuid, layout) to their elements, and the elements /// waiting for one's frame ([`surround::link`]). - maps: Vec<(String, usize, u32)>, + maps: std::collections::HashMap<(String, usize), u32>, /// The map items that will come in, by (uuid, layout) ([`surround::known_maps`]). - known: Vec<(String, usize)>, + known: std::collections::HashSet<(String, usize)>, /// Overviews past what a frame outlines, and scale bars' text bold, italic, underlined, /// buffered or shadowed. overviews_past: usize, @@ -175,6 +175,10 @@ pub(super) struct Tally { numeric_other: usize, /// Numeric scale bars, printing the scale in RustGIS's format. numeric_formats: usize, + /// Numeric scale bars' text sizes outside what a text takes (1 to 400 pt), and overviews + /// switched off. + numeric_sizes: usize, + overviews_off: usize, /// Scale bars as RustGIS's nearest: their style, colours, units, divisions (past RustGIS's), /// subdivisions, fixed division values, placement, and text sizes (past a layout's). bar_styles: usize, @@ -687,22 +691,33 @@ fn name_or(id: Option, kind: &str) -> String { id.unwrap_or_else(|| kind.to_string()) } +/// A map item's extent (`Extent`), [xmin, ymin, xmax, ymax]: `None` where it doesn't read or is +/// empty, and the item then doesn't come in. +fn map_extent(item: Node) -> Option<[f64; 4]> { + let e = child(item, "Extent")?; + let v = |k: &str| num(e, k); + let x = [v("xmin")?, v("ymin")?, v("xmax")?, v("ymax")?]; + (x[0] < x[2] && x[1] < x[3]).then_some(x) +} + fn map_item(item: Node, place: &Placed, id: Option, target: &mut ProjectLayout, tally: &mut Tally) { if place.turn.rem_euclid(360.0) != 0.0 { tally.turned_items += 1; } - let extent = child(item, "Extent").and_then(|e| { - let v = |k: &str| num(e, k); - let x = [v("xmin")?, v("ymin")?, v("xmax")?, v("ymax")?]; - (x[0] < x[2] && x[1] < x[3]).then_some(x) - }); - let Some(extent) = extent else { + let Some(extent) = map_extent(item) else { tally.unplaced += 1; return; }; let crs = child(item, "crs").and_then(super::crs_of); tally.own_crs += usize::from(crs.is_some()); - tally.grids += item.children().filter(|c| c.has_tag_name("ComposerMapGrid") && c.attribute("show") != Some("0")).count(); + for g in item.children().filter(|c| c.has_tag_name("ComposerMapGrid")) { + // A grid switched off is said as one, as an overview switched off is. + if g.attribute("show") == Some("0") { + tally.overviews_off += 1; + } else { + tally.grids += 1; + } + } if item.attribute("keepLayerSet") == Some("true") || item.attribute("followPreset") == Some("true") { tally.locked_layers += 1; } @@ -742,7 +757,7 @@ fn map_item(item: Node, place: &Placed, id: Option, target: &mut Project target.frames.push(LayoutFrame { element, extent, crs }); // The surrounds and overviews of its map find its frame by its id. if let Some(uuid) = item.attribute("uuid").map(str::trim).filter(|u| !u.is_empty()) { - tally.maps.push((uuid.to_string(), place.page, element)); + tally.maps.entry((uuid.to_string(), place.page)).or_insert(element); } surround::overviews(item, place.page, element, tally); } @@ -1257,7 +1272,8 @@ impl Tally { let skipped = [ (self.legends, "legends"), (self.unlinked, "scale bars and north arrows whose map isn't on their page, or is left out"), - (self.overviews_unlinked, "map overviews of their own map or of a map not on their page"), + (self.overviews_unlinked, "map overviews of their own map, or of a map not on their page or left out"), + (self.overviews_off, "map overviews and grids switched off"), (self.overviews_past, &format!("map overviews past the {} a frame outlines", crate::layout::MAX_EXTENT_INDICATORS)), (self.bar_subdivisions, "scale bars' subdivisions"), (self.tables, "attribute tables"), @@ -1313,6 +1329,7 @@ impl Tally { (self.overview_ways, "map overviews inverted, centring their map, blended or dashed, drawn as plain outlines"), (self.bar_text_styles, "scale bars' text bold, italic, underlined, buffered or shadowed, drawn plain"), (self.numeric_formats, "numeric scale bars, printing the scale in RustGIS's format (1:25,000)"), + (self.numeric_sizes, "numeric scale bars' text sizes outside 1 to 400 pt, drawn at the nearest"), (self.numeric_other, "numeric scale bars of a map other than their layout's first, printing the first's scale"), (self.bar_styles, "scale bars of a double box, hollow, ticks down or across, or another style, in RustGIS's nearest"), (self.bar_colors, "scale bars whose lines, labels and dark divisions differ in colour, drawn in one"), diff --git a/crates/map/src/qgis/layout/surround.rs b/crates/map/src/qgis/layout/surround.rs index fd5c6650fc..d9140bc657 100644 --- a/crates/map/src/qgis/layout/surround.rs +++ b/crates/map/src/qgis/layout/surround.rs @@ -29,11 +29,12 @@ pub(super) struct Linked { /// The QGIS layout's map items that will come in, by (uuid, layout): those with an id, an extent /// and a place, looked at before its items are read, so that a surround whose map isn't on its /// page is left out (said) before anything else of it is counted. -pub(super) fn known_maps(items: &[(f64, usize, Node)], pages: &Pages, dpi: f64) -> Vec<(String, usize)> { +pub(super) fn known_maps(items: &[(f64, usize, Node)], pages: &Pages, dpi: f64) -> std::collections::HashSet<(String, usize)> { items .iter() .map(|(_, _, n)| *n) - .filter(|n| n.attribute("type") == Some(MAP) && child(*n, "Extent").is_some()) + // As `map_item` reads it: one whose extent doesn't read doesn't come in. + .filter(|n| n.attribute("type") == Some(MAP) && map_extent(*n).is_some()) .filter_map(|n| { let uuid = n.attribute("uuid").map(str::trim).filter(|u| !u.is_empty())?; // Where it lands, counted nowhere: its own reading counts it. @@ -45,7 +46,7 @@ pub(super) fn known_maps(items: &[(f64, usize, Node)], pages: &Pages, dpi: f64) /// Whether map item `uuid` comes in on layout `page`. fn on_page(tally: &Tally, uuid: &str, page: usize) -> bool { - !uuid.is_empty() && tally.known.iter().any(|(u, p)| u == uuid && *p == page) + !uuid.is_empty() && tally.known.contains(&(uuid.to_string(), page)) } /// Links each element of the QGIS layout just read to the frame its map item became on its page @@ -54,7 +55,7 @@ pub(super) fn link(layouts: &mut [ProjectLayout], tally: &mut Tally) { let maps = std::mem::take(&mut tally.maps); for l in std::mem::take(&mut tally.linked) { let Some(target) = layouts.get_mut(l.page) else { continue }; - let frame = (!l.map.is_empty()).then(|| maps.iter().find(|(m, page, _)| *m == l.map && *page == l.page)).flatten().map(|m| m.2); + let frame = maps.get(&(l.map, l.page)).copied(); match (l.link, frame) { (Link::Overview { color, width }, Some(of)) if of != l.element => { if let Some(e) = target.layout.element_mut(l.element) { @@ -93,7 +94,12 @@ pub(super) fn link(layouts: &mut [ProjectLayout], tally: &mut Tally) { /// no outline, its fill's colour opaque. pub(super) fn overviews(item: Node, page: usize, element: u32, tally: &mut Tally) { let own = item.attribute("uuid").map(str::trim).unwrap_or_default(); - for o in item.children().filter(|c| c.has_tag_name("ComposerMapOverview") && c.attribute("show") != Some("0")) { + for o in item.children().filter(|c| c.has_tag_name("ComposerMapOverview")) { + // Switched off, QGIS draws it not; said, as an indicator can't be kept switched off. + if o.attribute("show") == Some("0") { + tally.overviews_off += 1; + continue; + } let map = o.attribute("frameMap").map(str::trim).unwrap_or_default().to_string(); // Of its own map, or of one not on its page: not drawn, said, and nothing else of it. if map == own || !on_page(tally, &map, page) { @@ -173,7 +179,9 @@ pub(super) fn scale_bar_item( let name = name_or(id, "Scale bar"); let bounds = (place.x, place.y, place.w, place.h); if style == "Numeric" { - let mut kind = ElementKind::text("{scale}", size, fade(text_color), false); + let kept = size.clamp(1.0, 400.0); + tally.numeric_sizes += usize::from(kept != size); + let mut kind = ElementKind::text("{scale}", kept, fade(text_color), false); if let ElementKind::Text { align, valign, font_name, rotation, .. } = &mut kind { // Across: left 0, centre 1, right 2; QGIS centres it down its box. *align = match num(item, "alignment").map_or(0, |a| a as i64) { @@ -298,6 +306,8 @@ fn text_style(item: Node, tally: &mut Tally) -> (f64, Rgba, Option) { let (bold, italic) = labels::bold_italic(s); let styled = bold || italic + || s.attribute("forcedBold") == Some("1") + || s.attribute("forcedItalic") == Some("1") || s.attribute("fontUnderline") == Some("1") || s.attribute("fontStrikeout") == Some("1") || child(s, "text-buffer").is_some_and(|n| n.attribute("bufferDraw") == Some("1")) diff --git a/crates/map/src/qgis/layout_surround_tests.rs b/crates/map/src/qgis/layout_surround_tests.rs index 86cd9ebb26..50da502d44 100644 --- a/crates/map/src/qgis/layout_surround_tests.rs +++ b/crates/map/src/qgis/layout_surround_tests.rs @@ -289,7 +289,7 @@ fn a_map_overview_outlines_its_maps_frame() { let mut report = Report::default(); read(&layout(TWO_PAGES, &items), &mut report); assert!(said(&report, "map overviews' fills, drawn as their outlines (1)"), "{:?}", report.notes); - assert!(said(&report, "map overviews of their own map or of a map not on their page (1)"), "{:?}", report.notes); + assert!(said(&report, "map overviews of their own map, or of a map not on their page or left out (1)"), "{:?}", report.notes); } /// A scale bar past a full layout is counted with the elements it leaves out. @@ -346,3 +346,47 @@ fn the_corpus_surrounds_show_the_main_map() { ] ); } + +/// A map whose extent doesn't read doesn't come in, so its scale bar is left out, said as only +/// that. +#[test] +fn a_surround_of_a_map_that_doesnt_come_in_says_only_that() { + let broken = r#""#; + let items = format!("{broken}{}", bar("{m}", r#"style="Double Box" unitType="yd""#, BAR_COLOURS)); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + assert!(bars(&p.layouts[0].layout).is_empty()); + let texts: Vec<&str> = report.notes.iter().map(|n| n.text.as_str()).collect(); + assert_eq!( + texts, + [ + "its print layouts' scale bars and north arrows whose map isn't on their page, or is left out (1)", + "its print layouts' items whose place or shape doesn't read (1)" + ] + ); +} + +/// A numeric scale's text size past what a text takes is drawn at the nearest, said; forced bold +/// on a bar's text is said; an overview and a grid switched off are said. +#[test] +fn numeric_sizes_forced_bold_and_switched_off_overviews_are_said() { + let numeric = r#""#; + let forced = bar("{m}", r#"style="Single Box" segmentSizeMode="1""#, BAR_COLOURS) + .replace(r#"textColor="0,0,0,255"/>"#, r#"textColor="0,0,0,255" forcedBold="1"/>"#); + let off = r#""#; + let items = format!("{}{}{numeric}{forced}", map("{m}", 10.0, 0, ""), map("{o}", 115.0, 0, off)); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + let size = p.layouts[0].layout.elements.iter().find_map(|e| match e.kind { + ElementKind::Text { size, .. } => Some(size), + _ => None, + }); + assert_eq!(size, Some(400.0)); + for part in [ + "numeric scale bars' text sizes outside 1 to 400 pt, drawn at the nearest (1)", + "scale bars' text bold, italic, underlined, buffered or shadowed, drawn plain (1)", + "map overviews and grids switched off (2)", + ] { + assert!(said(&report, part), "{part}: {:?}", report.notes); + } +} diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index ad278ed6b8..c8120c0d33 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -442,10 +442,13 @@ isn't read, noted: save it as a file beside the project and point the item at it and ellipses with their fill, outline and rounded corners; and lines and polygons as straight lines along their edges, with arrowheads. Scale bars, north arrows and map overviews show the frame of the map item they follow, on their page: a scale bar in RustGIS's nearest style (a single -box, ticks or a stepped line), with its units, divisions, label placement, text size and unit -label, and its division values chosen to fit its box (noted when QGIS's were fixed); a numeric -scale bar as a text printing `{scale}`; a north arrow (QGIS's is a picture) as RustGIS's arrow, -noted; an overview as an extent indicator in its outline's colour, its fill noted. One whose map +box, ticks or a stepped line), with its label placement and, within what RustGIS takes, its +units (metres, kilometres, feet or miles; others RustGIS's choice, with its own abbreviation), +divisions, text size and unit label, its division values chosen to fit its box (each change +noted, and fixed values in QGIS too); a numeric scale bar as a text printing `{scale}`, the scale +of the layout's first map (noted when it follows another); a north arrow (QGIS's is a picture) as +RustGIS's arrow, noted; an overview as an extent indicator in its outline's colour, its fill +noted. One whose map isn't on its page is left out, noted. Labels' and pictures' backgrounds and frames, a map's frame, hidden items and locked ones carry over. What a layout can't hold is noted: legends, tables, HTML and other items, map grids and From e637a489fd4a970edb20730aacd3ededa9a7e843 Mon Sep 17 00:00:00 2001 From: strebdom Date: Tue, 1 Dec 2026 20:09:05 +0100 Subject: [PATCH 3/8] fix(map): a QGIS layout surround's notes are said only once it links; unit labels, invisible overviews and symbol opacity - A scale bar's, numeric scale's, north arrow's and overview's notes, and their placement's, wait on their link: one left out (its map past a full layout) says only that. - A scale bar with no unit label written prints its units' abbreviation. - An overview with neither fill nor outline is no indicator; a hairline outline is drawn thin. - A scale bar's colours take their symbol's own opacity. --- crates/map/src/qgis/layout.rs | 30 ++-- crates/map/src/qgis/layout/surround.rs | 143 ++++++++++++++----- crates/map/src/qgis/layout_surround_tests.rs | 87 +++++++++++ 3 files changed, 219 insertions(+), 41 deletions(-) diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index 90179352b4..cc22d6b2b7 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -608,15 +608,16 @@ fn read_item( let tiny = !matches!(kind, POLYLINE | POLYGON) && (place.w < crate::layout::MIN_ELEMENT_MM || place.h < crate::layout::MIN_ELEMENT_MM); // A picture's notes wait for its image (a north arrow, also a QGIS picture, is not one). let picture = target.layout.elements.get(first).is_some_and(|e| matches!(e.kind, ElementKind::Picture { .. })); + let mut counted = surround::Counts::default(); let counts = [ - (id_cut, &mut tally.cut_names, "pictures' ids longer than 100 characters, cut to fit"), - (pixels, &mut tally.pixels, "picture positions in pixels, read at the layout's print resolution"), - (oversized, &mut tally.oversized, "pictures larger than 5 m a side, cut to it"), - (tiny, &mut tally.tiny, "pictures less than 0.05 mm across or down, widened to it"), - (blended, &mut tally.blended, "pictures' blending modes, drawn normally"), - (data_defined, &mut tally.data_defined, "pictures with settings set by expressions, drawn as set"), - (opacity < 1.0 && (kind == MAP || picture), &mut tally.translucent, "translucent pictures, drawn opaque"), - (shown && !exported, &mut tally.not_exported, "pictures left out of exports, kept hidden"), + (id_cut, &mut counted.cut_names, "pictures' ids longer than 100 characters, cut to fit"), + (pixels, &mut counted.pixels, "picture positions in pixels, read at the layout's print resolution"), + (oversized, &mut counted.oversized, "pictures larger than 5 m a side, cut to it"), + (tiny, &mut counted.tiny, "pictures less than 0.05 mm across or down, widened to it"), + (blended, &mut counted.blended, "pictures' blending modes, drawn normally"), + (data_defined, &mut counted.data_defined, "pictures with settings set by expressions, drawn as set"), + (opacity < 1.0 && (kind == MAP || picture), &mut counted.translucent, "translucent pictures, drawn opaque"), + (shown && !exported, &mut counted.not_exported, "pictures left out of exports, kept hidden"), ]; for (set, count, picture_note) in counts { if !(added && set) { @@ -630,6 +631,19 @@ fn read_item( *count += 1; } } + // A scale bar's or north arrow's wait for its link (one that doesn't link says only that). + let element = target.layout.elements.get(first).map(|e| e.id); + match tally.linked.last_mut() { + Some(l) + if added + && l.page == place.page + && element == Some(l.element) + && matches!(l.link, surround::Link::Surround | surround::Link::Numeric) => + { + l.counts.merge(counted); + } + _ => counted.add_to(tally), + } // A hidden item, and one QGIS leaves out of its exports, is kept hidden. let locked = item.attribute("positionLock") == Some("true"); for e in target.layout.elements.iter_mut().skip(first) { diff --git a/crates/map/src/qgis/layout/surround.rs b/crates/map/src/qgis/layout/surround.rs index d9140bc657..33d29352bc 100644 --- a/crates/map/src/qgis/layout/surround.rs +++ b/crates/map/src/qgis/layout/surround.rs @@ -18,14 +18,71 @@ pub(super) enum Link { Overview { color: Rgba, width: f64 }, } -/// An element waiting for the frame of a map item (by its `uuid`) on its page. +/// An element waiting for the frame of a map item (by its `uuid`) on its page, with what it is +/// said as: counted once it links, so one left out says only that. pub(super) struct Linked { pub(super) page: usize, pub(super) element: u32, pub(super) map: String, pub(super) link: Link, + pub(super) counts: Counts, } +/// What a surround or overview, or another item, counts in the layouts' notes ([`Tally`]'s +/// fields of the same names), and what reading its text size noted. +macro_rules! counts { + ($($field:ident),* $(,)?) => { + #[derive(Default)] + pub(super) struct Counts { + $(pub(super) $field: usize,)* + pub(super) notes: Report, + } + + impl Counts { + /// Counted in the layouts' notes. + pub(super) fn add_to(self, tally: &mut Tally) { + $(tally.$field += self.$field;)* + tally.notes.merge_as("", &self.notes); + } + + /// Added to these, waiting with them. + pub(super) fn merge(&mut self, other: Counts) { + $(self.$field += other.$field;)* + self.notes.merge_as("", &other.notes); + } + } + }; +} + +counts!( + north_arrows, + true_north, + turned_items, + numeric_formats, + numeric_sizes, + bar_styles, + bar_colors, + bar_units, + bar_divisions, + bar_subdivisions, + bar_values, + bar_layout, + bar_text_sizes, + bar_text_styles, + cut_texts, + braces, + overview_fills, + overview_ways, + cut_names, + pixels, + oversized, + tiny, + blended, + data_defined, + translucent, + not_exported, +); + /// The QGIS layout's map items that will come in, by (uuid, layout): those with an id, an extent /// and a place, looked at before its items are read, so that a surround whose map isn't on its /// page is left out (said) before anything else of it is counted. @@ -56,6 +113,7 @@ pub(super) fn link(layouts: &mut [ProjectLayout], tally: &mut Tally) { for l in std::mem::take(&mut tally.linked) { let Some(target) = layouts.get_mut(l.page) else { continue }; let frame = maps.get(&(l.map, l.page)).copied(); + let counts = l.counts; match (l.link, frame) { (Link::Overview { color, width }, Some(of)) if of != l.element => { if let Some(e) = target.layout.element_mut(l.element) { @@ -67,6 +125,7 @@ pub(super) fn link(layouts: &mut [ProjectLayout], tally: &mut Tally) { } shown.push(ExtentIndicator { of, color, width }); e.kind.set_extent_indicators(shown); + counts.add_to(tally); } } (Link::Overview { .. }, _) => tally.overviews_unlinked += 1, @@ -76,10 +135,12 @@ pub(super) fn link(layouts: &mut [ProjectLayout], tally: &mut Tally) { { *frame = of; } + counts.add_to(tally); } (Link::Numeric, Some(of)) => { // `{scale}` prints the layout's first frame's scale. tally.numeric_other += usize::from(target.layout.first_frame() != Some(of)); + counts.add_to(tally); } (Link::Surround | Link::Numeric, None) => { target.layout.remove(l.element); @@ -106,16 +167,24 @@ pub(super) fn overviews(item: Node, page: usize, element: u32, tally: &mut Tally tally.overviews_unlinked += 1; continue; } - let (fill, outline, width, dash) = fill_of(o, &|c| c, &mut tally.notes); - let (color, width) = if outline.a() > 0 && width > 0.0 { (outline, width) } else { (fill.with_alpha(255), INDICATOR_WIDTH) }; - tally.overview_fills += usize::from(fill.a() > 0); - tally.overview_ways += usize::from( + let mut counts = Counts::default(); + let (fill, outline, width, dash) = fill_of(o, &|c| c, &mut counts.notes); + // An outline of no width is QGIS's hairline: RustGIS's thinnest indicator's width. + let drawn_outline = outline.a() > 0; + // Neither fill nor outline: QGIS draws nothing of it, nor does RustGIS. + if !drawn_outline && fill.a() == 0 { + continue; + } + let (color, width) = + if drawn_outline { (outline, if width > 0.0 { width } else { 1.0 }) } else { (fill.with_alpha(255), INDICATOR_WIDTH) }; + counts.overview_fills += usize::from(fill.a() > 0); + counts.overview_ways += usize::from( o.attribute("inverted") == Some("1") || o.attribute("centered") == Some("1") || num(o, "blendMode").is_some_and(|b| b != 0.0) || dash.is_some(), ); - tally.linked.push(Linked { page, element, map, link: Link::Overview { color, width } }); + tally.linked.push(Linked { page, element, map, link: Link::Overview { color, width }, counts }); } } @@ -139,10 +208,11 @@ pub(super) fn north_arrow( return; } // QGIS's arrow is a picture (an SVG); RustGIS draws its own, in ink faded as the item is. - tally.north_arrows += 1; - tally.turned_items += usize::from(place.turn.rem_euclid(360.0) != 0.0); + let mut counts = Counts { north_arrows: 1, ..Counts::default() }; + counts.turned_items += usize::from(place.turn.rem_euclid(360.0) != 0.0); // Grid north 0 is the map's; true north 1 and an offset turn it from there. - tally.true_north += usize::from(num(item, "northMode").is_some_and(|m| m != 0.0) || num(item, "northOffset").is_some_and(|o| o != 0.0)); + counts.true_north += + usize::from(num(item, "northMode").is_some_and(|m| m != 0.0) || num(item, "northOffset").is_some_and(|o| o != 0.0)); let mut kind = ElementKind::north_arrow(0); if let ElementKind::NorthArrow { fill, outline, .. } = &mut kind { (*fill, *outline) = (fade(*fill), fade(*outline)); @@ -151,7 +221,7 @@ pub(super) fn north_arrow( if let Some(e) = target.layout.element_mut(element) { e.background = backdrop(item, true, place.dpi, &fade); } - tally.linked.push(Linked { page: place.page, element, map, link: Link::Surround }); + tally.linked.push(Linked { page: place.page, element, map, link: Link::Surround, counts }); } /// Whether a scale bar's map comes in on its page: one whose map doesn't is left out, said, and @@ -173,14 +243,15 @@ pub(super) fn scale_bar_item( tally: &mut Tally, ) { let map = item.attribute("mapUuid").map(str::trim).unwrap_or_default().to_string(); - let (size, text_color, font) = text_style(item, tally); + let mut counts = Counts::default(); + let (size, text_color, font) = text_style(item, &mut counts); let turned = place.turn.rem_euclid(360.0) != 0.0; let style = item.attribute("style").map(str::trim).unwrap_or("Single Box"); let name = name_or(id, "Scale bar"); let bounds = (place.x, place.y, place.w, place.h); if style == "Numeric" { let kept = size.clamp(1.0, 400.0); - tally.numeric_sizes += usize::from(kept != size); + counts.numeric_sizes += usize::from(kept != size); let mut kind = ElementKind::text("{scale}", kept, fade(text_color), false); if let ElementKind::Text { align, valign, font_name, rotation, .. } = &mut kind { // Across: left 0, centre 1, right 2; QGIS centres it down its box. @@ -198,8 +269,8 @@ pub(super) fn scale_bar_item( e.background = backdrop(item, true, place.dpi, &fade); } // QGIS's number format (`1:25'000.5`) as RustGIS's (`1:25,000`), said. - tally.numeric_formats += 1; - tally.linked.push(Linked { page: place.page, element, map, link: Link::Numeric }); + counts.numeric_formats += 1; + tally.linked.push(Linked { page: place.page, element, map, link: Link::Numeric, counts }); return; } let (style, exact) = match style { @@ -210,8 +281,8 @@ pub(super) fn scale_bar_item( // A double box, a hollow bar and a style of a plugin: RustGIS's alternating bar. _ => (ScaleBarStyle::Alternating, false), }; - tally.bar_styles += usize::from(!exact); - tally.turned_items += usize::from(turned); + counts.bar_styles += usize::from(!exact); + counts.turned_items += usize::from(turned); let line = style != ScaleBarStyle::Alternating; // Its lines' colour (a line's), its dark divisions' and its light ones'. let stroke = symbol_color(item, "lineSymbol").or_else(|| child(item, "strokeColor").and_then(rgba_of)).unwrap_or(Rgba::rgb(0, 0, 0)); @@ -223,7 +294,7 @@ pub(super) fn scale_bar_item( let color = if line { stroke } else { dark }; // Its ticks' (a line's divisions' and subdivisions') colours too. let ticks = ["divisionLineSymbol", "subdivisionLineSymbol"].iter().filter_map(|t| symbol_color(item, t)).any(|c| line && c != color); - tally.bar_colors += usize::from(text_color != color || (!line && stroke != color) || ticks); + counts.bar_colors += usize::from(text_color != color || (!line && stroke != color) || ticks); let (units, abbr) = match item.attribute("unitType").map(str::trim).unwrap_or("meters") { "meters" | "m" => (ScaleUnits::Meters, Some("m")), "km" | "kilometers" => (ScaleUnits::Kilometers, Some("km")), @@ -233,13 +304,15 @@ pub(super) fn scale_bar_item( // (millimetres to kilometres), said. _ => (ScaleUnits::Auto, None), }; - tally.bar_units += usize::from(abbr.is_none()); + counts.bar_units += usize::from(abbr.is_none()); // The label QGIS prints for its units: none where it is RustGIS's abbreviation, and none in // RustGIS's choice of units (its own abbreviation, for what it counts in). - let label = item.attribute("unitLabelString").unwrap_or_default(); + // No label written (QGIS before it had one): the abbreviation, as QGIS prints then. One + // written empty prints none, in both. + let label = item.attribute("unitLabelString").unwrap_or(abbr.unwrap_or_default()); let unit_label = (abbr.is_some() && Some(label) != abbr).then(|| { - tally.cut_texts += usize::from(label.chars().nth(MAX_UNIT_LABEL_CHARS).is_some()); - tally.braces += usize::from(label.contains(['{', '}'])); + counts.cut_texts += usize::from(label.chars().nth(MAX_UNIT_LABEL_CHARS).is_some()); + counts.braces += usize::from(label.contains(['{', '}'])); as_written(&label.chars().take(MAX_UNIT_LABEL_CHARS).collect::()) }); let count = |k: &str, max: usize, least: usize| { @@ -248,16 +321,16 @@ pub(super) fn scale_bar_item( }; let (divisions, more) = count("numSegments", MAX_SCALE_DIVISIONS, 1); let (before, more_before) = count("numSegmentsLeft", MAX_SCALE_BEFORE_ZERO, 0); - tally.bar_divisions += usize::from(more || more_before); + counts.bar_divisions += usize::from(more || more_before); // Subdivisions of its divisions (drawn by QGIS's line styles): left out, said. - tally.bar_subdivisions += usize::from(line && num(item, "numSubdivisions").is_some_and(|n| n > 1.0)); + counts.bar_subdivisions += usize::from(line && num(item, "numSubdivisions").is_some_and(|n| n > 1.0)); // A fixed value a division (`segmentSizeMode` 0): RustGIS picks its own to fit the bar's box. - tally.bar_values += usize::from(num(item, "segmentSizeMode").is_none_or(|m| m == 0.0)); + counts.bar_values += usize::from(num(item, "segmentSizeMode").is_none_or(|m| m == 0.0)); // Its labels over the middle of their division (1), its bar in the middle or right of its box, // its height and its lines' width other than RustGIS's (3 mm, 0.3 mm): drawn as RustGIS draws // a bar. let width = symbol_number(item, "lineSymbol", "line_width").or_else(|| num(item, "outlineWidth")); - tally.bar_layout += usize::from( + counts.bar_layout += usize::from( num(item, "labelHorizontalPlacement").is_some_and(|p| p != 0.0) || num(item, "alignment").is_some_and(|a| a != 0.0) || num(item, "height").is_some_and(|h| (h - 3.0).abs() > 1e-9) @@ -291,17 +364,17 @@ pub(super) fn scale_bar_item( *fit = ScaleBarFit::AdjustDivisionValue; *font_name = font; } - tally.bar_text_sizes += usize::from(!LAYOUT_TEXT_SIZE.contains(&size)); + counts.bar_text_sizes += usize::from(!LAYOUT_TEXT_SIZE.contains(&size)); let element = target.layout.add(name, bounds, kind); if let Some(e) = target.layout.element_mut(element) { e.background = backdrop(item, true, place.dpi, &fade); } - tally.linked.push(Linked { page: place.page, element, map, link: Link::Surround }); + tally.linked.push(Linked { page: place.page, element, map, link: Link::Surround, counts }); } /// A surround's text style (`text-style`): its size in points, colour and installed font; its /// bold, italic, underline, buffer and shadow, which a scale bar's text lacks, counted. -fn text_style(item: Node, tally: &mut Tally) -> (f64, Rgba, Option) { +fn text_style(item: Node, counts: &mut Counts) -> (f64, Rgba, Option) { let Some(s) = child(item, "text-style") else { return (10.0, Rgba::rgb(0, 0, 0), None) }; let (bold, italic) = labels::bold_italic(s); let styled = bold @@ -313,9 +386,9 @@ fn text_style(item: Node, tally: &mut Tally) -> (f64, Rgba, Option) { || child(s, "text-buffer").is_some_and(|n| n.attribute("bufferDraw") == Some("1")) || child(s, "shadow").is_some_and(|n| n.attribute("shadowDraw") == Some("1")) || child(s, "background").is_some_and(|n| n.attribute("shapeDraw") == Some("1")); - tally.bar_text_styles += usize::from(styled); + counts.bar_text_styles += usize::from(styled); let unit = s.attribute("fontSizeUnit").unwrap_or("Point"); - let size = labels::points(num(s, "fontSize").unwrap_or(10.0), unit, "scale bar text sizes", "", &mut tally.notes); + let size = labels::points(num(s, "fontSize").unwrap_or(10.0), unit, "scale bar text sizes", "", &mut counts.notes); let opacity = num(s, "textOpacity").unwrap_or(1.0).clamp(0.0, 1.0); let c = s.attribute("textColor").and_then(color).unwrap_or(Rgba::rgb(0, 0, 0)); let c = c.with_alpha((f64::from(c.a()) * opacity).round() as u8); @@ -329,9 +402,13 @@ fn symbol_number(item: Node, tag: &str, key: &str) -> Option { super::super::prop(&super::super::props(layer), key)?.trim().parse::().ok().filter(|v| v.is_finite()) } -/// The colour of a symbol held under `tag` (its first layer's fill or line colour). +/// The colour of a symbol held under `tag` (its first layer's fill or line colour), faded by the +/// symbol's own opacity (`alpha`). fn symbol_color(item: Node, tag: &str) -> Option { - let layer = child(item, tag)?.descendants().find(|d| d.has_tag_name("layer"))?; + let symbol = child(item, tag)?.descendants().find(|d| d.has_tag_name("symbol"))?; + let layer = symbol.descendants().find(|d| d.has_tag_name("layer"))?; let props = super::super::props(layer); - super::super::prop(&props, "color").or_else(|| super::super::prop(&props, "line_color")).and_then(color) + let c = super::super::prop(&props, "color").or_else(|| super::super::prop(&props, "line_color")).and_then(color)?; + let alpha = num(symbol, "alpha").unwrap_or(1.0).clamp(0.0, 1.0); + Some(c.with_alpha((f64::from(c.a()) * alpha).round() as u8)) } diff --git a/crates/map/src/qgis/layout_surround_tests.rs b/crates/map/src/qgis/layout_surround_tests.rs index 50da502d44..44d86ce44b 100644 --- a/crates/map/src/qgis/layout_surround_tests.rs +++ b/crates/map/src/qgis/layout_surround_tests.rs @@ -390,3 +390,90 @@ fn numeric_sizes_forced_bold_and_switched_off_overviews_are_said() { assert!(said(&report, part), "{part}: {:?}", report.notes); } } + +/// A north arrow read before its map, whose map a full layout then leaves out, is left out too and +/// said only as that: none of its own notes, nor its placement's, are said. +#[test] +fn a_surround_whose_map_a_full_layout_leaves_out_says_only_that() { + let mut items = String::new(); + for i in 0..499 { + items.push_str(&format!(r#""#)); + } + items.push_str(r#""#); + items.push_str(&map("{m}", 10.0, 3, "")); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + assert!(p.layouts[0].layout.elements.iter().all(|e| !matches!(e.kind, ElementKind::NorthArrow { .. }))); + let texts: Vec<&str> = report.notes.iter().map(|n| n.text.as_str()).collect(); + assert_eq!( + texts, + [ + "its print layouts' scale bars and north arrows whose map isn't on their page, or is left out (1)", + "its print layouts' elements past the 500 a layout keeps (1)" + ] + ); +} + +/// A scale bar with no unit label written prints its units' abbreviation; one written empty prints +/// none, as QGIS does. +#[test] +fn a_scale_bar_without_a_unit_label_prints_its_abbreviation() { + let label = |attrs: &str| { + let p = read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", attrs, BAR_COLOURS))), &mut Report::default()); + match &bars(&p.layouts[0].layout)[0].kind { + ElementKind::ScaleBar { unit_label, .. } => unit_label.clone(), + _ => None, + } + }; + assert_eq!(label(r#"style="Single Box" unitType="km""#), None); + assert_eq!(label(r#"style="Single Box" unitType="km" unitLabelString="""#), Some(String::new())); +} + +/// An overview with neither fill nor outline draws nothing, in QGIS as here: no indicator, nothing +/// said. +#[test] +fn an_invisible_overview_draws_nothing() { + let invisible = r#""#; + let items = format!("{}{}", map("{main}", 10.0, 1, ""), map("{ov}", 115.0, 0, invisible)); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + assert!(p.layouts[0].layout.elements.iter().all(|e| e.kind.extent_indicators().is_empty())); + assert!(report.notes.is_empty(), "{:?}", report.notes); +} + +/// A scale bar's colours take their symbol's own opacity. +#[test] +fn a_scale_bars_colours_take_their_symbols_opacity() { + let symbol = |tag: &str, c: &str| { + format!( + r#"<{tag}>"# + ) + }; + let children = symbol("fillSymbol1", "0,0,0,255") + &symbol("fillSymbol2", "255,255,255,255"); + let p = read( + &layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", r#"style="Single Box" segmentSizeMode="1""#, &children))), + &mut Report::default(), + ); + assert!(matches!(bars(&p.layouts[0].layout)[0].kind, ElementKind::ScaleBar { color, fill, .. } if color.a() == 64 && fill.a() == 64)); +} + +/// A scale bar and north arrow that link say their placement's notes as other items do +/// (blending, left out of exports); an overview's hairline outline (no width) is drawn thin. +#[test] +fn linked_surrounds_say_their_placement_and_a_hairline_overview_is_drawn() { + let arrow = r#""#; + let hairline = r#""#; + let items = format!( + "{}{}{arrow}{}", + map("{m}", 10.0, 1, ""), + map("{o}", 115.0, 0, hairline), + bar("{m}", r#"style="Single Box" segmentSizeMode="1" excludeFromExports="1""#, BAR_COLOURS) + ); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + assert!(said(&report, "items' blending modes, drawn normally (1)"), "{:?}", report.notes); + assert!(said(&report, "items left out of exports, kept hidden (1)"), "{:?}", report.notes); + let shown: Vec = p.layouts[0].layout.elements.iter().flat_map(|e| e.kind.extent_indicators()).collect(); + assert_eq!(shown.len(), 1); + assert!(shown[0].width > 0.0 && shown[0].color == Rgba::rgb(0, 0, 200)); +} From 83e6c94767322bf83c42815f6ebbb8877103676c Mon Sep 17 00:00:00 2001 From: strebdom Date: Tue, 1 Dec 2026 20:43:04 +0100 Subject: [PATCH 4/8] fix(map): QGIS layout scale bars' fills switched off, a named hairline width, overviews capped as read - A scale bar's fill or line switched off draws nothing of it: its dark divisions so drawn in its text's colour, said; its light ones transparent. - An overview's hairline outline is drawn at a named width, a pixel at 96 dpi. - A map item's overviews are capped at the 16 a frame outlines as they are read; one of a map already outlined is kept once, said. - The module doc says what the reader brings in now. --- crates/map/src/qgis/layout.rs | 18 +++++++-- crates/map/src/qgis/layout/surround.rs | 31 ++++++++++++--- crates/map/src/qgis/layout_surround_tests.rs | 41 +++++++++++++++++++- 3 files changed, 80 insertions(+), 10 deletions(-) diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index cc22d6b2b7..7c72302302 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -3,11 +3,12 @@ //! its labels text, its pictures pictures (read by the engine, from the file each names), its //! rectangles and ellipses those shapes, and its lines and polygons straight lines along their //! edges. Items are drawn in QGIS's order (its `zValue`), placed where QGIS draws them on their -//! page in millimetres, a turned label turned about its centre as QGIS turns it. +//! page in millimetres, a turned label turned about its centre as QGIS turns it. Its scale bars, +//! north arrows and map overviews show their map's frame ([`surround`], piece 12b). //! -//! What a RustGIS layout has no place for is noted, counted over all the layouts: scale bars, -//! legends, north arrows, tables, HTML and the other item kinds, map grids and overviews, the -//! atlas, groups, blending, and settings set by expressions. A QGIS 2 composer isn't read. +//! What a RustGIS layout has no place for is noted, counted over all the layouts: legends, +//! tables, HTML and the other item kinds, map grids, the atlas, groups, blending, and settings set +//! by expressions. A QGIS 2 composer isn't read. use roxmltree::Node; @@ -160,6 +161,8 @@ pub(super) struct Tally { /// Overviews past what a frame outlines, and scale bars' text bold, italic, underlined, /// buffered or shadowed. overviews_past: usize, + /// Overviews of a map another overview of the same item already outlines, kept once. + overviews_twice: usize, bar_text_styles: usize, linked: Vec, /// Scale bars and north arrows whose map isn't on their page, left out; overviews of a map @@ -1288,6 +1291,7 @@ impl Tally { (self.unlinked, "scale bars and north arrows whose map isn't on their page, or is left out"), (self.overviews_unlinked, "map overviews of their own map, or of a map not on their page or left out"), (self.overviews_off, "map overviews and grids switched off"), + (self.overviews_twice, "map overviews of a map their map item already outlines (kept once)"), (self.overviews_past, &format!("map overviews past the {} a frame outlines", crate::layout::MAX_EXTENT_INDICATORS)), (self.bar_subdivisions, "scale bars' subdivisions"), (self.tables, "attribute tables"), @@ -1466,3 +1470,9 @@ fn unit_mm(unit: &str, dpi: f64) -> Option { _ => return None, }) } + +/// The width an overview's hairline outline is drawn at, for tests. +#[cfg(test)] +pub(super) fn surround_hairline() -> f64 { + surround::HAIRLINE_PT +} diff --git a/crates/map/src/qgis/layout/surround.rs b/crates/map/src/qgis/layout/surround.rs index 33d29352bc..308d364a6c 100644 --- a/crates/map/src/qgis/layout/surround.rs +++ b/crates/map/src/qgis/layout/surround.rs @@ -8,6 +8,10 @@ use crate::layout::{ }; use crate::layout::{ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits}; +/// The width (points) an overview's hairline outline (QGIS's outline of no width, a pixel on +/// screen) is drawn at: a pixel at 96 dpi, as a layout point is. +pub(super) const HAIRLINE_PT: f64 = 1.0; + /// What an element links to its map item as. pub(super) enum Link { /// A scale bar or a north arrow: its `frame`. @@ -155,6 +159,8 @@ pub(super) fn link(layouts: &mut [ProjectLayout], tally: &mut Tally) { /// no outline, its fill's colour opaque. pub(super) fn overviews(item: Node, page: usize, element: u32, tally: &mut Tally) { let own = item.attribute("uuid").map(str::trim).unwrap_or_default(); + // The maps its overviews outline: one outlined twice is kept once, as a layout keeps it. + let mut kept: Vec = Vec::new(); for o in item.children().filter(|c| c.has_tag_name("ComposerMapOverview")) { // Switched off, QGIS draws it not; said, as an indicator can't be kept switched off. if o.attribute("show") == Some("0") { @@ -169,14 +175,14 @@ pub(super) fn overviews(item: Node, page: usize, element: u32, tally: &mut Tally } let mut counts = Counts::default(); let (fill, outline, width, dash) = fill_of(o, &|c| c, &mut counts.notes); - // An outline of no width is QGIS's hairline: RustGIS's thinnest indicator's width. + // An outline of no width is QGIS's hairline, drawn a pixel wide. let drawn_outline = outline.a() > 0; // Neither fill nor outline: QGIS draws nothing of it, nor does RustGIS. if !drawn_outline && fill.a() == 0 { continue; } let (color, width) = - if drawn_outline { (outline, if width > 0.0 { width } else { 1.0 }) } else { (fill.with_alpha(255), INDICATOR_WIDTH) }; + if drawn_outline { (outline, if width > 0.0 { width } else { HAIRLINE_PT }) } else { (fill.with_alpha(255), INDICATOR_WIDTH) }; counts.overview_fills += usize::from(fill.a() > 0); counts.overview_ways += usize::from( o.attribute("inverted") == Some("1") @@ -184,6 +190,16 @@ pub(super) fn overviews(item: Node, page: usize, element: u32, tally: &mut Tally || num(o, "blendMode").is_some_and(|b| b != 0.0) || dash.is_some(), ); + if kept.contains(&map) { + tally.overviews_twice += 1; + continue; + } + // A frame outlines no more than a layout keeps: those past it said, and not held. + if kept.len() >= MAX_EXTENT_INDICATORS { + tally.overviews_past += 1; + continue; + } + kept.push(map.clone()); tally.linked.push(Linked { page, element, map, link: Link::Overview { color, width }, counts }); } } @@ -291,10 +307,13 @@ pub(super) fn scale_bar_item( symbol_color(item, "fillSymbol2").or_else(|| child(item, "fillColor2").and_then(rgba_of)).unwrap_or(Rgba::rgb(255, 255, 255)); // RustGIS draws a bar's lines, dark divisions and labels in one colour: its dark divisions' // (a line's lines'); another in QGIS's is drawn in it, said. - let color = if line { stroke } else { dark }; + let drawn = if line { stroke } else { dark }; + // Switched off (transparent), RustGIS would draw the bar's labels so too: its text's colour, + // said with the colours below. + let color = if drawn.a() == 0 { text_color } else { drawn }; // Its ticks' (a line's divisions' and subdivisions') colours too. let ticks = ["divisionLineSymbol", "subdivisionLineSymbol"].iter().filter_map(|t| symbol_color(item, t)).any(|c| line && c != color); - counts.bar_colors += usize::from(text_color != color || (!line && stroke != color) || ticks); + counts.bar_colors += usize::from(drawn.a() == 0 || text_color != color || (!line && stroke != color) || ticks); let (units, abbr) = match item.attribute("unitType").map(str::trim).unwrap_or("meters") { "meters" | "m" => (ScaleUnits::Meters, Some("m")), "km" | "kilometers" => (ScaleUnits::Kilometers, Some("km")), @@ -409,6 +428,8 @@ fn symbol_color(item: Node, tag: &str) -> Option { let layer = symbol.descendants().find(|d| d.has_tag_name("layer"))?; let props = super::super::props(layer); let c = super::super::prop(&props, "color").or_else(|| super::super::prop(&props, "line_color")).and_then(color)?; - let alpha = num(symbol, "alpha").unwrap_or(1.0).clamp(0.0, 1.0); + // A fill or line switched off (`style`, `line_style` "no") draws nothing: transparent. + let off = |k: &str| super::super::prop(&props, k).is_some_and(|v| v.trim() == "no"); + let alpha = if off("style") || off("line_style") { 0.0 } else { num(symbol, "alpha").unwrap_or(1.0).clamp(0.0, 1.0) }; Some(c.with_alpha((f64::from(c.a()) * alpha).round() as u8)) } diff --git a/crates/map/src/qgis/layout_surround_tests.rs b/crates/map/src/qgis/layout_surround_tests.rs index 44d86ce44b..42b8d05980 100644 --- a/crates/map/src/qgis/layout_surround_tests.rs +++ b/crates/map/src/qgis/layout_surround_tests.rs @@ -475,5 +475,44 @@ fn linked_surrounds_say_their_placement_and_a_hairline_overview_is_drawn() { assert!(said(&report, "items left out of exports, kept hidden (1)"), "{:?}", report.notes); let shown: Vec = p.layouts[0].layout.elements.iter().flat_map(|e| e.kind.extent_indicators()).collect(); assert_eq!(shown.len(), 1); - assert!(shown[0].width > 0.0 && shown[0].color == Rgba::rgb(0, 0, 200)); + assert_eq!((shown[0].width, shown[0].color), (super::layout::surround_hairline(), Rgba::rgb(0, 0, 200))); +} + +/// A scale bar whose dark divisions' fill is switched off draws in its text's colour, said; its +/// light divisions switched off are transparent. +#[test] +fn a_scale_bars_fill_switched_off_is_said() { + let fill = |tag: &str, style: &str| { + format!( + r#"<{tag}>"# + ) + }; + let children = fill("fillSymbol1", "no") + &fill("fillSymbol2", "no"); + let text = bar("{m}", r#"style="Single Box" segmentSizeMode="1""#, &children) + .replace(r#"textColor="0,0,0,255""#, r#"textColor="20,40,60,255""#); + let mut report = Report::default(); + let p = read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &text)), &mut report); + assert!( + matches!(bars(&p.layouts[0].layout)[0].kind, ElementKind::ScaleBar { color, fill, .. } if color == Rgba::rgb(20, 40, 60) && fill.a() == 0) + ); + assert!(said(&report, "scale bars whose lines, labels and dark divisions differ in colour, drawn in one (1)"), "{:?}", report.notes); +} + +/// A map item's overviews past what a frame outlines are said as past it, and not held; a second +/// overview of the same map is kept once, said. +#[test] +fn overviews_past_a_frames_are_said() { + let targets: String = (0..18).map(|i| map(&format!("{{t{i}}}"), 10.0, 1, "")).collect(); + let mut overviews: String = (0..18).map(|i| format!(r#""#)).collect(); + overviews.push_str(r#""#); + let items = format!("{targets}{}", map("{ov}", 115.0, 0, &overviews)); + let mut report = Report::default(); + let p = read(&layout(PAGE, &items), &mut report); + let mut shown: Vec = p.layouts[0].layout.elements.iter().flat_map(|e| e.kind.extent_indicators()).map(|i| i.of).collect(); + assert_eq!(shown.len(), 16); + shown.sort_unstable(); + shown.dedup(); + assert_eq!(shown.len(), 16, "each frame outlined once"); + assert!(said(&report, "map overviews past the 16 a frame outlines (2)"), "{:?}", report.notes); + assert!(said(&report, "map overviews of a map their map item already outlines (kept once) (1)"), "{:?}", report.notes); } From 1c2dc59bebd0e9bd6b7b4f40405faad3b691acb6 Mon Sep 17 00:00:00 2001 From: strebdom Date: Tue, 1 Dec 2026 21:07:26 +0100 Subject: [PATCH 5/8] fix(map): QGIS layout scale bars' division values said; symbol layers switched off give no colour - Every scale bar's division values are said as RustGIS's own, chosen to fit its box (QGIS's fixed, or fitted between its bar's widths). - A scale bar's and a page's colour come from the symbol's first layer switched on; a symbol with none switched on draws nothing. - The hairline width's doc names the layout point (1/96 inch). --- crates/map/src/qgis/layout.rs | 10 ++++---- crates/map/src/qgis/layout/surround.rs | 24 +++++++++++------ crates/map/src/qgis/layout_surround_tests.rs | 27 ++++++++++++++++---- crates/map/src/qgis/layout_tests.rs | 19 ++++++++++++++ docs/user-guide/workspace.md | 4 +-- 5 files changed, 64 insertions(+), 20 deletions(-) diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index 7c72302302..b8d3a5715b 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -382,13 +382,13 @@ fn read_layout(node: Node, dir: &str, title: &Title, room: usize, tally: &mut Ta layouts } -/// The paper a fill symbol under `node` gives: `None` with no symbol, `Some(None)` for white (or a -/// colour that doesn't read). +/// The paper a fill symbol under `node` gives (its first layer switched on): `None` with no +/// symbol, `Some(None)` for white (or a colour that doesn't read, or no layer switched on). fn paper_of(node: Node) -> Option> { let s = node.children().find(|c| c.has_tag_name("symbol"))?; Some( - s.descendants() - .find(|d| d.has_tag_name("layer")) + s.children() + .find(|d| d.has_tag_name("layer") && d.attribute("enabled") != Some("0")) .and_then(|l| super::prop(&super::props(l), "color").and_then(color)) .filter(|c| *c != Rgba::rgb(255, 255, 255)), ) @@ -1363,7 +1363,7 @@ impl Tally { crate::layout::MAX_SCALE_BEFORE_ZERO ), ), - (self.bar_values, "scale bars' fixed values of a division, chosen anew to fit their box"), + (self.bar_values, "scale bars' division values, chosen anew to fit their box"), ( self.bar_layout, "scale bars' heights, line widths, alignment in their box or labels over their divisions' middles, as RustGIS draws them", diff --git a/crates/map/src/qgis/layout/surround.rs b/crates/map/src/qgis/layout/surround.rs index 308d364a6c..e2932213bd 100644 --- a/crates/map/src/qgis/layout/surround.rs +++ b/crates/map/src/qgis/layout/surround.rs @@ -8,8 +8,8 @@ use crate::layout::{ }; use crate::layout::{ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits}; -/// The width (points) an overview's hairline outline (QGIS's outline of no width, a pixel on -/// screen) is drawn at: a pixel at 96 dpi, as a layout point is. +/// The width an overview's hairline outline (QGIS's outline of no width, a pixel on screen) is +/// drawn at, in layout points (1/96 inch, not the typographic 1/72): a pixel at 96 dpi. pub(super) const HAIRLINE_PT: f64 = 1.0; /// What an element links to its map item as. @@ -343,8 +343,9 @@ pub(super) fn scale_bar_item( counts.bar_divisions += usize::from(more || more_before); // Subdivisions of its divisions (drawn by QGIS's line styles): left out, said. counts.bar_subdivisions += usize::from(line && num(item, "numSubdivisions").is_some_and(|n| n > 1.0)); - // A fixed value a division (`segmentSizeMode` 0): RustGIS picks its own to fit the bar's box. - counts.bar_values += usize::from(num(item, "segmentSizeMode").is_none_or(|m| m == 0.0)); + // Its division values: QGIS's fixed (`segmentSizeMode` 0) or fitted between its bar's least and + // most widths (1); RustGIS picks its own to fill the bar's box, said for every bar. + counts.bar_values += 1; // Its labels over the middle of their division (1), its bar in the middle or right of its box, // its height and its lines' width other than RustGIS's (3 mm, 0.3 mm): drawn as RustGIS draws // a bar. @@ -417,15 +418,22 @@ fn text_style(item: Node, counts: &mut Counts) -> (f64, Rgba, Option) { /// A number of a symbol held under `tag` (its first layer's property `key`). fn symbol_number(item: Node, tag: &str, key: &str) -> Option { - let layer = child(item, tag)?.descendants().find(|d| d.has_tag_name("layer"))?; + let symbol = child(item, tag)?.descendants().find(|d| d.has_tag_name("symbol"))?; + let layer = first_enabled(symbol)?; super::super::prop(&super::super::props(layer), key)?.trim().parse::().ok().filter(|v| v.is_finite()) } -/// The colour of a symbol held under `tag` (its first layer's fill or line colour), faded by the -/// symbol's own opacity (`alpha`). +/// A symbol's first layer switched on (`enabled` other than 0), as the symbol reader takes them. +fn first_enabled<'a, 'i>(symbol: Node<'a, 'i>) -> Option> { + symbol.children().find(|c| c.has_tag_name("layer") && c.attribute("enabled") != Some("0")) +} + +/// The colour of a symbol held under `tag` (its first layer's fill or line colour, of those +/// switched on), faded by the symbol's own opacity (`alpha`); a symbol with none switched on draws +/// nothing: transparent. fn symbol_color(item: Node, tag: &str) -> Option { let symbol = child(item, tag)?.descendants().find(|d| d.has_tag_name("symbol"))?; - let layer = symbol.descendants().find(|d| d.has_tag_name("layer"))?; + let Some(layer) = first_enabled(symbol) else { return Some(Rgba::new(0, 0, 0, 0)) }; let props = super::super::props(layer); let c = super::super::prop(&props, "color").or_else(|| super::super::prop(&props, "line_color")).and_then(color)?; // A fill or line switched off (`style`, `line_style` "no") draws nothing: transparent. diff --git a/crates/map/src/qgis/layout_surround_tests.rs b/crates/map/src/qgis/layout_surround_tests.rs index 42b8d05980..754d38d758 100644 --- a/crates/map/src/qgis/layout_surround_tests.rs +++ b/crates/map/src/qgis/layout_surround_tests.rs @@ -78,7 +78,9 @@ fn a_scale_bar_comes_in_showing_its_maps_frame() { assert!((text_size - 9.0).abs() < 1e-9); assert_eq!(font_name.as_deref(), Some("DejaVu Sans")); assert_eq!((*color, *fill), (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 255, 255))); - assert!(report.notes.is_empty(), "{:?}", report.notes); + // Only its division values, RustGIS's own (QGIS fits them within its bar's widths). + let texts: Vec<&str> = report.notes.iter().map(|n| n.text.as_str()).collect(); + assert_eq!(texts, ["its print layouts' scale bars' division values, chosen anew to fit their box (1)"]); } /// QGIS's styles as RustGIS's nearest: a single box, ticks up and a stepped line as they are; a @@ -128,7 +130,8 @@ fn scale_bar_units_and_divisions_are_kept_or_said() { }; let (kind, report) = one(r#"style="Single Box" segmentSizeMode="1" unitType="km" unitLabelString="Kilometres""#); assert!(matches!(kind, ElementKind::ScaleBar { units: ScaleUnits::Kilometers, unit_label: Some(ref l), .. } if l == "Kilometres")); - assert!(report.notes.is_empty(), "{:?}", report.notes); + let texts: Vec<&str> = report.notes.iter().map(|n| n.text.as_str()).collect(); + assert_eq!(texts, ["its print layouts' scale bars' division values, chosen anew to fit their box (1)"]); let (kind, report) = one(r#"style="Single Box" segmentSizeMode="1" unitType="nautical miles" unitLabelString="NM""#); assert!(matches!(kind, ElementKind::ScaleBar { units: ScaleUnits::Auto, .. })); assert!(said(&report, "in RustGIS's choice of units (1)"), "{:?}", report.notes); @@ -136,7 +139,7 @@ fn scale_bar_units_and_divisions_are_kept_or_said() { assert!(matches!(kind, ElementKind::ScaleBar { divisions: 10, divisions_before_zero: 2, .. })); assert!(said(&report, "scale bars' divisions brought within RustGIS's (1 to 10, 2 before zero) (1)"), "{:?}", report.notes); assert!(said(&report, "scale bars' subdivisions (1)"), "{:?}", report.notes); - assert!(said(&report, "scale bars' fixed values of a division, chosen anew to fit their box (1)"), "{:?}", report.notes); + assert!(said(&report, "scale bars' division values, chosen anew to fit their box (1)"), "{:?}", report.notes); } /// A scale bar whose lines, labels and dark divisions differ in colour is drawn in its dark @@ -336,13 +339,15 @@ fn the_corpus_surrounds_show_the_main_map() { let shown = overview.kind.extent_indicators(); assert_eq!(shown.len(), 1); assert_eq!((shown[0].of, shown[0].color), (main.id, Rgba::rgb(200, 0, 0))); - // What it says: the north arrow and the numeric scale's format, nothing more. + // What it says: the north arrow, the numeric scale's format and the bars' division values, + // nothing more. let texts: Vec<&str> = report.notes.iter().map(|n| n.text.as_str()).collect(); assert_eq!( texts, [ "its print layouts' north arrows (pictures turned with a map), drawn as RustGIS's arrow (1)", - "its print layouts' numeric scale bars, printing the scale in RustGIS's format (1:25,000) (1)" + "its print layouts' numeric scale bars, printing the scale in RustGIS's format (1:25,000) (1)", + "its print layouts' scale bars' division values, chosen anew to fit their box (3)" ] ); } @@ -516,3 +521,15 @@ fn overviews_past_a_frames_are_said() { assert!(said(&report, "map overviews past the 16 a frame outlines (2)"), "{:?}", report.notes); assert!(said(&report, "map overviews of a map their map item already outlines (kept once) (1)"), "{:?}", report.notes); } + +/// A symbol layer switched off (`enabled="0"`) gives no colour: a light division fill switched off +/// is transparent. +#[test] +fn a_switched_off_symbol_layer_gives_no_colour() { + let light = r#""#; + let p = read( + &layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", r#"style="Single Box" segmentSizeMode="1""#, light))), + &mut Report::default(), + ); + assert!(matches!(bars(&p.layouts[0].layout)[0].kind, ElementKind::ScaleBar { fill, .. } if fill.a() == 0)); +} diff --git a/crates/map/src/qgis/layout_tests.rs b/crates/map/src/qgis/layout_tests.rs index 37bd57750d..97a23a39f4 100644 --- a/crates/map/src/qgis/layout_tests.rs +++ b/crates/map/src/qgis/layout_tests.rs @@ -1005,3 +1005,22 @@ fn a_label_read_short_is_said_cut() { read(&qgs("TT"), &mut report); assert!(said(&report, "labels longer than 5000 characters, cut there (1)"), "{:?}", report.notes); } + +/// A page's fill takes its first layer switched on: one switched off gives no colour. +#[test] +fn a_pages_switched_off_fill_layer_gives_no_paper() { + let layer = |enabled: &str, c: &str| { + format!( + r#""# + ) + }; + let qgs = |layers: &str| { + format!( + r#"{layers}"# + ) + }; + let p = read(&qgs(&(layer("0", "0,0,255,255") + &layer("1", "255,255,200,255"))), &mut Report::default()); + assert_eq!(p.layouts[0].layout.paper, Some(Rgba::rgb(255, 255, 200))); + let p = read(&qgs(&layer("0", "0,0,255,255")), &mut Report::default()); + assert_eq!(p.layouts[0].layout.paper, None); +} diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index c8120c0d33..078df5d9ea 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -444,8 +444,8 @@ lines along their edges, with arrowheads. Scale bars, north arrows and map overv frame of the map item they follow, on their page: a scale bar in RustGIS's nearest style (a single box, ticks or a stepped line), with its label placement and, within what RustGIS takes, its units (metres, kilometres, feet or miles; others RustGIS's choice, with its own abbreviation), -divisions, text size and unit label, its division values chosen to fit its box (each change -noted, and fixed values in QGIS too); a numeric scale bar as a text printing `{scale}`, the scale +divisions, text size and unit label, each change noted; its division values chosen anew to fit +its box, noted; a numeric scale bar as a text printing `{scale}`, the scale of the layout's first map (noted when it follows another); a north arrow (QGIS's is a picture) as RustGIS's arrow, noted; an overview as an extent indicator in its outline's colour, its fill noted. One whose map From 2ed1de8f7ca521241e945bb1e68b38a6278eb340 Mon Sep 17 00:00:00 2001 From: strebdom Date: Tue, 1 Dec 2026 21:32:30 +0100 Subject: [PATCH 6/8] fix(map): QGIS layout scale bars drawn with symbols beyond a plain colour are said - A scale bar whose symbols have several layers, a pattern, a dash, an outline of their own or another kind is said as drawn in a plain colour. - Subdivisions are said for line styles only, as QGIS draws them on those only. --- crates/map/src/qgis/layout.rs | 6 ++++ crates/map/src/qgis/layout/surround.rs | 26 ++++++++++++++- crates/map/src/qgis/layout_surround_tests.rs | 34 ++++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index b8d3a5715b..07290a7e57 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -164,6 +164,8 @@ pub(super) struct Tally { /// Overviews of a map another overview of the same item already outlines, kept once. overviews_twice: usize, bar_text_styles: usize, + /// Scale bars drawn with a symbol of several layers, patterned, dashed or of another kind. + bar_symbols: usize, linked: Vec, /// Scale bars and north arrows whose map isn't on their page, left out; overviews of a map /// not on theirs, not drawn. @@ -1345,6 +1347,10 @@ impl Tally { (self.true_north, "north arrows to true north or offset from the map's, pointing to the map's north"), (self.overview_fills, "map overviews' fills, drawn as their outlines"), (self.overview_ways, "map overviews inverted, centring their map, blended or dashed, drawn as plain outlines"), + ( + self.bar_symbols, + "scale bars drawn with symbols of several layers, patterned, dashed, outlined or of another kind, in a plain colour", + ), (self.bar_text_styles, "scale bars' text bold, italic, underlined, buffered or shadowed, drawn plain"), (self.numeric_formats, "numeric scale bars, printing the scale in RustGIS's format (1:25,000)"), (self.numeric_sizes, "numeric scale bars' text sizes outside 1 to 400 pt, drawn at the nearest"), diff --git a/crates/map/src/qgis/layout/surround.rs b/crates/map/src/qgis/layout/surround.rs index e2932213bd..fa77f031bd 100644 --- a/crates/map/src/qgis/layout/surround.rs +++ b/crates/map/src/qgis/layout/surround.rs @@ -73,6 +73,7 @@ counts!( bar_layout, bar_text_sizes, bar_text_styles, + bar_symbols, cut_texts, braces, overview_fills, @@ -313,6 +314,11 @@ pub(super) fn scale_bar_item( let color = if drawn.a() == 0 { text_color } else { drawn }; // Its ticks' (a line's divisions' and subdivisions') colours too. let ticks = ["divisionLineSymbol", "subdivisionLineSymbol"].iter().filter_map(|t| symbol_color(item, t)).any(|c| line && c != color); + // The symbols it draws with (a box's fills and outline, a line's line and ticks): one of several + // layers, patterned, dashed, outlined or of another kind, drawn in a plain colour. + let drawn_with: &[&str] = + if line { &["lineSymbol", "divisionLineSymbol", "subdivisionLineSymbol"] } else { &["lineSymbol", "fillSymbol1", "fillSymbol2"] }; + counts.bar_symbols += usize::from(drawn_with.iter().any(|t| symbol_not_plain(item, t))); counts.bar_colors += usize::from(drawn.a() == 0 || text_color != color || (!line && stroke != color) || ticks); let (units, abbr) = match item.attribute("unitType").map(str::trim).unwrap_or("meters") { "meters" | "m" => (ScaleUnits::Meters, Some("m")), @@ -341,7 +347,8 @@ pub(super) fn scale_bar_item( let (divisions, more) = count("numSegments", MAX_SCALE_DIVISIONS, 1); let (before, more_before) = count("numSegmentsLeft", MAX_SCALE_BEFORE_ZERO, 0); counts.bar_divisions += usize::from(more || more_before); - // Subdivisions of its divisions (drawn by QGIS's line styles): left out, said. + // Subdivisions of its divisions: QGIS draws them on its line styles only (a box bar's are + // drawn as none, as QGIS 4.4 does); left out, said. counts.bar_subdivisions += usize::from(line && num(item, "numSubdivisions").is_some_and(|n| n > 1.0)); // Its division values: QGIS's fixed (`segmentSizeMode` 0) or fitted between its bar's least and // most widths (1); RustGIS picks its own to fill the bar's box, said for every bar. @@ -428,6 +435,23 @@ fn first_enabled<'a, 'i>(symbol: Node<'a, 'i>) -> Option> { symbol.children().find(|c| c.has_tag_name("layer") && c.attribute("enabled") != Some("0")) } +/// Whether a symbol held under `tag` is more than a plain colour: several layers switched on, or +/// its layer not a simple fill or line, or patterned or dashed (a `style` or `line_style` other +/// than solid or none, a dash of its own), or a fill with an outline of its own. +fn symbol_not_plain(item: Node, tag: &str) -> bool { + let Some(symbol) = child(item, tag).and_then(|t| t.descendants().find(|d| d.has_tag_name("symbol"))) else { return false }; + let mut on = symbol.children().filter(|c| c.has_tag_name("layer") && c.attribute("enabled") != Some("0")); + let Some(layer) = on.next() else { return false }; + if on.next().is_some() || !matches!(layer.attribute("class"), Some("SimpleFill" | "SimpleLine") | None) { + return true; + } + let props = super::super::props(layer); + let prop = |k: &str| super::super::prop(&props, k).map(str::trim); + ["style", "line_style"].iter().any(|k| prop(k).is_some_and(|v| !matches!(v, "solid" | "no"))) + || prop("use_custom_dash") == Some("1") + || (layer.attribute("class") == Some("SimpleFill") && prop("outline_style").is_some_and(|v| v != "no")) +} + /// The colour of a symbol held under `tag` (its first layer's fill or line colour, of those /// switched on), faded by the symbol's own opacity (`alpha`); a symbol with none switched on draws /// nothing: transparent. diff --git a/crates/map/src/qgis/layout_surround_tests.rs b/crates/map/src/qgis/layout_surround_tests.rs index 754d38d758..743c7450b8 100644 --- a/crates/map/src/qgis/layout_surround_tests.rs +++ b/crates/map/src/qgis/layout_surround_tests.rs @@ -533,3 +533,37 @@ fn a_switched_off_symbol_layer_gives_no_colour() { ); assert!(matches!(bars(&p.layouts[0].layout)[0].kind, ElementKind::ScaleBar { fill, .. } if fill.a() == 0)); } + +/// A scale bar drawn with a symbol of several layers, or a patterned one, is said; a plain one +/// isn't. +#[test] +fn scale_bars_symbols_beyond_a_plain_colour_are_said() { + let fill = |tag: &str, layers: &str| format!(r#"<{tag}>{layers}"#); + let layer = |c: &str, style: &str| { + format!( + r#""# + ) + }; + let one = |children: &str| { + let mut report = Report::default(); + read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", r#"style="Single Box" segmentSizeMode="1""#, children))), &mut report); + said( + &report, + "scale bars drawn with symbols of several layers, patterned, dashed, outlined or of another kind, in a plain colour (1)", + ) + }; + assert!(one(&fill("fillSymbol2", &(layer("255,255,255,255", "solid") + &layer("255,0,0,255", "solid"))))); + assert!(one(&fill("fillSymbol2", &layer("255,255,255,255", "horizontal")))); + assert!(!one(&fill("fillSymbol2", &layer("255,255,255,255", "solid")))); + // A fill outlined of its own; a second layer switched off stays plain. + let outlined = layer("255,255,255,255", "solid") + .replace("", r#""#); + assert!(one(&fill("fillSymbol2", &outlined))); + let off = layer("255,0,0,255", "solid").replace(r#"enabled="1""#, r#"enabled="0""#); + assert!(!one(&fill("fillSymbol2", &(layer("255,255,255,255", "solid") + &off)))); + // A line style's tick dashed of its own. + let tick = r#""#; + let mut report = Report::default(); + read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", r#"style="Line Ticks Up" segmentSizeMode="1""#, tick))), &mut report); + assert!(said(&report, "in a plain colour (1)"), "{:?}", report.notes); +} From 567114667c59eebfeac25eddf06b0889609841ab Mon Sep 17 00:00:00 2001 From: strebdom Date: Tue, 1 Dec 2026 22:04:44 +0100 Subject: [PATCH 7/8] fix(map): QGIS layout bar line widths read in their unit; page fills beyond a colour said - A scale bar's line width is compared in millimetres from its unit (any case, none as millimetres); one in map units is said. - A page's fill switched off gives no paper; one of several layers, a pattern, an outline or another kind is said as drawn in a plain colour. --- crates/map/src/qgis/layout.rs | 48 ++++++++++++++------ crates/map/src/qgis/layout/surround.rs | 28 ++++++++++-- crates/map/src/qgis/layout_surround_tests.rs | 27 +++++++++++ crates/map/src/qgis/layout_tests.rs | 31 +++++++++++++ 4 files changed, 114 insertions(+), 20 deletions(-) diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index 07290a7e57..c451bc2094 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -164,6 +164,8 @@ pub(super) struct Tally { /// Overviews of a map another overview of the same item already outlines, kept once. overviews_twice: usize, bar_text_styles: usize, + /// Pages whose fill is more than a colour (several layers, a pattern, another kind). + papers: usize, /// Scale bars drawn with a symbol of several layers, patterned, dashed or of another kind. bar_symbols: usize, linked: Vec, @@ -267,7 +269,7 @@ fn read_layout(node: Node, dir: &str, title: &Title, room: usize, tally: &mut Ta // the first [`MAX_PAGES`] and reads. let collection = child(node, "PageCollection"); // The paper: a page's fill symbol's colour (when not white), else its collection's. - let paper = collection.and_then(paper_of).flatten(); + let collection_paper = collection.and_then(paper_of).unwrap_or((None, false)); let entries = collection.map_or(0, |pc| pc.children().filter(|c| c.has_tag_name("LayoutItem") && c.attribute("type") == Some(PAGE)).count()); tally.pages_left += entries.saturating_sub(MAX_PAGE_NODES); @@ -277,11 +279,15 @@ fn read_layout(node: Node, dir: &str, title: &Title, room: usize, tally: &mut Ta .filter(|c| c.has_tag_name("LayoutItem") && c.attribute("type") == Some(PAGE)) .take(MAX_PAGE_NODES) .enumerate() - .map(|(i, p)| Slot { - top: p.attribute("position").and_then(|v| pair(v, dpi)).map(|(_, y)| y), - page: if i < MAX_PAGES { Page::read(p, dpi) } else { None }, - paper: paper_of(p).unwrap_or(paper), - layout: None, + .map(|(i, p)| { + let (paper, paper_rough) = paper_of(p).unwrap_or(collection_paper); + Slot { + top: p.attribute("position").and_then(|v| pair(v, dpi)).map(|(_, y)| y), + page: if i < MAX_PAGES { Page::read(p, dpi) } else { None }, + paper, + paper_rough, + layout: None, + } }) .collect() }) @@ -291,7 +297,8 @@ fn read_layout(node: Node, dir: &str, title: &Title, room: usize, tally: &mut Ta // A layout with no page QGIS can read: A4 portrait, as QGIS starts one, said (the pages // that don't read counted above). tally.no_pages += 1; - pages = vec![Slot { top: Some(0.0), page: Some(Page { top: 0.0, w: 210.0, h: 297.0 }), paper, layout: None }]; + let (paper, paper_rough) = collection_paper; + pages = vec![Slot { top: Some(0.0), page: Some(Page { top: 0.0, w: 210.0, h: 297.0 }), paper, paper_rough, layout: None }]; } if child(node, "Atlas").is_some_and(|a| a.attribute("enabled") == Some("1")) { tally.atlases += 1; @@ -316,6 +323,7 @@ fn read_layout(node: Node, dir: &str, title: &Title, room: usize, tally: &mut Ta }; let mut layout = Layout::new(name, p.w, p.h); layout.paper = slot.paper; + tally.papers += usize::from(slot.paper_rough); slot.layout = Some(n); layouts.push(ProjectLayout { layout, frames: Vec::new(), pictures: Vec::new() }); } @@ -385,15 +393,22 @@ fn read_layout(node: Node, dir: &str, title: &Title, room: usize, tally: &mut Ta } /// The paper a fill symbol under `node` gives (its first layer switched on): `None` with no -/// symbol, `Some(None)` for white (or a colour that doesn't read, or no layer switched on). -fn paper_of(node: Node) -> Option> { +/// symbol; else its colour, none for white (or a colour that doesn't read, a fill switched off +/// or no layer switched on), and whether the fill is more than that colour (several layers, a +/// pattern, an outline, another kind), drawn as that colour alone. +fn paper_of(node: Node) -> Option<(Option, bool)> { let s = node.children().find(|c| c.has_tag_name("symbol"))?; - Some( - s.children() - .find(|d| d.has_tag_name("layer") && d.attribute("enabled") != Some("0")) - .and_then(|l| super::prop(&super::props(l), "color").and_then(color)) - .filter(|c| *c != Rgba::rgb(255, 255, 255)), - ) + let mut on = s.children().filter(|d| d.has_tag_name("layer") && d.attribute("enabled") != Some("0")); + let Some(layer) = on.next() else { return Some((None, false)) }; + let props = super::props(layer); + let style = super::prop(&props, "style").map(str::trim); + let rough = on.next().is_some() + || !matches!(layer.attribute("class"), Some("SimpleFill") | None) + || style.is_some_and(|v| !matches!(v, "solid" | "no")) + || super::prop(&props, "outline_style").is_some_and(|v| v.trim() != "no"); + let paper = + (style != Some("no")).then(|| super::prop(&props, "color").and_then(color)).flatten().filter(|c| *c != Rgba::rgb(255, 255, 255)); + Some((paper, rough)) } /// A layout's pages, with where each starts in order (for finding an item's page by halving) @@ -449,6 +464,8 @@ struct Slot { top: Option, page: Option, paper: Option, + /// Its fill more than a colour, drawn as one. + paper_rough: bool, layout: Option, } @@ -1351,6 +1368,7 @@ impl Tally { self.bar_symbols, "scale bars drawn with symbols of several layers, patterned, dashed, outlined or of another kind, in a plain colour", ), + (self.papers, "pages whose fill has several layers, a pattern, an outline or is of another kind, drawn as a plain colour"), (self.bar_text_styles, "scale bars' text bold, italic, underlined, buffered or shadowed, drawn plain"), (self.numeric_formats, "numeric scale bars, printing the scale in RustGIS's format (1:25,000)"), (self.numeric_sizes, "numeric scale bars' text sizes outside 1 to 400 pt, drawn at the nearest"), diff --git a/crates/map/src/qgis/layout/surround.rs b/crates/map/src/qgis/layout/surround.rs index fa77f031bd..f611af74fd 100644 --- a/crates/map/src/qgis/layout/surround.rs +++ b/crates/map/src/qgis/layout/surround.rs @@ -356,12 +356,25 @@ pub(super) fn scale_bar_item( // Its labels over the middle of their division (1), its bar in the middle or right of its box, // its height and its lines' width other than RustGIS's (3 mm, 0.3 mm): drawn as RustGIS draws // a bar. - let width = symbol_number(item, "lineSymbol", "line_width").or_else(|| num(item, "outlineWidth")); + // A width in millimetres, points, pixels (at 96 dpi) or inches; in map units it can't be + // compared, and is said. + let width = match symbol_number(item, "lineSymbol", "line_width") { + Some(w) => match symbol_prop(item, "lineSymbol", "line_width_unit").unwrap_or_default().to_ascii_lowercase().as_str() { + // As QGIS reads a unit: any case, none or empty millimetres. + "mm" | "" => Some(w), + "point" => Some(w * 25.4 / 72.0), + "pixel" => Some(w * 25.4 / 96.0), + "inch" => Some(w * 25.4), + _ => Some(f64::NAN), + }, + // QGIS's older bars: their outline width, in millimetres. + None => num(item, "outlineWidth"), + }; counts.bar_layout += usize::from( num(item, "labelHorizontalPlacement").is_some_and(|p| p != 0.0) || num(item, "alignment").is_some_and(|a| a != 0.0) || num(item, "height").is_some_and(|h| (h - 3.0).abs() > 1e-9) - || width.is_some_and(|w| (w - 0.3).abs() > 1e-9), + || width.is_some_and(|w| w.is_nan() || (w - 0.3).abs() > 1e-9), ); let mut kind = ElementKind::scale_bar(0); if let ElementKind::ScaleBar { @@ -423,11 +436,16 @@ fn text_style(item: Node, counts: &mut Counts) -> (f64, Rgba, Option) { (size, c, font) } -/// A number of a symbol held under `tag` (its first layer's property `key`). -fn symbol_number(item: Node, tag: &str, key: &str) -> Option { +/// A property of a symbol held under `tag` (its first layer switched on's `key`). +fn symbol_prop(item: Node, tag: &str, key: &str) -> Option { let symbol = child(item, tag)?.descendants().find(|d| d.has_tag_name("symbol"))?; let layer = first_enabled(symbol)?; - super::super::prop(&super::super::props(layer), key)?.trim().parse::().ok().filter(|v| v.is_finite()) + super::super::prop(&super::super::props(layer), key).map(|v| v.trim().to_string()) +} + +/// A number of a symbol held under `tag` (its first layer switched on's property `key`). +fn symbol_number(item: Node, tag: &str, key: &str) -> Option { + symbol_prop(item, tag, key)?.parse::().ok().filter(|v| v.is_finite()) } /// A symbol's first layer switched on (`enabled` other than 0), as the symbol reader takes them. diff --git a/crates/map/src/qgis/layout_surround_tests.rs b/crates/map/src/qgis/layout_surround_tests.rs index 743c7450b8..2d58af6126 100644 --- a/crates/map/src/qgis/layout_surround_tests.rs +++ b/crates/map/src/qgis/layout_surround_tests.rs @@ -567,3 +567,30 @@ fn scale_bars_symbols_beyond_a_plain_colour_are_said() { read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", r#"style="Line Ticks Up" segmentSizeMode="1""#, tick))), &mut report); assert!(said(&report, "in a plain colour (1)"), "{:?}", report.notes); } + +/// A bar's line width is compared in millimetres whatever its unit: 0.3 pt is not RustGIS's +/// 0.3 mm, said; 0.3 mm isn't; one in map units is said. +#[test] +fn a_bar_line_width_is_read_in_its_unit() { + let line = |w: &str, unit: &str| { + format!( + r#""# + ) + }; + let said_width = |children: &str| { + let mut report = Report::default(); + read( + &layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", r#"style="Line Ticks Up" segmentSizeMode="1""#, children))), + &mut report, + ); + said(&report, "scale bars' heights, line widths,") + }; + assert!(said_width(&line("0.3", "Point"))); + assert!(!said_width(&line("0.3", "MM"))); + assert!(said_width(&line("0.3", "MapUnit"))); + // Pixels at 96 dpi and inches converted; a unit in any case, or none, as QGIS reads it. + assert!(!said_width(&line(&(0.3 * 96.0 / 25.4).to_string(), "Pixel"))); + assert!(!said_width(&line(&(0.3 / 25.4).to_string(), "Inch"))); + assert!(!said_width(&line("0.3", "mm"))); + assert!(!said_width(&line("0.3", ""))); +} diff --git a/crates/map/src/qgis/layout_tests.rs b/crates/map/src/qgis/layout_tests.rs index 97a23a39f4..2c512262a7 100644 --- a/crates/map/src/qgis/layout_tests.rs +++ b/crates/map/src/qgis/layout_tests.rs @@ -1024,3 +1024,34 @@ fn a_pages_switched_off_fill_layer_gives_no_paper() { let p = read(&qgs(&layer("0", "0,0,255,255")), &mut Report::default()); assert_eq!(p.layouts[0].layout.paper, None); } + +/// A page's fill switched off gives no paper; one of several layers or a pattern is said as drawn +/// in a plain colour; a plain one isn't. +#[test] +fn a_pages_fill_beyond_a_colour_is_said() { + let layer = |c: &str, style: &str| { + format!( + r#""# + ) + }; + let page = |layers: &str| { + let qgs = format!( + r#"{layers}"# + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + ( + p.layouts[0].layout.paper, + said(&report, "pages whose fill has several layers, a pattern, an outline or is of another kind, drawn as a plain colour (1)"), + ) + }; + assert_eq!(page(&layer("0,0,255,255", "no")), (None, false)); + assert_eq!(page(&layer("0,0,255,255", "solid")), (Some(Rgba::rgb(0, 0, 255)), false)); + assert_eq!(page(&layer("0,0,255,255", "dense3")), (Some(Rgba::rgb(0, 0, 255)), true)); + assert_eq!(page(&(layer("0,0,255,255", "solid") + &layer("255,0,0,255", "solid"))), (Some(Rgba::rgb(0, 0, 255)), true)); + let outlined = layer("0,0,255,255", "solid") + .replace("", r#""#); + assert_eq!(page(&outlined), (Some(Rgba::rgb(0, 0, 255)), true)); + let gradient = layer("0,0,255,255", "solid").replace(r#"class="SimpleFill""#, r#"class="GradientFill""#); + assert_eq!(page(&gradient), (Some(Rgba::rgb(0, 0, 255)), true)); +} From 4e2c499b2b4307377165a92a450c05297f1a52f1 Mon Sep 17 00:00:00 2001 From: strebdom Date: Tue, 1 Dec 2026 22:13:23 +0100 Subject: [PATCH 8/8] fix(map): a QGIS layout scale bar's spacing of its own is said The room between a bar's labels and its bar (labelBarSpace) and inside its box (boxContentSpace), which RustGIS doesn't read, is said when it differs from QGIS's 3 mm and 1 mm. --- crates/map/src/qgis/layout.rs | 2 +- crates/map/src/qgis/layout/surround.rs | 7 +++++-- crates/map/src/qgis/layout_surround_tests.rs | 18 ++++++++++++++++-- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index c451bc2094..baac281a11 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -1390,7 +1390,7 @@ impl Tally { (self.bar_values, "scale bars' division values, chosen anew to fit their box"), ( self.bar_layout, - "scale bars' heights, line widths, alignment in their box or labels over their divisions' middles, as RustGIS draws them", + "scale bars' heights, line widths, spacing, alignment in their box or labels over their divisions' middles, as RustGIS draws them", ), (self.bar_text_sizes, "scale bars' text sizes outside 4 to 100 pt, drawn at the nearest"), (self.map_backgrounds, "map items' background colours, drawn as the map's own"), diff --git a/crates/map/src/qgis/layout/surround.rs b/crates/map/src/qgis/layout/surround.rs index f611af74fd..733f4a2940 100644 --- a/crates/map/src/qgis/layout/surround.rs +++ b/crates/map/src/qgis/layout/surround.rs @@ -354,8 +354,8 @@ pub(super) fn scale_bar_item( // most widths (1); RustGIS picks its own to fill the bar's box, said for every bar. counts.bar_values += 1; // Its labels over the middle of their division (1), its bar in the middle or right of its box, - // its height and its lines' width other than RustGIS's (3 mm, 0.3 mm): drawn as RustGIS draws - // a bar. + // its height, its lines' width and its spacing other than RustGIS's (3 mm, 0.3 mm): drawn as + // RustGIS draws a bar. // A width in millimetres, points, pixels (at 96 dpi) or inches; in map units it can't be // compared, and is said. let width = match symbol_number(item, "lineSymbol", "line_width") { @@ -374,6 +374,9 @@ pub(super) fn scale_bar_item( num(item, "labelHorizontalPlacement").is_some_and(|p| p != 0.0) || num(item, "alignment").is_some_and(|a| a != 0.0) || num(item, "height").is_some_and(|h| (h - 3.0).abs() > 1e-9) + // The room between its labels and its bar (3 mm) and inside its box (1 mm). + || num(item, "labelBarSpace").is_some_and(|v| (v - 3.0).abs() > 1e-9) + || num(item, "boxContentSpace").is_some_and(|v| (v - 1.0).abs() > 1e-9) || width.is_some_and(|w| w.is_nan() || (w - 0.3).abs() > 1e-9), ); let mut kind = ElementKind::scale_bar(0); diff --git a/crates/map/src/qgis/layout_surround_tests.rs b/crates/map/src/qgis/layout_surround_tests.rs index 2d58af6126..11597fcfe1 100644 --- a/crates/map/src/qgis/layout_surround_tests.rs +++ b/crates/map/src/qgis/layout_surround_tests.rs @@ -254,7 +254,7 @@ fn a_scale_bar_in_other_units_prints_rustgis_abbreviation() { let mut report = Report::default(); read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &styled)), &mut report); assert!(said(&report, "scale bars' text bold, italic, underlined, buffered or shadowed, drawn plain (1)"), "{:?}", report.notes); - assert!(said(&report, "scale bars' heights, line widths,"), "{:?}", report.notes); + assert!(said(&report, "scale bars' heights, line widths, spacing,"), "{:?}", report.notes); } /// A map overview is an extent indicator of its map's frame, in its outline's colour and width; @@ -583,7 +583,7 @@ fn a_bar_line_width_is_read_in_its_unit() { &layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", r#"style="Line Ticks Up" segmentSizeMode="1""#, children))), &mut report, ); - said(&report, "scale bars' heights, line widths,") + said(&report, "scale bars' heights, line widths, spacing,") }; assert!(said_width(&line("0.3", "Point"))); assert!(!said_width(&line("0.3", "MM"))); @@ -594,3 +594,17 @@ fn a_bar_line_width_is_read_in_its_unit() { assert!(!said_width(&line("0.3", "mm"))); assert!(!said_width(&line("0.3", ""))); } + +/// A bar's spacing (between its labels and its bar, inside its box) other than QGIS's default is +/// said; the default isn't. +#[test] +fn a_bars_spacing_of_its_own_is_said() { + let spaced = |attrs: &str| { + let mut report = Report::default(); + read(&layout(PAGE, &(map("{m}", 10.0, 0, "") + &bar("{m}", attrs, BAR_COLOURS))), &mut report); + said(&report, "scale bars' heights, line widths, spacing,") + }; + assert!(!spaced(r#"style="Single Box" segmentSizeMode="1" labelBarSpace="3" boxContentSpace="1""#)); + assert!(spaced(r#"style="Single Box" segmentSizeMode="1" labelBarSpace="6""#)); + assert!(spaced(r#"style="Single Box" segmentSizeMode="1" boxContentSpace="2.5""#)); +}