From f69b07a48471bb55f38dc866e7e9465df65979a4 Mon Sep 17 00:00:00 2001 From: strebdom Date: Wed, 2 Dec 2026 11:59:18 +0100 Subject: [PATCH 1/4] feat(map): QGIS layouts' map grids as their frames' grids (piece 12b of #882) --- crates/engine/src/tests/qgis_layouts.rs | 30 + crates/map/src/qgis/layout.rs | 32 +- crates/map/src/qgis/layout/grid.rs | 456 ++++ crates/map/src/qgis/layout/surround.rs | 8 +- crates/map/src/qgis/layout_grid_tests.rs | 535 +++++ crates/map/src/qgis/mod.rs | 9 +- crates/map/src/qgis/tests.rs | 2 +- crates/map/testdata/qgis/README.md | 4 +- .../map/testdata/qgis/generated/generate.py | 72 + .../qgis/generated/qgs/layout-grids.qgs | 2009 +++++++++++++++++ docs/user-guide/workspace.md | 15 +- 11 files changed, 3144 insertions(+), 28 deletions(-) create mode 100644 crates/map/src/qgis/layout/grid.rs create mode 100644 crates/map/src/qgis/layout_grid_tests.rs create mode 100644 crates/map/testdata/qgis/generated/qgs/layout-grids.qgs diff --git a/crates/engine/src/tests/qgis_layouts.rs b/crates/engine/src/tests/qgis_layouts.rs index 814c69e294..19934c4fbd 100644 --- a/crates/engine/src/tests/qgis_layouts.rs +++ b/crates/engine/src/tests/qgis_layouts.rs @@ -286,3 +286,33 @@ fn a_layouts_legends_name_the_imported_layers() { exported.unwrap(); assert!(written > 0); } + +/// The corpus's grids come in on their frames as read (a measured grid in the project's system, +/// a graticule), and the layout exports. +#[test] +fn a_layouts_grids_come_in_on_their_frames() { + use rustgis_map::layout::GridKind; + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../map/testdata/qgis/generated/qgs/layout-grids.qgs"); + let mut s = Session::new(Project::default()); + s.run("project.importQgis", &json!({"path": path.display().to_string()})).unwrap(); + let l = s.project.layouts.iter().find(|l| l.name == "Grids").unwrap(); + let mut grids: Vec<(f64, GridKind, f64, Option)> = l + .elements + .iter() + .filter_map(|e| match &e.kind { + ElementKind::MapFrame { grid: Some(g), .. } => Some((e.x, g.kind, g.step, g.crs.clone())), + _ => None, + }) + .collect(); + grids.sort_by(|a, b| a.0.total_cmp(&b.0)); + let kinds: Vec<_> = grids.into_iter().map(|(_, k, step, crs)| (k, step, crs)).collect(); + assert_eq!(kinds, [(GridKind::Measured, 500.0, Some("EPSG:2056".to_string())), (GridKind::Graticule, 0.005, None)]); + let dir = std::env::temp_dir().join(format!("rustgis-qgis-grids-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let png = dir.join("grids.png"); + let exported = s.run("layout.export", &json!({"layout": "Grids", "path": png.display().to_string(), "dpi": 36})); + let written = std::fs::metadata(&png).map(|m| m.len()).unwrap_or(0); + let _ = std::fs::remove_dir_all(&dir); + exported.unwrap(); + assert!(written > 0); +} diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index 36a5e56216..dabcc7327c 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -4,12 +4,11 @@ //! 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. Its scale bars, -//! north arrows, map overviews ([`surround`]) and legends ([`legend`]) show their map's frame -//! (piece 12b). +//! north arrows, map overviews ([`surround`]) and legends ([`legend`]) show their map's frame, and +//! a map item's first grid becomes its frame's ([`grid`]) (piece 12b). //! //! What a RustGIS layout has no place for is noted, counted over all the layouts: 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. +//! and the other item kinds, the atlas, groups, blending, and settings set by expressions. A QGIS 2 composer isn't read. use roxmltree::Node; @@ -82,7 +81,9 @@ pub(super) struct Tally { other_kinds: Vec, groups: usize, map_backgrounds: usize, - grids: usize, + grid: grid::Counts, + /// The project's coordinate system, which a map item without one of its own shows. + project_crs: Option, atlases: usize, locked_layers: usize, turned_items: usize, @@ -231,6 +232,7 @@ pub(super) struct Tally { bar_text_sizes: usize, } +mod grid; mod legend; mod surround; @@ -246,7 +248,7 @@ fn as_written(text: &str) -> String { pub fn read_layouts( root: Node, dir: &str, - (title, layers, annotations): (&str, &[super::ProjectLayer], Option<&super::ProjectLayer>), + (title, crs, layers, annotations): (&str, Option<&str>, &[super::ProjectLayer], Option<&super::ProjectLayer>), report: &mut Report, ) -> Vec { let composers = root.children().filter(|c| c.has_tag_name("Composer")).count(); @@ -260,6 +262,7 @@ pub fn read_layouts( let title = Title { text: as_written(&title.chars().take(MAX_TEXT).collect::()), cut, braced: title.contains(['{', '}']) }; tally.title_len = title.text.len(); tally.layers = legend::project_layers(layers, annotations); + tally.project_crs = child(root, "projectCrs").and_then(grid::readable_crs).or_else(|| crs.map(str::to_string)); let mut out = Vec::new(); let mut names = Vec::new(); let all: Vec = list.children().filter(|c| c.has_tag_name("Layout")).collect(); @@ -790,14 +793,11 @@ 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 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; - } - } + // Its grid, in the system it shows its extent in (its own, else the project's), a page + // millimetre being its extent's width over its own. + let map_crs = child(item, "crs").and_then(grid::readable_crs).or_else(|| tally.project_crs.clone()); + let per_mm = (place.w > 0.0).then(|| (extent[2] - extent[0]) / place.w).filter(|v| v.is_finite() && *v > 0.0); + let grid = grid::map_grid(item, map_crs.as_deref(), extent, per_mm, tally); if item.attribute("keepLayerSet") == Some("true") || item.attribute("followPreset") == Some("true") { tally.locked_layers += 1; } @@ -814,7 +814,7 @@ fn map_item(item: Node, place: &Placed, id: Option, target: &mut Project center: rustgis_geom::Coord::new(0.0, 0.0), scale: 1.0, shape: Default::default(), - grid: None, + grid, sections: Vec::new(), extent_of: None, extent_color: INDICATOR_COLOR, @@ -1370,7 +1370,6 @@ impl Tally { (self.tables, "attribute tables"), (self.html, "HTML frames"), (self.markers, "marker items"), - (self.grids, "map grids"), (self.atlases, "atlases"), (self.svg, "SVG pictures (RustGIS's pictures are PNG or JPEG)"), (self.no_picture, "pictures that name no file"), @@ -1534,6 +1533,7 @@ impl Tally { } // What their symbols and sizes noted, as theirs. report.merge_as("print layouts", &self.notes); + self.grid.say(report); if self.unread_texts > 0 { report.skipped("", format!("its print layouts' labels' {} ({})", self.unread_text.join(", "), self.unread_texts)); } diff --git a/crates/map/src/qgis/layout/grid.rs b/crates/map/src/qgis/layout/grid.rs new file mode 100644 index 0000000000..48b9c6b221 --- /dev/null +++ b/crates/map/src/qgis/layout/grid.rs @@ -0,0 +1,456 @@ +//! A QGIS map item's grids (the last part of piece 12b of #882): the first one shown becomes its +//! frame's grid, a graticule when its coordinate system is in degrees, else a measured grid in +//! it. What RustGIS's grid draws differently, and the grids past the first, are said. + +use super::surround::{HAIRLINE_PT, symbol_color, symbol_not_plain, symbol_number, symbol_prop}; +use super::*; +use crate::layout::{ + CoordFormat, GRID_LABEL_PT, Grid, GridEdges, GridKind, GridStyle, LAYOUT_TEXT_SIZE, MAX_GRATICULE_STEP, MAX_GRID_CRS, MAX_GRID_WIDTH, + MAX_MEASURED_STEP, MAX_TICK_MM, MIN_MEASURED_STEP, Orientation, PT_PER_MM, +}; + +/// What a map item's grids count in the layouts' notes, one count a grid. +#[derive(Default)] +pub(super) struct Counts { + past: usize, + marks: usize, + frames: usize, + ticks_out: usize, + tick_sides: usize, + frame_pens: usize, + outside: usize, + directions: usize, + formats: usize, + decimals: usize, + fonts: usize, + sizes: usize, + steps: usize, + offsets: usize, + fitted: usize, + symbols: usize, + clamped: usize, + blended: usize, + turned: usize, + datum: usize, + unread_crs: usize, + fine: usize, + odd: usize, + /// What reading its labels' size noted. + notes: Report, +} + +impl Counts { + pub(super) fn say(&self, report: &mut Report) { + let skipped = [ + (self.past, "map grids past the first one shown on a map item, which a frame draws"), + (self.frames, "map grids' zebra, line border and nautical frames"), + ]; + for (n, what) in skipped { + if n > 0 { + report.skipped("", format!("its print layouts' {what} ({n})")); + } + } + let approximated = [ + (self.marks, "map grids of crosses or markers, drawn as lines"), + (self.ticks_out, "map grids' ticks outside their map or across its edge, drawn inside it"), + (self.tick_sides, "map grids' ticks on some sides only, or showing some coordinates only, drawn on all four for all"), + (self.frame_pens, "map grids' ticks in a colour or width of their own, drawn as their lines"), + (self.outside, "map grids' annotations outside their map, drawn just inside its edge"), + ( + self.directions, + "map grids' annotations upright along the top or bottom, over, on or under their ticks, descending, or turned differently left and right, as RustGIS turns them", + ), + ( + self.formats, + "map grids' annotations by an expression, in plain decimals or in degrees and minutes (and seconds), which QGIS writes otherwise, or in degrees on a measured grid, in RustGIS's nearest format", + ), + (self.decimals, "map grids' annotations' decimals, as many as the step needs"), + (self.fonts, "map grids' annotations in a font, colour or style of their own, in RustGIS's grid labels' font and colour"), + (self.sizes, "map grids' annotation sizes outside 4 to 100 pt, drawn at the nearest"), + (self.steps, "map grids with different steps across and up, drawn at the step across"), + (self.offsets, "map grids' offsets, their lines drawn from zero"), + ( + self.fitted, + "map grids fitted to the page, or spaced on it in a coordinate system other than their map's, given a step of RustGIS's to fit", + ), + (self.symbols, "map grids' lines dashed, of several layers or of another kind, drawn plain"), + ( + self.clamped, + "map grids' steps, line widths or tick lengths brought within RustGIS's (1 m to 10,000 km or up to 90°, 10 pt, 20 mm)", + ), + (self.blended, "map grids' blending modes, drawn normally"), + (self.turned, "map grids' annotations or ticks set to turn with a turned map, drawn as RustGIS draws them"), + (self.datum, "map grids of latitudes and longitudes in a system other than WGS 84, drawn as WGS 84's"), + (self.unread_crs, "map grids in a coordinate system that doesn't read, drawn in their map's or by their extent"), + ( + self.fine, + "map grids finer than RustGIS draws (more than 100 lines across a measured grid, 200 latitudes or longitudes, or less than 0.001° apart), drawn wider or cut there", + ), + (self.odd, "map grids' settings that don't read, drawn as RustGIS's"), + ]; + for (n, what) in approximated { + if n > 0 { + report.approximated("", format!("its print layouts' {what} ({n})")); + } + } + report.merge_as("print layouts", &self.notes); + } +} + +/// The map item's frame's grid: its first grid shown (`show` other than 0). Those switched off, +/// and those past the first, are counted. `map_crs` is the system the map item shows its extent +/// in (its own, else the project's), `per_mm` its map units a millimetre across the page. +pub(super) fn map_grid(item: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option, tally: &mut Tally) -> Option { + let mut grid = None; + 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 if int(g, "unit") != Some(3) && num(g, "intervalX").is_none_or(|i| i <= 0.0) { + // A step of none (a new grid's) draws nothing in QGIS: nothing to carry over. + continue; + } else if grid.is_some() { + tally.grid.past += 1; + } else { + grid = Some(read_grid(g, map_crs, extent, per_mm, &mut tally.grid)); + } + } + grid +} + +/// An attribute as a whole number (QGIS's enums and flags). +fn int(n: Node, k: &str) -> Option { + num(n, k).filter(|v| v.fract() == 0.0 && v.abs() < 1e9).map(|v| v as i64) +} + +fn read_grid(g: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option, counts: &mut Counts) -> Grid { + use rustgis_data::raster::Crs; + // Its coordinate system: its own, else its map's (each read by its code, else its PROJ + // string, as a custom system's code doesn't read). One that doesn't read, or longer than a + // grid keeps, is said, its map's taken (or its extent's, below). + let parse = |c: &str| (c.chars().count() <= MAX_GRID_CRS).then(|| Crs::parse(c).ok()).flatten(); + let own = g.children().find(|c| c.has_tag_name("spatialrefsys")).and_then(readable_crs); + let own_read = own.as_deref().and_then(parse); + let map_read = map_crs.and_then(parse); + counts.unread_crs += + usize::from((own.is_some() && own_read.is_none()) || (own_read.is_none() && map_crs.is_some() && map_read.is_none())); + let (code, crs) = match own_read { + Some(c) => (own.clone(), Some(c)), + None => (map_crs.map(str::to_string), map_read), + }; + // Its map's own when it names none, or the same: a step on the page converts to its units. + let same_system = own_read.is_none() || own.as_deref() == map_crs; + // A system that doesn't read (or none at all) is taken from the extent: degrees when it fits + // the Earth's. + let in_degrees = match crs { + Some(c) => c.is_geographic(), + None => extent[0] >= -180.0 && extent[2] <= 180.0 && extent[1] >= -90.0 && extent[3] <= 90.0, + }; + let kind = if in_degrees { GridKind::Graticule } else { GridKind::Measured }; + // (A custom system's code is 0: its PROJ string names its datum, WGS 84's itself rather than + // shifted to it.) + let wgs84 = |c: Crs| { + let def = code.as_deref().unwrap_or_default().to_ascii_lowercase(); + c.epsg() == 4326 || (c.epsg() == 0 && !def.contains("+towgs84") && (def.contains("+datum=wgs84") || def.contains("+ellps=wgs84"))) + }; + counts.datum += usize::from(crs.is_some_and(|c| c.is_geographic() && !wgs84(c))); + // A measured grid names its system, so it draws in it whatever the map's is; a graticule is + // WGS 84's latitudes and longitudes. + let grid_crs = code.filter(|_| kind == GridKind::Measured && crs.is_some()); + + // Its step: in its system's units (0), or in millimetres (1) or centimetres (2) on the page, + // converted when its system is its map's; fitted to the page (3), RustGIS's own. + let (ix, iy) = (num(g, "intervalX").unwrap_or(0.0), num(g, "intervalY").unwrap_or(0.0)); + let unit = int(g, "unit").unwrap_or(0); + let page_mm = match unit { + 1 => Some(1.0), + 2 => Some(10.0), + _ => None, + }; + // (A grid of no step in map units or on the page draws nothing, and isn't read.) + let step = match (unit, page_mm, per_mm) { + (0, ..) if ix > 0.0 => ix, + (_, Some(mm), Some(per_mm)) if ix > 0.0 && same_system => ix * mm * per_mm, + _ => { + counts.fitted += 1; + 0.0 + } + }; + // A step up other than across, or none (drawn at the step across). + counts.steps += usize::from(unit != 3 && (iy <= 0.0 || (ix - iy).abs() > 1e-9 * ix.abs().max(iy.abs()))); + counts.offsets += usize::from(num(g, "offsetX").is_some_and(|v| v != 0.0) || num(g, "offsetY").is_some_and(|v| v != 0.0)); + let kept = match kind { + GridKind::Graticule => step.min(MAX_GRATICULE_STEP), + GridKind::Measured if step > 0.0 => step.clamp(MIN_MEASURED_STEP, MAX_MEASURED_STEP), + GridKind::Measured => 0.0, + }; + let mut clamped = kept != step; + let step = kept; + // Finer than RustGIS draws, over its map's extent in its own system: a measured grid widened + // past 100 lines across, a graticule drawn from 0.001° apart and cut at 200 longitudes, 400 + // lines in all. + let span = match kind { + GridKind::Measured => extent_in(extent, map_read, crs), + GridKind::Graticule => extent_in(extent, map_read, None), + }; + counts.fine += usize::from( + step > 0.0 + && match kind { + GridKind::Measured => span.is_some_and(|e| (e[2] - e[0]).max(e[3] - e[1]) / step > 100.0), + GridKind::Graticule => { + let lines = |a: f64, b: f64| (b / step.max(0.001)).floor() - (a / step.max(0.001)).floor() + 1.0; + step < 0.001 || span.is_some_and(|e| lines(e[0], e[2]) > 200.0 || lines(e[0], e[2]) + lines(e[1], e[3]) > 400.0) + } + }, + ); + + // Its frame: ticks inside (2), outside (3) or across (4) the map's edge, which RustGIS draws + // inside; a zebra, a line border or nautical (1, 5 to 7), left out. + let frame = int(g, "gridFrameStyle").unwrap_or(0); + let ticks = matches!(frame, 2..=4); + // (A margin moves its frame off the map's edge.) + counts.ticks_out += usize::from(matches!(frame, 3 | 4) || (ticks && num(g, "gridFrameMargin").is_some_and(|m| m != 0.0))); + counts.frames += usize::from(matches!(frame, 1 | 5..=7)); + // Ticks on some sides only, or a side's showing latitudes or longitudes only (its divisions). + let divisions = ["left", "right", "top", "bottom"].iter().any(|s| int(g, &format!("{s}FrameDivisions")).is_some_and(|d| d != 0)); + counts.tick_sides += usize::from(ticks && (divisions || int(g, "gridFrameSideFlags").is_some_and(|f| f & 15 != 15))); + // Lines (0), crosses (1), markers (2), or its frame and annotations only (3). + let shape = int(g, "gridStyle").unwrap_or(0); + counts.marks += usize::from(matches!(shape, 1 | 2)); + let mut odd = !(0..=3).contains(&shape) || !(0..=7).contains(&frame); + let style = match (shape, ticks) { + (3, _) => GridStyle::Ticks, + (_, true) => GridStyle::LinesAndTicks, + (_, false) => GridStyle::Lines, + }; + let tick_length = if ticks { + let w = num(g, "gridFrameWidth").unwrap_or(2.0); + clamped |= !(0.0..=MAX_TICK_MM).contains(&w); + w.clamp(0.0, MAX_TICK_MM) + } else if style == GridStyle::Ticks { + // Its annotations alone: no ticks. + 0.0 + } else { + crate::layout::Grid::default().tick_length + }; + + // Its lines' colour and width, in layout points; a width in map units can't be compared, and + // is said with the line's other differences. + let line_color = symbol_color(g, "lineStyle").unwrap_or(Rgba::rgb(0, 0, 0)); + let line_mm = match symbol_number(g, "lineStyle", "line_width") { + Some(w) => match symbol_prop(g, "lineStyle", "line_width_unit").unwrap_or_default().to_ascii_lowercase().as_str() { + "mm" | "" => Some(w), + "point" => Some(w * 25.4 / 72.0), + "pixel" => Some(w * 25.4 / 96.0), + "inch" => Some(w * 25.4), + _ => None, + }, + None => Some(0.3), + }; + // (Its frame and annotations alone draw no lines.) + counts.symbols += usize::from(style != GridStyle::Ticks && (line_mm.is_none() || symbol_not_plain(g, "lineStyle"))); + let line_mm = line_mm.unwrap_or(0.3); + // Its frame's pen, which draws its ticks: the grid's ticks alone take it, ticks with lines + // the lines', a pen of its own said. + let pen_color = g.attribute("gridFramePenColor").and_then(color).unwrap_or(Rgba::rgb(0, 0, 0)); + let pen_mm = num(g, "gridFramePenThickness").unwrap_or(0.3); + clamped |= pen_mm < 0.0 || line_mm < 0.0; + let (pen_mm, line_mm) = (pen_mm.max(0.0), line_mm.max(0.0)); + let (color, mm) = if style == GridStyle::Ticks { (pen_color, pen_mm) } else { (line_color, line_mm) }; + counts.frame_pens += usize::from(style == GridStyle::LinesAndTicks && (pen_color != line_color || (pen_mm - line_mm).abs() > 1e-9)); + // A hairline (width 0) is drawn a pixel wide, as QGIS draws one. + let width = if mm > 0.0 { mm * PT_PER_MM } else { HAIRLINE_PT }; + clamped |= width > MAX_GRID_WIDTH; + let width = width.min(MAX_GRID_WIDTH); + counts.clamped += usize::from(clamped); + for s in ["left", "right", "top", "bottom"].into_iter().filter(|_| g.attribute("showAnnotation") == Some("1")) { + let at = |k: &str| int(g, &format!("{s}Annotation{k}")); + odd |= at("Display").is_some_and(|d| !(0..=3).contains(&d)) + || at("Position").is_some_and(|d| !(0..=1).contains(&d)) + || at("Direction").is_some_and(|d| !(0..=6).contains(&d)); + } + counts.odd += usize::from(odd); + + counts.blended += usize::from(int(g, "blendMode").is_some_and(|b| b != 0)); + counts.turned += usize::from(g.attribute("rotatedAnnotationsEnabled") == Some("1") || g.attribute("rotatedTicksEnabled") == Some("1")); + + let mut grid = Grid { + step, + color, + labels: g.attribute("showAnnotation") == Some("1"), + style, + tick_length, + width, + kind, + crs: grid_crs, + ..Grid::default() + }; + if grid.labels { + annotations(g, &mut grid, counts); + } + grid +} + +/// A grid's annotations: the sides showing them, their direction, format and size. +fn annotations(g: Node, grid: &mut Grid, counts: &mut Counts) { + // Each side's display: all (0), latitudes only (1), longitudes only (2) or none (3). RustGIS + // labels longitudes (eastings) along the top and bottom, latitudes (northings) left and right, + // as QGIS shows them on a map facing north. + let side = |s: &str, k: &str| int(g, &format!("{s}Annotation{k}")); + let display = |s: &str| side(s, "Display").unwrap_or(0); + let across = |s: &str| matches!(display(s), 0 | 2); + let along = |s: &str| matches!(display(s), 0 | 1); + grid.edges = GridEdges { top: across("top"), bottom: across("bottom"), left: along("left"), right: along("right") }; + let shown: Vec<&str> = [("left", grid.edges.left), ("right", grid.edges.right), ("bottom", grid.edges.bottom), ("top", grid.edges.top)] + .into_iter() + .filter_map(|(s, on)| on.then_some(s)) + .collect(); + // Inside the map (0) or outside it (1, QGIS's default): RustGIS draws them inside. + counts.outside += usize::from(shown.iter().any(|s| side(s, "Position").unwrap_or(1) == 1)); + // Their direction: across (0), up (1), down (2), along their side (3), or over, on or under + // their ticks (4 to 6). RustGIS writes the top and bottom's across, and the left and right's + // across or up, both alike. + let mut odd = false; + let mut sides = Vec::new(); + for s in &shown { + let d = side(s, "Direction").unwrap_or(0); + match *s { + // (One past QGIS's is said as a setting that doesn't read.) + "top" | "bottom" => odd |= matches!(d, 1 | 2 | 4..=6), + _ => { + odd |= matches!(d, 2 | 4..=6); + sides.push(matches!(d, 1..=3)); + } + } + } + odd |= sides.windows(2).any(|w| w.first() != w.get(1)); + counts.directions += usize::from(odd); + grid.label_orientation = if sides.first() == Some(&true) { Orientation::Vertical } else { Orientation::Horizontal }; + + // Their format: decimal (0), with a suffix (3); degrees and minutes (1, 4, 5) or with seconds + // (2, 6, 7), with a suffix, without (4, 6) or padded (5, 7); an expression (8). + let format = int(g, "annotationFormat").unwrap_or(0); + match grid.kind { + GridKind::Graticule => { + (grid.format, grid.hemisphere) = match format { + 0 => (CoordFormat::Decimal, false), + 3 => (CoordFormat::Decimal, true), + 4 | 6 => (CoordFormat::Dms, false), + 1..=7 => (CoordFormat::Dms, true), + _ => (CoordFormat::Decimal, false), + }; + // QGIS writes plain decimals without a degree sign, and minutes and seconds unpadded + // and always, which RustGIS pads and leaves out where the step doesn't need them: + // only decimals with a suffix are written alike. + counts.formats += usize::from(format != 3); + // Decimal degrees show as many decimals as the step needs, seconds none. + let precision = int(g, "annotationPrecision").unwrap_or(3); + counts.decimals += usize::from(match format { + 0 | 3 => grid.step > 0.0 && precision != decimals(grid.step), + 2 | 6 | 7 => precision != 0, + _ => false, + }); + } + GridKind::Measured => { + // A measured grid's labels show as many decimals as the step needs (a fitted step's + // none): QGIS's decimal format at that many. + counts.formats += usize::from(format != 0); + let needed = if grid.step > 0.0 { decimals(grid.step) } else { 0 }; + counts.decimals += usize::from(format == 0 && int(g, "annotationPrecision").unwrap_or(3) != needed); + } + } + + // Their text: its size, and a font, colour or style other than RustGIS's grid labels'. + let Some(s) = child(g, "text-style") else { + older_font(g, grid, counts); + return; + }; + let unit = s.attribute("fontSizeUnit").unwrap_or("Point"); + let size = labels::points(num(s, "fontSize").unwrap_or(10.0), unit, "map grid annotation sizes", "", &mut counts.notes); + let kept = size.clamp(*LAYOUT_TEXT_SIZE.start(), *LAYOUT_TEXT_SIZE.end()); + counts.sizes += usize::from(kept != size); + grid.label_size = if (kept - GRID_LABEL_PT).abs() < 1e-9 { GRID_LABEL_PT } else { kept }; + let (bold, italic) = labels::bold_italic(s); + let c = s.attribute("textColor").and_then(color).unwrap_or(Rgba::rgb(0, 0, 0)); + let dark = c.r() <= 0x40 && c.g() <= 0x40 && c.b() <= 0x40 && c.a() == 255 && num(s, "textOpacity").is_none_or(|o| o >= 1.0); + let font = s.attribute("fontFamily").map(str::trim).is_some_and(|f| !f.is_empty() && !annotation::generic(f)); + 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")); + counts.fonts += usize::from(!dark || font || styled); +} + +/// The decimals a graticule's decimal labels show on lines `step` degrees apart, as RustGIS +/// writes them: the fewest (0 to 3) that write a multiple of it exactly, else 4. +fn decimals(step: f64) -> i64 { + (0..4i64) + .find(|&n| { + let k = step * 10f64.powi(n as i32); + (k - k.round()).abs() < 1e-6 + }) + .unwrap_or(4) +} + +/// QGIS 3's older grids' annotation font (`annotationFont`, Qt's `family,points,pixels,hint, +/// weight,italic,underline,strikeout,…`) and colour (`annotationFontColor`), before their text style. +fn older_font(g: Node, grid: &mut Grid, counts: &mut Counts) { + let font = g.attribute("annotationFont").unwrap_or_default(); + let parts: Vec<&str> = font.split(',').map(str::trim).take(8).collect(); + let field = |i: usize| parts.get(i).and_then(|p| p.parse::().ok()).filter(|p| p.is_finite()); + let family = parts.first().copied().unwrap_or_default(); + if let Some(size) = field(1).filter(|p| *p > 0.0).or(field(2).filter(|p| *p > 0.0).map(|p| p * 0.75)) { + let kept = size.clamp(*LAYOUT_TEXT_SIZE.start(), *LAYOUT_TEXT_SIZE.end()); + counts.sizes += usize::from(kept != size); + grid.label_size = if (kept - GRID_LABEL_PT).abs() < 1e-9 { GRID_LABEL_PT } else { kept }; + } + // Its weight bold (Qt 5's 75, Qt 6's 700), italic, underlined or struck through. + let weight = field(4).unwrap_or(50.0); + let styled = (weight > 50.0 && weight < 100.0) || weight > 500.0 || [5, 6, 7].iter().any(|&i| field(i).is_some_and(|v| v != 0.0)); + let c = g.attribute("annotationFontColor").and_then(color).unwrap_or(Rgba::rgb(0, 0, 0)); + let dark = c.r() <= 0x40 && c.g() <= 0x40 && c.b() <= 0x40 && c.a() == 255; + counts.fonts += usize::from(!dark || styled || (!family.is_empty() && !annotation::generic(family))); +} + +/// A coordinate system element's (``, or one holding it) system as a grid reads +/// it: its code when that reads, else its PROJ string when that does (a custom system's code, +/// `USER:…`, doesn't), else its code as written, to be said as unread. +pub(super) fn readable_crs(node: Node) -> Option { + use rustgis_data::raster::Crs; + let srs = if node.has_tag_name("spatialrefsys") { Some(node) } else { node.descendants().find(|d| d.has_tag_name("spatialrefsys")) }?; + let text = |tag: &str| child(srs, tag).and_then(|n| n.text()).map(str::trim).filter(|t| !t.is_empty()); + let named: Vec<&str> = [text("authid").filter(|a| a.contains(':')), text("proj4")].into_iter().flatten().collect(); + named.iter().find(|c| c.chars().count() <= MAX_GRID_CRS && Crs::parse(c).is_ok()).or(named.first()).map(|c| c.to_string()) +} + +/// `extent` in `from`'s system as an extent in `to`'s (longitude/latitude when none), through +/// points along its edges; none when either doesn't convert. +fn extent_in(extent: [f64; 4], from: Option, to: Option) -> Option<[f64; 4]> { + let from = from?.transformer().ok()?; + let to = match to { + Some(c) => Some(c.transformer().ok()?), + None => None, + }; + let [x0, y0, x1, y1] = extent; + let mut out = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for i in 0..=8 { + let t = f64::from(i) / 8.0; + let (x, y) = (x0 + (x1 - x0) * t, y0 + (y1 - y0) * t); + for (px, py) in [(x, y0), (x, y1), (x0, y), (x1, y)] { + let Some(ll) = from.to_lonlat(rustgis_geom::Coord::new(px, py)) else { continue }; + let Some(c) = (match &to { + Some(tr) => tr.from_lonlat(ll), + None => Some(ll), + }) else { + continue; + }; + if c.x.is_finite() && c.y.is_finite() { + out = [out[0].min(c.x), out[1].min(c.y), out[2].max(c.x), out[3].max(c.y)]; + } + } + } + (out[0] <= out[2] && out[1] <= out[3]).then_some(out) +} diff --git a/crates/map/src/qgis/layout/surround.rs b/crates/map/src/qgis/layout/surround.rs index 3fe8f564df..d159fe6072 100644 --- a/crates/map/src/qgis/layout/surround.rs +++ b/crates/map/src/qgis/layout/surround.rs @@ -492,14 +492,14 @@ fn text_style(item: Node, counts: &mut Counts) -> (f64, Rgba, 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 { +pub(super) 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).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 { +pub(super) fn symbol_number(item: Node, tag: &str, key: &str) -> Option { symbol_prop(item, tag, key)?.parse::().ok().filter(|v| v.is_finite()) } @@ -511,7 +511,7 @@ fn first_enabled<'a, 'i>(symbol: Node<'a, 'i>) -> Option> { /// 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 { +pub(super) 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 }; @@ -528,7 +528,7 @@ fn symbol_not_plain(item: Node, tag: &str) -> bool { /// 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 { +pub(super) fn symbol_color(item: Node, tag: &str) -> Option { let symbol = child(item, tag)?.descendants().find(|d| d.has_tag_name("symbol"))?; let Some(layer) = first_enabled(symbol) else { return Some(Rgba::new(0, 0, 0, 0)) }; let props = super::super::props(layer); diff --git a/crates/map/src/qgis/layout_grid_tests.rs b/crates/map/src/qgis/layout_grid_tests.rs new file mode 100644 index 0000000000..8ba3b1c6c9 --- /dev/null +++ b/crates/map/src/qgis/layout_grid_tests.rs @@ -0,0 +1,535 @@ +//! A QGIS map item's grids (piece 12b of #882): the first one shown becomes its frame's grid, +//! written in the shapes QGIS writes them; what RustGIS draws differently is said. + +use super::*; +use crate::layout::{CoordFormat, ElementKind, Grid, GridEdges, GridKind, GridStyle, Orientation, PT_PER_MM}; + +fn read(text: &str, report: &mut Report) -> Project { + super::read_project(text, "/data/proj", &mut |_, _| Err((super::IMAGE_UNOPENED, false)), report).unwrap() +} + +fn texts(report: &Report) -> Vec<&str> { + report.notes.iter().map(|n| n.text.as_str()).collect() +} + +const PAGE: &str = r#""#; + +/// A grid's line: black, `width` in `unit`, of `style`. +fn line(width: &str, unit: &str, style: &str) -> String { + format!( + r#""# + ) +} + +/// Annotations' text: 8 pt in QGIS's default font, black. +const TEXT: &str = r#""#; + +/// A grid RustGIS draws as QGIS does: lines 500 m apart in the map's system, ticks inside on all +/// sides, whole annotations inside the map on all sides, across. +const PLAIN: &str = r#"show="1" gridStyle="0" gridFrameStyle="2" gridFrameSideFlags="15" gridFrameWidth="2" gridFramePenColor="0,0,0,255" gridFramePenThickness="0.3" intervalX="500" intervalY="500" offsetX="0" offsetY="0" unit="0" showAnnotation="1" annotationFormat="0" annotationPrecision="0" blendMode="0" leftAnnotationPosition="0" rightAnnotationPosition="0" topAnnotationPosition="0" bottomAnnotationPosition="0""#; + +/// A grid of `attrs` (each later one replacing an earlier of the same name) and `children`. +fn grid(attrs: &str, children: &str) -> String { + let mut seen = std::collections::BTreeMap::new(); + let mut order = Vec::new(); + for a in format!("{PLAIN} {attrs}").split('"').collect::>().chunks(2) { + if let [k, v] = a { + let k = k.trim().trim_end_matches('=').to_string(); + if !seen.contains_key(&k) { + order.push(k.clone()); + } + seen.insert(k, v.to_string()); + } + } + let attrs: Vec = order.iter().map(|k| format!(r#"{k}="{}""#, seen[k])).collect(); + format!(r#"{children}"#, attrs.join(" ")) +} + +/// A plain grid with these attributes changed, its line and text as QGIS writes them by default. +fn plain(attrs: &str) -> String { + grid(attrs, &format!("{}{TEXT}", line("0.3", "MM", "solid"))) +} + +/// A project (in `crs`) with a 150 mm wide map item holding `grids`, 1,700 m across. +fn project(crs: &str, grids: &str) -> String { + project_at(crs, [2696300.0, 1261200.0, 2698000.0, 1262475.0], grids) +} + +/// A project (in `crs`) with a 150 mm wide map item of `extent` holding `grids`. +fn project_at(crs: &str, [x0, y0, x1, y1]: [f64; 4], grids: &str) -> String { + format!( + r#"T{crs}{PAGE}{grids}"# + ) +} + +/// Degrees around Zürich. +const DEGREES: [f64; 4] = [8.0, 47.0, 9.5, 48.0]; + +/// The first layout's frame's grid. +fn grid_of(p: &Project) -> Option { + p.layouts.first()?.layout.elements.iter().find_map(|e| match &e.kind { + ElementKind::MapFrame { grid, .. } => Some(grid.clone()), + _ => None, + })? +} + +/// A grid drawn as RustGIS draws one comes in as it is, with nothing said. +#[test] +fn a_measured_grid_comes_in_as_drawn() { + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &plain("")), &mut report); + let g = grid_of(&p).unwrap(); + assert_eq!(g.kind, GridKind::Measured); + assert_eq!(g.crs.as_deref(), Some("EPSG:2056")); + assert_eq!(g.step, 500.0); + assert_eq!(g.style, GridStyle::LinesAndTicks); + assert_eq!(g.tick_length, 2.0); + assert!((g.width - 0.3 * PT_PER_MM).abs() < 1e-9); + assert_eq!(g.color, Rgba::rgb(0, 0, 0)); + assert!(g.labels); + assert_eq!(g.edges, GridEdges { top: true, bottom: true, left: true, right: true }); + assert_eq!(g.label_orientation, Orientation::Horizontal); + assert_eq!(g.label_size, 8.0); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); +} + +/// A map item without a grid has none, as before. +#[test] +fn a_map_without_a_grid_has_none() { + let mut report = Report::default(); + let p = read(&project("EPSG:2056", ""), &mut report); + assert_eq!(grid_of(&p), None); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); +} + +/// A grid in degrees (its own system, or the project's) is a graticule, its format kept. +#[test] +fn a_grid_in_degrees_is_a_graticule() { + let wgs84 = r#"EPSG:4326"#; + let g = grid( + r#"intervalX="0.005" intervalY="0.005" annotationFormat="6" annotationPrecision="0""#, + &format!("{}{TEXT}{wgs84}", line("0.3", "MM", "solid")), + ); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &g), &mut report); + let g = grid_of(&p).unwrap(); + assert_eq!((g.kind, g.crs.as_deref(), g.step), (GridKind::Graticule, None, 0.005)); + assert_eq!((g.format, g.hemisphere), (CoordFormat::Dms, false)); + // (QGIS writes its minutes and seconds unpadded: said.) + assert_eq!(texts(&report).len(), 1, "{:?}", texts(&report)); + assert!(texts(&report)[0].contains("in degrees and minutes (and seconds)")); + // The project's own system in degrees, decimal with a suffix; three decimals where the step + // needs one are said. + let mut report = Report::default(); + let p = read( + &project_at("EPSG:4326", DEGREES, &plain(r#"intervalX="0.5" intervalY="0.5" annotationFormat="3" annotationPrecision="3""#)), + &mut report, + ); + let g = grid_of(&p).unwrap(); + assert_eq!((g.kind, g.format, g.hemisphere), (GridKind::Graticule, CoordFormat::Decimal, true)); + assert_eq!(texts(&report), ["its print layouts' map grids' annotations' decimals, as many as the step needs (1)"]); +} + +/// Degrees in another datum are drawn as WGS 84's, said. +#[test] +fn a_graticule_in_another_datum_is_said() { + let ch1903 = r#"EPSG:4150"#; + let g = grid( + r#"intervalX="0.01" intervalY="0.01" annotationFormat="0" annotationPrecision="2""#, + &format!("{}{TEXT}{ch1903}", line("0.3", "MM", "solid")), + ); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &g), &mut report); + assert_eq!(grid_of(&p).unwrap().kind, GridKind::Graticule); + assert!(texts(&report).iter().any(|t| t.contains("in a system other than WGS 84")), "{:?}", texts(&report)); +} + +/// A step in millimetres or centimetres on the page is its map's units at its scale; one in +/// another system than its map's, or fitted to the page, is RustGIS's own, said. +#[test] +fn a_step_on_the_page_converts_to_map_units() { + // 1,700 m across 150 mm: 15 mm is 170 m, 3 cm 340 m. + for (unit, interval, want) in [("1", "15", 170.0), ("2", "3", 340.0)] { + let mut report = Report::default(); + let p = + read(&project("EPSG:2056", &plain(&format!(r#"unit="{unit}" intervalX="{interval}" intervalY="{interval}""#))), &mut report); + assert!((grid_of(&p).unwrap().step - want).abs() < 1e-9); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); + } + let fitted = "its print layouts' map grids fitted to the page, or spaced on it in a coordinate system other than their map's, given a step of RustGIS's to fit (1)"; + let utm = r#"EPSG:32632"#; + for g in + [plain(r#"unit="3""#), grid(r#"unit="1" intervalX="10" intervalY="10""#, &format!("{}{TEXT}{utm}", line("0.3", "MM", "solid")))] + { + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &g), &mut report); + assert_eq!(grid_of(&p).unwrap().step, 0.0); + assert_eq!(texts(&report), [fitted]); + } + // 10 mm is 113.3 m, labelled to four decimals: QGIS's whole labels are said. + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &plain(r#"unit="1" intervalX="10" intervalY="10""#)), &mut report); + assert!((grid_of(&p).unwrap().step - 1700.0 / 15.0).abs() < 1e-9); + assert_eq!(texts(&report), ["its print layouts' map grids' annotations' decimals, as many as the step needs (1)"]); +} + +/// A grid of no step (a new grid's) draws nothing in QGIS: it isn't carried over, nothing said, +/// and the next grid is the frame's. +#[test] +fn a_grid_of_no_step_draws_nothing() { + for step in ["0", "-5", "NaN"] { + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &plain(&format!(r#"intervalX="{step}" intervalY="{step}""#))), &mut report); + assert_eq!(grid_of(&p), None); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); + } + let grids = format!("{}{}", plain(r#"intervalX="0" intervalY="0""#), plain(r#"intervalX="250" intervalY="250""#)); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &grids), &mut report); + assert_eq!(grid_of(&p).unwrap().step, 250.0); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); +} + +/// QGIS's plain decimals print no degree sign, and its minutes and seconds are unpadded and +/// always written: all said; decimals with a suffix are written alike. +#[test] +fn degree_formats_written_otherwise_are_said() { + let formats = "its print layouts' map grids' annotations by an expression, in plain decimals or in degrees and minutes (and seconds), which QGIS writes otherwise, or in degrees on a measured grid, in RustGIS's nearest format (1)"; + for (format, step, said) in + [("0", "0.5", true), ("2", "0.5", true), ("6", "1", true), ("2", "0.0125", true), ("7", "0.0125", true), ("3", "0.5", false)] + { + let attrs = format!( + r#"intervalX="{step}" intervalY="{step}" annotationFormat="{format}" annotationPrecision="{}""#, + if format == "0" || format == "3" { "1" } else { "0" } + ); + let mut report = Report::default(); + read(&project_at("EPSG:4326", DEGREES, &plain(&attrs)), &mut report); + let want: &[&str] = if said { &[formats] } else { &[] }; + assert_eq!(texts(&report), want, "format {format}, step {step}"); + } +} + +/// Steps finer than RustGIS draws are said; those it draws aren't. +#[test] +fn steps_finer_than_rustgis_draws_are_said() { + let fine = "map grids finer than RustGIS draws"; + for (crs, extent, step, said) in [ + ("EPSG:2056", [2696300.0, 1261200.0, 2698000.0, 1262475.0], "10", true), + ("EPSG:2056", [2696300.0, 1261200.0, 2698000.0, 1262475.0], "20", false), + ("EPSG:4326", DEGREES, "0.0005", true), + ("EPSG:4326", DEGREES, "0.005", true), + ("EPSG:4326", DEGREES, "0.01", false), + ] { + let mut report = Report::default(); + let attrs = format!(r#"intervalX="{step}" intervalY="{step}" annotationFormat="3" showAnnotation="0""#); + read(&project_at(crs, extent, &plain(&attrs)), &mut report); + assert_eq!(texts(&report).iter().any(|t| t.contains(fine)), said, "{crs} {step}: {:?}", texts(&report)); + } +} + +/// A custom system's grid reads by its PROJ string; one too long to keep, or the map's that +/// doesn't read, is said. +#[test] +fn a_grids_system_reads_by_its_proj_string() { + let custom = + r#"USER:100000+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs"#; + let mut report = Report::default(); + let p = read( + &project("EPSG:2056", &grid(r#"intervalX="1000" intervalY="1000""#, &format!("{}{TEXT}{custom}", line("0.3", "MM", "solid")))), + &mut report, + ); + let g = grid_of(&p).unwrap(); + assert_eq!(g.kind, GridKind::Measured); + assert!(g.crs.as_deref().is_some_and(|c| c.starts_with("+proj=utm")), "{:?}", g.crs); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); + let unread = "coordinate system that doesn't read"; + let mut report = Report::default(); + read(&project("USER:100000", &plain("")), &mut report); + assert!(texts(&report).iter().any(|t| t.contains(unread)), "{:?}", texts(&report)); + let long = format!(r#"EPSG:{}2056"#, "0".repeat(5000)); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &grid("", &format!("{}{TEXT}{long}", line("0.3", "MM", "solid")))), &mut report); + assert!(grid_of(&p).unwrap().crs.as_deref().is_none_or(|c| c.chars().count() <= crate::layout::MAX_GRID_CRS)); + assert!(texts(&report).iter().any(|t| t.contains(unread)), "{:?}", texts(&report)); +} + +/// QGIS 3's older grids keep their annotations' font and colour as attributes: read. +#[test] +fn an_older_grids_font_is_read() { + let older = r#"annotationFont="Sans Serif,12,-1,5,50,0,0,0,0,0" annotationFontColor="0,0,0,255""#; + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &grid(older, &line("0.3", "MM", "solid"))), &mut report); + assert_eq!(grid_of(&p).unwrap().label_size, 12.0); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); + let mut report = Report::default(); + let red = r#"annotationFont="Georgia,8,-1,5,50,0,0,0,0,0" annotationFontColor="200,0,0,255""#; + read(&project("EPSG:2056", &grid(red, &line("0.3", "MM", "solid"))), &mut report); + assert_eq!(texts(&report).len(), 1, "{:?}", texts(&report)); + assert!(texts(&report)[0].contains("in a font, colour or style of their own")); +} + +/// The first grid shown is the frame's; those past it, and those switched off, are said. +#[test] +fn grids_past_the_first_are_said() { + let grids = + format!("{}{}{}", plain(r#"show="0" intervalX="50" intervalY="50""#), plain(""), plain(r#"intervalX="100" intervalY="100""#)); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &grids), &mut report); + assert_eq!(grid_of(&p).unwrap().step, 500.0); + assert_eq!( + texts(&report), + [ + "its print layouts' map overviews and grids switched off (1)", + "its print layouts' map grids past the first one shown on a map item, which a frame draws (1)" + ] + ); +} + +/// Sides showing latitudes or longitudes only show what crosses them; annotations up the sides +/// run vertical, and sides turned differently are said. +#[test] +fn annotation_sides_and_directions() { + let attrs = r#"topAnnotationDisplay="1" bottomAnnotationDisplay="2" leftAnnotationDisplay="2" rightAnnotationDisplay="3" leftAnnotationDirection="1""#; + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &plain(attrs)), &mut report); + let g = grid_of(&p).unwrap(); + assert_eq!(g.edges, GridEdges { top: false, bottom: true, left: false, right: false }); + // Left hidden: its direction isn't drawn, so nothing is said. + assert_eq!(g.label_orientation, Orientation::Horizontal); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &plain(r#"leftAnnotationDirection="1" rightAnnotationDirection="3""#)), &mut report); + assert_eq!(grid_of(&p).unwrap().label_orientation, Orientation::Vertical); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &plain(r#"leftAnnotationDirection="1" topAnnotationDirection="5""#)), &mut report); + assert_eq!(grid_of(&p).unwrap().label_orientation, Orientation::Vertical); + assert_eq!(texts(&report).len(), 1); + assert!(texts(&report)[0].contains("map grids' annotations upright"), "{:?}", texts(&report)); +} + +/// QGIS's defaults (annotations outside, three decimals) on a measured grid say both. +#[test] +fn qgis_default_annotations_are_said() { + let mut report = Report::default(); + let attrs = r#"annotationPrecision="3" leftAnnotationPosition="1" rightAnnotationPosition="1" topAnnotationPosition="1" bottomAnnotationPosition="1""#; + read(&project("EPSG:2056", &plain(attrs)), &mut report); + assert_eq!( + texts(&report), + [ + "its print layouts' map grids' annotations outside their map, drawn just inside its edge (1)", + "its print layouts' map grids' annotations' decimals, as many as the step needs (1)" + ] + ); +} + +/// Its frame and annotations alone: no lines, its ticks in its frame's pen. +#[test] +fn a_frame_only_grid_draws_ticks_in_its_pen() { + let mut report = Report::default(); + let p = + read(&project("EPSG:2056", &plain(r#"gridStyle="3" gridFramePenColor="200,0,0,255" gridFramePenThickness="0.5""#)), &mut report); + let g = grid_of(&p).unwrap(); + assert_eq!((g.style, g.tick_length, g.color), (GridStyle::Ticks, 2.0, Rgba::rgb(200, 0, 0))); + assert!((g.width - 0.5 * PT_PER_MM).abs() < 1e-9); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); + // No frame: annotations alone, without ticks. + let p = read(&project("EPSG:2056", &plain(r#"gridStyle="3" gridFrameStyle="0""#)), &mut Report::default()); + assert_eq!(grid_of(&p).unwrap().tick_length, 0.0); + // Ticks in a pen of their own beside lines are said. + let mut report = Report::default(); + read(&project("EPSG:2056", &plain(r#"gridFramePenColor="200,0,0,255""#)), &mut report); + assert_eq!(texts(&report), ["its print layouts' map grids' ticks in a colour or width of their own, drawn as their lines (1)"]); +} + +/// What RustGIS's grid can't draw is said, each kind once a grid. +#[test] +fn what_a_grid_draws_differently_is_said() { + let attrs = r#"gridStyle="1" gridFrameStyle="1" intervalY="400" offsetX="5" blendMode="6" rotatedTicksEnabled="1""#; + let children = format!( + r#"{}"#, + line("0.3", "MM", "dash") + ); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &grid(attrs, &children)), &mut report); + assert_eq!(grid_of(&p).unwrap().style, GridStyle::Lines); + let said = texts(&report); + for part in [ + "map grids' zebra, line border and nautical frames (1)", + "map grids of crosses or markers, drawn as lines (1)", + "in a font, colour or style of their own", + "different steps across and up", + "map grids' offsets", + "map grids' lines dashed", + "map grids' blending modes", + "set to turn with a turned map", + ] { + assert!(said.iter().any(|t| t.contains(part)), "{part}: {said:?}"); + } + assert_eq!(said.len(), 8, "{said:?}"); +} + +/// Ticks showing latitudes or longitudes only on a side are said. +#[test] +fn ticks_of_some_coordinates_are_said() { + let mut report = Report::default(); + read(&project("EPSG:2056", &plain(r#"leftFrameDivisions="2""#)), &mut report); + assert_eq!( + texts(&report), + ["its print layouts' map grids' ticks on some sides only, or showing some coordinates only, drawn on all four for all (1)"] + ); + // Without ticks, divisions show nothing. + let mut report = Report::default(); + read(&project("EPSG:2056", &plain(r#"leftFrameDivisions="2" gridFrameStyle="0""#)), &mut report); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); +} + +/// Ticks outside or on some sides only are drawn inside, on all four, said. +#[test] +fn ticks_outside_or_on_some_sides_are_said() { + let mut report = Report::default(); + read(&project("EPSG:2056", &plain(r#"gridFrameStyle="3" gridFrameSideFlags="5""#)), &mut report); + assert_eq!( + texts(&report), + [ + "its print layouts' map grids' ticks outside their map or across its edge, drawn inside it (1)", + "its print layouts' map grids' ticks on some sides only, or showing some coordinates only, drawn on all four for all (1)" + ] + ); +} + +/// Hostile numbers are brought within RustGIS's, said, and never panic. +#[test] +fn hostile_grid_numbers_are_brought_within_range() { + let attrs = r#"intervalX="1e300" intervalY="1e300" gridFrameWidth="1e9" annotationFormat="99" unit="-7" leftAnnotationDisplay="NaN" gridFrameSideFlags="x""#; + let children = format!(r#"{}"#, line("1e9", "MM", "solid")); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &grid(attrs, &children)), &mut report); + let g = grid_of(&p).unwrap(); + assert_eq!(g.step, 0.0, "a unit that doesn't read is fitted"); + assert_eq!(g.tick_length, crate::layout::MAX_TICK_MM); + assert_eq!(g.width, crate::layout::MAX_GRID_WIDTH); + assert_eq!(g.label_size, 100.0); + let said = texts(&report); + assert!(said.iter().any(|t| t.contains("brought within RustGIS's (1 m to 10,000 km")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("annotation sizes outside 4 to 100 pt")), "{said:?}"); + // A step in map units past the widest is brought down to it. + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &plain(r#"intervalX="1e300" intervalY="1e300""#)), &mut report); + assert_eq!(grid_of(&p).unwrap().step, crate::layout::MAX_MEASURED_STEP); + assert_eq!(texts(&report).len(), 1, "{:?}", texts(&report)); + // A step up of none, a line width that doesn't read, a system that doesn't read, and + // settings past QGIS's. + let junk = r#"+proj=nonsense"#; + let mut report = Report::default(); + let attrs = r#"intervalY="-5" gridStyle="9" leftAnnotationDirection="40""#; + let p = read(&project("EPSG:2056", &grid(attrs, &format!("{}{TEXT}{junk}", line("NaN", "MM", "solid")))), &mut report); + let g = grid_of(&p).unwrap(); + assert_eq!((g.kind, g.step), (GridKind::Measured, 500.0)); + assert!(texts(&report).iter().any(|t| t.contains("settings that don't read")), "{:?}", texts(&report)); + assert!(g.width.is_finite()); + assert!(texts(&report).iter().any(|t| t.contains("coordinate system that doesn't read")), "{:?}", texts(&report)); +} + +/// The corpus's grids: a measured grid as drawn (a second on its map said), and a graticule of +/// crosses with a zebra frame and annotations outside, in degrees, minutes and seconds. +#[test] +fn the_corpus_grids_come_in() { + 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-grids.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 mut grids: Vec<(f64, Grid)> = l + .elements + .iter() + .filter_map(|e| match &e.kind { + ElementKind::MapFrame { grid: Some(g), .. } => Some((e.x, g.clone())), + _ => None, + }) + .collect(); + grids.sort_by(|a, b| a.0.total_cmp(&b.0)); + let [(_, m), (_, d)] = grids.as_slice() else { panic!("{grids:?}") }; + assert_eq!((m.kind, m.step, m.style, m.tick_length), (GridKind::Measured, 500.0, GridStyle::LinesAndTicks, 2.0)); + assert_eq!(m.crs.as_deref(), Some("EPSG:2056")); + assert_eq!(m.edges, GridEdges { top: true, bottom: true, left: true, right: true }); + assert_eq!((d.kind, d.step, d.style), (GridKind::Graticule, 0.005, GridStyle::Lines)); + assert_eq!((d.format, d.hemisphere), (CoordFormat::Dms, true)); + assert_eq!( + texts(&report), + [ + "its print layouts' map overviews and grids switched off (1)", + "its print layouts' map grids past the first one shown on a map item, which a frame draws (1)", + "its print layouts' map grids' zebra, line border and nautical frames (1)", + "its print layouts' map grids of crosses or markers, drawn as lines (1)", + "its print layouts' map grids' annotations outside their map, drawn just inside its edge (1)", + "its print layouts' map grids' annotations by an expression, in plain decimals or in degrees and minutes (and seconds), which QGIS writes otherwise, or in degrees on a measured grid, in RustGIS's nearest format (1)", + "its print layouts' map grids' annotations' decimals, as many as the step needs (1)", + "its print layouts' map grids' annotations in a font, colour or style of their own, in RustGIS's grid labels' font and colour (2)", + ] + ); +} + +/// Finer than RustGIS draws is said for a grid in a system of its own too, over its map's extent +/// in that system. +#[test] +fn steps_finer_than_rustgis_draws_are_said_across_systems() { + let fine = "map grids finer than RustGIS draws"; + let wgs84 = r#"EPSG:4326"#; + let utm = r#"EPSG:32632"#; + // The 1,700 m map is about 0.022° across: 0.0001° is 220 lines, 0.0005° 45; under 0.001° is + // drawn at it, said whatever the extent. In UTM, 10 m is 170 lines across, 20 m 85. + for (srs, step, said) in + [(wgs84, "0.0001", true), (wgs84, "0.0005", true), (wgs84, "0.002", false), (utm, "10", true), (utm, "20", false)] + { + let attrs = format!(r#"intervalX="{step}" intervalY="{step}" annotationFormat="3" showAnnotation="0""#); + let mut report = Report::default(); + read(&project("EPSG:2056", &grid(&attrs, &format!("{}{TEXT}{srs}", line("0.3", "MM", "solid")))), &mut report); + assert_eq!(texts(&report).iter().any(|t| t.contains(fine)), said, "{step}: {:?}", texts(&report)); + } +} + +/// A custom system shifted to WGS 84 is another datum, said; one on WGS 84 itself isn't. +#[test] +fn a_custom_geographic_systems_datum() { + for (proj, said) in + [("+proj=longlat +ellps=bessel +towgs84=674.374,15.056,405.346 +no_defs", true), ("+proj=longlat +datum=WGS84 +no_defs", false)] + { + let srs = format!(r#"USER:100001{proj}"#); + let attrs = r#"intervalX="0.005" intervalY="0.005" annotationFormat="3" showAnnotation="0""#; + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &grid(attrs, &format!("{}{TEXT}{srs}", line("0.3", "MM", "solid")))), &mut report); + assert_eq!(grid_of(&p).unwrap().kind, GridKind::Graticule); + assert_eq!(texts(&report).iter().any(|t| t.contains("other than WGS 84")), said, "{proj}: {:?}", texts(&report)); + } +} + +/// A project in a custom system reads by its PROJ string: a page step converts, nothing said. +#[test] +fn a_custom_project_system_reads() { + let text = project("EPSG:2056", &plain(r#"unit="1" intervalX="15" intervalY="15""#)).replace( + "EPSG:2056", + "USER:100000+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", + ); + let mut report = Report::default(); + let p = read(&text, &mut report); + let g = grid_of(&p).unwrap(); + assert_eq!((g.kind, g.step), (GridKind::Measured, 170.0)); + assert!(g.crs.as_deref().is_some_and(|c| c.starts_with("+proj=somerc")), "{:?}", g.crs); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); +} + +/// No step up is drawn at the step across, said; a setting past QGIS's is said once, as one +/// that doesn't read, and annotations' settings only when it shows them. +#[test] +fn a_missing_step_up_and_odd_settings_are_said_once() { + let mut report = Report::default(); + read(&project("EPSG:2056", &plain(r#"intervalY="0""#)), &mut report); + assert_eq!(texts(&report), ["its print layouts' map grids with different steps across and up, drawn at the step across (1)"]); + let mut report = Report::default(); + read(&project("EPSG:2056", &plain(r#"leftAnnotationPosition="5" topAnnotationDirection="40""#)), &mut report); + assert_eq!(texts(&report), ["its print layouts' map grids' settings that don't read, drawn as RustGIS's (1)"]); + let mut report = Report::default(); + read(&project("EPSG:2056", &plain(r#"showAnnotation="0" leftAnnotationPosition="5""#)), &mut report); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); +} diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 523358b7ee..09d5f4435c 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_grid_tests; +#[cfg(test)] mod layout_legend_tests; #[cfg(test)] mod layout_surround_tests; @@ -805,7 +807,12 @@ pub fn read_project(text: &str, dir: &str, images: &mut ReadImage, report: &mut project.layers = layers.into_iter().map(|(_, l)| l).collect(); resolve_virtual_layers(&mut project.layers, report); // The print layouts, after the layers: their legends list the layers as the import made them. - project.layouts = layout::read_layouts(root, dir, (&project.title, &project.layers, project.main_annotations.as_ref()), report); + project.layouts = layout::read_layouts( + root, + dir, + (&project.title, project.crs.as_deref(), &project.layers, project.main_annotations.as_ref()), + report, + ); group_notes(&tree, &blended, &effects, report); if !unkept.is_empty() { let names = unkept.iter().take(8).map(String::as_str).collect::>().join(", "); diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 3ffaf36410..f11e950fbc 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(), 41, "project corpus changed: {projects:?}"); + assert_eq!(projects.len(), 42, "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 04e14435af..1d34795244 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/` | 41 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; `layout-legends.qgs`, a sheet with legends (one listing the project's layers, its points in two categories; one with its own list, a layer renamed and another left out, in two columns; one filtered by its map), 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/` | 42 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; `layout-legends.qgs`, a sheet with legends (one listing the project's layers, its points in two categories; one with its own list, a layer renamed and another left out, in two columns; one filtered by its map), written by QGIS 4.4.0; `layout-grids.qgs`, a sheet with map grids (a measured grid in the map's system with ticks and annotations inside the map, a second grid on the same map and one switched off; a graticule of crosses in degrees, minutes and seconds with a zebra frame and annotations outside), 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-surrounds.qgs` and `qgs/layout-legends.qgs`. +`qgs/layout-sheets.qgs`, `qgs/layout-surrounds.qgs`, `qgs/layout-legends.qgs` and `qgs/layout-grids.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 2f795f0fa2..edf5ac665e 100644 --- a/crates/map/testdata/qgis/generated/generate.py +++ b/crates/map/testdata/qgis/generated/generate.py @@ -1524,6 +1524,78 @@ def layout_legends(): attempt("layout legends", layout_legends) + + +# A sheet with map grids (piece 12b): a measured grid in the map's own system, with ticks inside +# and annotations inside the map (as RustGIS draws a grid), and a second grid on the same map, +# which a RustGIS frame doesn't draw; and a graticule of crosses in degrees, minutes and seconds, +# with a zebra frame and annotations outside, said as drawn differently. +def layout_grids(): + from qgis.core import QgsLayoutItemPage, QgsLayoutItemMapGrid, QgsLayoutExporter, QgsTextFormat + from qgis.PyQt.QtGui import QFont + mm = Qgis.LayoutUnit.Millimeters + G = QgsLayoutItemMapGrid + p = new_project() + p.relationManager().setPolymorphicRelations([]) + p.setTitle("Grids") + pts, polys = layer("points"), layer("polygons") + p.addMapLayers([pts, polys]) + lay = QgsPrintLayout(p) + lay.initializeDefaults() + lay.setName("Grids") + lay.pageCollection().page(0).setPageSize("A4", QgsLayoutItemPage.Orientation.Landscape) + fmt = QgsTextFormat() + fmt.setFont(QFont("DejaVu Sans")) + fmt.setSize(8) + + def map_at(x, w): + m = QgsLayoutItemMap(lay) + lay.addLayoutItem(m) + m.attemptMove(QgsLayoutPoint(x, 20, mm)) + m.attemptResize(QgsLayoutSize(w, 120, mm)) + m.setExtent(QgsRectangle(2696300, 1261200, 2698000, 1262475)) + m.setFrameEnabled(True) + return m + + m = map_at(10, 120) + g = G("Measured", m) + m.grids().addGrid(g) + g.setIntervalX(500) + g.setIntervalY(500) + g.setFrameStyle(G.FrameStyle.InteriorTicks) + g.setFrameWidth(2) + g.setAnnotationEnabled(True) + g.setAnnotationPrecision(0) + g.setAnnotationTextFormat(fmt) + for side in (G.BorderSide.Left, G.BorderSide.Right, G.BorderSide.Top, G.BorderSide.Bottom): + g.setAnnotationPosition(G.AnnotationPosition.InsideMapFrame, side) + second = G("Second", m) + m.grids().addGrid(second) + second.setIntervalX(100) + second.setIntervalY(100) + off = G("Off", m) + m.grids().addGrid(off) + off.setEnabled(False) + n = map_at(160, 105) + d = G("Degrees", n) + n.grids().addGrid(d) + d.setCrs(QgsCoordinateReferenceSystem("EPSG:4326")) + d.setStyle(G.GridStyle.Cross) + d.setIntervalX(0.005) + d.setIntervalY(0.005) + d.setFrameStyle(G.FrameStyle.Zebra) + d.setAnnotationEnabled(True) + d.setAnnotationFormat(G.AnnotationFormat.DegreeMinuteSecond) + d.setAnnotationTextFormat(fmt) + p.layoutManager().addLayout(lay) + save_project(p, "layout-grids") + os.makedirs(os.path.join(OUT, "renders"), exist_ok=True) + settings = QgsLayoutExporter.ImageExportSettings() + settings.dpi = 96 + QgsLayoutExporter(lay).exportToImage(os.path.join(OUT, "renders", "Grids.png"), settings) + + +attempt("layout grids", layout_grids) attempt("all styles project", all_styles) diff --git a/crates/map/testdata/qgis/generated/qgs/layout-grids.qgs b/crates/map/testdata/qgis/generated/qgs/layout-grids.qgs new file mode 100644 index 0000000000..6004447ea5 --- /dev/null +++ b/crates/map/testdata/qgis/generated/qgs/layout-grids.qgs @@ -0,0 +1,2009 @@ + + + + Grids + + + + + 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_e666b6cd_7a13_44e5_b13b_e720f4015b43 + polygons_ac0eed85_f949_400c_b64b_86bd04e175f5 + + + + + + + + + + + + Annotations_90441d90_0583_411b_83b1_06fe2bb5bd60 + + 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_e666b6cd_7a13_44e5_b13b_e720f4015b43 + ../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_ac0eed85_f949_400c_b64b_86bd04e175f5 + ../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 + + + + + + + + + + + + + Grids + + + + + + Unknown + 2026-12-02T11:05:58 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 139fe1b873..bd89d7ad08 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -455,10 +455,17 @@ shows `` only where a layer has that category or an ELSE rule. (listed flat), its classes' own labels and rows, hidden layers it lists (unless filtered by its map), one of two layers of a name, a layer kept whole across columns and text styles of its own are noted; one QGIS hasn't sized yet is given room for a row a layer, and one of a map on another -page shows its page's first map, noted. One on a page without a map 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: 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 +page shows its page's first map, noted. One on a page without a map is left out, noted. A map +item's first grid shown becomes its frame's grid: in degrees a graticule, else a measured grid in +its coordinate system, with its step (a step in millimetres or centimetres on the page as map +units at the map's scale), lines, ticks inside the map and their length, line colour and width, +and its annotations' sides, direction, format and size; a grid of no step, which QGIS draws +nothing of, isn't. Further grids, zebra, line border and nautical frames, crosses and markers +(drawn as lines), ticks or annotations outside the map (drawn inside), offsets, annotations' own +fonts, decimals and formats RustGIS writes otherwise, steps finer than RustGIS draws, a step fitted +to the page and a coordinate system that doesn't read are 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: tables, HTML and other items, 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 0ce03d60f1c99b195343293d3d5c412ae5a999b0 Mon Sep 17 00:00:00 2001 From: strebdom Date: Wed, 2 Dec 2026 13:57:20 +0100 Subject: [PATCH 2/4] fix(map): QGIS map grids of a step one way, on the page or on a turned map, and unchecked fineness, said - A grid with a step up only (or across only) draws that way's lines in QGIS: read at that step, said. - A step in millimetres or centimetres on the page is drawn by QGIS from the map's corner and labelled with page distances: said. - On a map turned a quarter, sides' latitudes or longitudes only follow the turn; turned otherwise, showing both is said. - With neither system reading, fineness is told from the extent; an extent that doesn't convert is said as unchecked. - The guide's paragraph says which page steps convert and which grids are read. --- crates/map/src/qgis/layout.rs | 3 +- crates/map/src/qgis/layout/grid.rs | 100 ++++++++++++++++------- crates/map/src/qgis/layout_grid_tests.rs | 98 ++++++++++++++++++++-- docs/user-guide/workspace.md | 17 ++-- 4 files changed, 175 insertions(+), 43 deletions(-) diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs index dabcc7327c..2bb0635261 100644 --- a/crates/map/src/qgis/layout.rs +++ b/crates/map/src/qgis/layout.rs @@ -797,7 +797,8 @@ fn map_item(item: Node, place: &Placed, id: Option, target: &mut Project // millimetre being its extent's width over its own. let map_crs = child(item, "crs").and_then(grid::readable_crs).or_else(|| tally.project_crs.clone()); let per_mm = (place.w > 0.0).then(|| (extent[2] - extent[0]) / place.w).filter(|v| v.is_finite() && *v > 0.0); - let grid = grid::map_grid(item, map_crs.as_deref(), extent, per_mm, tally); + let turn = num(item, "mapRotation").filter(|r| r.is_finite()).unwrap_or(0.0); + let grid = grid::map_grid(item, map_crs.as_deref(), extent, per_mm, turn, tally); if item.attribute("keepLayerSet") == Some("true") || item.attribute("followPreset") == Some("true") { tally.locked_layers += 1; } diff --git a/crates/map/src/qgis/layout/grid.rs b/crates/map/src/qgis/layout/grid.rs index 48b9c6b221..458216d03e 100644 --- a/crates/map/src/qgis/layout/grid.rs +++ b/crates/map/src/qgis/layout/grid.rs @@ -34,6 +34,9 @@ pub(super) struct Counts { datum: usize, unread_crs: usize, fine: usize, + unchecked: usize, + paper: usize, + kinds: usize, odd: usize, /// What reading its labels' size noted. notes: Report, @@ -67,7 +70,11 @@ impl Counts { (self.decimals, "map grids' annotations' decimals, as many as the step needs"), (self.fonts, "map grids' annotations in a font, colour or style of their own, in RustGIS's grid labels' font and colour"), (self.sizes, "map grids' annotation sizes outside 4 to 100 pt, drawn at the nearest"), - (self.steps, "map grids with different steps across and up, drawn at the step across"), + (self.steps, "map grids with different steps across and up, or lines one way only, drawn at one step both ways"), + ( + self.paper, + "map grids spaced in millimetres or centimetres on the page, their lines at round map coordinates and labelled with them rather than from the map's corner on the page", + ), (self.offsets, "map grids' offsets, their lines drawn from zero"), ( self.fitted, @@ -86,6 +93,8 @@ impl Counts { self.fine, "map grids finer than RustGIS draws (more than 100 lines across a measured grid, 200 latitudes or longitudes, or less than 0.001° apart), drawn wider or cut there", ), + (self.unchecked, "map grids whose map's extent doesn't convert to their coordinate system, how fine they draw unchecked"), + (self.kinds, "map grids' annotations on a turned map's sides set to latitudes or longitudes only, showing both"), (self.odd, "map grids' settings that don't read, drawn as RustGIS's"), ]; for (n, what) in approximated { @@ -99,20 +108,30 @@ impl Counts { /// The map item's frame's grid: its first grid shown (`show` other than 0). Those switched off, /// and those past the first, are counted. `map_crs` is the system the map item shows its extent -/// in (its own, else the project's), `per_mm` its map units a millimetre across the page. -pub(super) fn map_grid(item: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option, tally: &mut Tally) -> Option { +/// in (its own, else the project's), `per_mm` its map units a millimetre across the page, `turn` +/// the map's rotation in degrees (QGIS's `mapRotation`). +pub(super) fn map_grid( + item: Node, + map_crs: Option<&str>, + extent: [f64; 4], + per_mm: Option, + turn: f64, + tally: &mut Tally, +) -> Option { let mut grid = None; 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. + let step = |k: &str| num(g, k).is_some_and(|i| i > 0.0); if g.attribute("show") == Some("0") { tally.overviews_off += 1; - } else if int(g, "unit") != Some(3) && num(g, "intervalX").is_none_or(|i| i <= 0.0) { - // A step of none (a new grid's) draws nothing in QGIS: nothing to carry over. + } else if int(g, "unit") != Some(3) && !step("intervalX") && !step("intervalY") { + // A step of none either way (a new grid's) draws nothing in QGIS: nothing to carry + // over. (A step one way only draws that way's lines.) continue; } else if grid.is_some() { tally.grid.past += 1; } else { - grid = Some(read_grid(g, map_crs, extent, per_mm, &mut tally.grid)); + grid = Some(read_grid(g, map_crs, extent, per_mm, turn, &mut tally.grid)); } } grid @@ -123,7 +142,7 @@ fn int(n: Node, k: &str) -> Option { num(n, k).filter(|v| v.fract() == 0.0 && v.abs() < 1e9).map(|v| v as i64) } -fn read_grid(g: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option, counts: &mut Counts) -> Grid { +fn read_grid(g: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option, turn: f64, counts: &mut Counts) -> Grid { use rustgis_data::raster::Crs; // Its coordinate system: its own, else its map's (each read by its code, else its PROJ // string, as a custom system's code doesn't read). One that doesn't read, or longer than a @@ -167,17 +186,24 @@ fn read_grid(g: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option Some(10.0), _ => None, }; - // (A grid of no step in map units or on the page draws nothing, and isn't read.) + // (A grid of no step either way in map units or on the page draws nothing, and isn't read; + // one of a step one way only draws that way's lines, here at that step both ways.) + let given = if ix > 0.0 { ix } else { iy }; let step = match (unit, page_mm, per_mm) { - (0, ..) if ix > 0.0 => ix, - (_, Some(mm), Some(per_mm)) if ix > 0.0 && same_system => ix * mm * per_mm, + (0, ..) if given > 0.0 => given, + (_, Some(mm), Some(per_mm)) if given > 0.0 && same_system => { + // QGIS draws it from the map's lower left corner on the page, labelled with the + // page's distance from there: RustGIS's lines are at round map coordinates. + counts.paper += 1; + given * mm * per_mm + } _ => { counts.fitted += 1; 0.0 } }; - // A step up other than across, or none (drawn at the step across). - counts.steps += usize::from(unit != 3 && (iy <= 0.0 || (ix - iy).abs() > 1e-9 * ix.abs().max(iy.abs()))); + // A step up other than across, or none either way (drawn at the one given both ways). + counts.steps += usize::from(unit != 3 && (ix <= 0.0 || iy <= 0.0 || (ix - iy).abs() > 1e-9 * ix.abs().max(iy.abs()))); counts.offsets += usize::from(num(g, "offsetX").is_some_and(|v| v != 0.0) || num(g, "offsetY").is_some_and(|v| v != 0.0)); let kept = match kind { GridKind::Graticule => step.min(MAX_GRATICULE_STEP), @@ -189,20 +215,23 @@ fn read_grid(g: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option extent_in(extent, map_read, crs), - GridKind::Graticule => extent_in(extent, map_read, None), + // (Neither system reading, the grid is drawn by its extent as it is.) + let span = match (kind, map_read, own_read) { + (_, None, None) => Some(extent), + (GridKind::Measured, ..) => extent_in(extent, map_read, crs), + (GridKind::Graticule, ..) => extent_in(extent, map_read, None), }; - counts.fine += usize::from( - step > 0.0 - && match kind { - GridKind::Measured => span.is_some_and(|e| (e[2] - e[0]).max(e[3] - e[1]) / step > 100.0), - GridKind::Graticule => { - let lines = |a: f64, b: f64| (b / step.max(0.001)).floor() - (a / step.max(0.001)).floor() + 1.0; - step < 0.001 || span.is_some_and(|e| lines(e[0], e[2]) > 200.0 || lines(e[0], e[2]) + lines(e[1], e[3]) > 400.0) - } - }, - ); + let fine = step > 0.0 + && match kind { + GridKind::Measured => span.is_some_and(|e| (e[2] - e[0]).max(e[3] - e[1]) / step > 100.0), + GridKind::Graticule => { + let lines = |a: f64, b: f64| (b / step.max(0.001)).floor() - (a / step.max(0.001)).floor() + 1.0; + step < 0.001 || span.is_some_and(|e| lines(e[0], e[2]) > 200.0 || lines(e[0], e[2]) + lines(e[1], e[3]) > 400.0) + } + }; + counts.fine += usize::from(fine); + // Its map's extent not converting to its system, how fine it draws can't be told: said. + counts.unchecked += usize::from(step > 0.0 && !fine && span.is_none()); // Its frame: ticks inside (2), outside (3) or across (4) the map's edge, which RustGIS draws // inside; a zebra, a line border or nautical (1, 5 to 7), left out. @@ -286,21 +315,32 @@ fn read_grid(g: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option = [("left", grid.edges.left), ("right", grid.edges.right), ("bottom", grid.edges.bottom), ("top", grid.edges.top)] .into_iter() .filter_map(|(s, on)| on.then_some(s)) diff --git a/crates/map/src/qgis/layout_grid_tests.rs b/crates/map/src/qgis/layout_grid_tests.rs index 8ba3b1c6c9..4fa339e0ed 100644 --- a/crates/map/src/qgis/layout_grid_tests.rs +++ b/crates/map/src/qgis/layout_grid_tests.rs @@ -145,17 +145,23 @@ fn a_graticule_in_another_datum_is_said() { } /// A step in millimetres or centimetres on the page is its map's units at its scale; one in -/// another system than its map's, or fitted to the page, is RustGIS's own, said. +/// another system than its map's, or fitted to the page, is RustGIS's own, said. QGIS draws one +/// on the page from the map's corner, labelled with the page's distance from there: said. #[test] fn a_step_on_the_page_converts_to_map_units() { + let paper = "its print layouts' map grids spaced in millimetres or centimetres on the page, their lines at round map coordinates and labelled with them rather than from the map's corner on the page (1)"; // 1,700 m across 150 mm: 15 mm is 170 m, 3 cm 340 m. for (unit, interval, want) in [("1", "15", 170.0), ("2", "3", 340.0)] { let mut report = Report::default(); let p = read(&project("EPSG:2056", &plain(&format!(r#"unit="{unit}" intervalX="{interval}" intervalY="{interval}""#))), &mut report); assert!((grid_of(&p).unwrap().step - want).abs() < 1e-9); - assert!(texts(&report).is_empty(), "{:?}", texts(&report)); + assert_eq!(texts(&report), [paper]); } + // In map units, nothing is said. + let mut report = Report::default(); + read(&project("EPSG:2056", &plain(r#"unit="0" intervalX="170" intervalY="170""#)), &mut report); + assert!(texts(&report).is_empty(), "{:?}", texts(&report)); let fitted = "its print layouts' map grids fitted to the page, or spaced on it in a coordinate system other than their map's, given a step of RustGIS's to fit (1)"; let utm = r#"EPSG:32632"#; for g in @@ -170,7 +176,7 @@ fn a_step_on_the_page_converts_to_map_units() { let mut report = Report::default(); let p = read(&project("EPSG:2056", &plain(r#"unit="1" intervalX="10" intervalY="10""#)), &mut report); assert!((grid_of(&p).unwrap().step - 1700.0 / 15.0).abs() < 1e-9); - assert_eq!(texts(&report), ["its print layouts' map grids' annotations' decimals, as many as the step needs (1)"]); + assert_eq!(texts(&report), ["its print layouts' map grids' annotations' decimals, as many as the step needs (1)", paper]); } /// A grid of no step (a new grid's) draws nothing in QGIS: it isn't carried over, nothing said, @@ -504,7 +510,8 @@ fn a_custom_geographic_systems_datum() { } } -/// A project in a custom system reads by its PROJ string: a page step converts, nothing said. +/// A project in a custom system reads by its PROJ string: a page step converts, said only as one +/// on the page. #[test] fn a_custom_project_system_reads() { let text = project("EPSG:2056", &plain(r#"unit="1" intervalX="15" intervalY="15""#)).replace( @@ -516,7 +523,86 @@ fn a_custom_project_system_reads() { let g = grid_of(&p).unwrap(); assert_eq!((g.kind, g.step), (GridKind::Measured, 170.0)); assert!(g.crs.as_deref().is_some_and(|c| c.starts_with("+proj=somerc")), "{:?}", g.crs); - assert!(texts(&report).is_empty(), "{:?}", texts(&report)); + assert_eq!(texts(&report).len(), 1, "{:?}", texts(&report)); + assert!(texts(&report)[0].contains("spaced in millimetres or centimetres on the page"), "{:?}", texts(&report)); +} + +const STEPS: &str = + "its print layouts' map grids with different steps across and up, or lines one way only, drawn at one step both ways (1)"; + +/// A step one way only draws that way's lines in QGIS: the grid is read at that step both ways, +/// said, and isn't passed over for the next one. +#[test] +fn a_step_one_way_only_is_read() { + for (x, y) in [("0", "400"), ("400", "0"), ("-1", "400")] { + let grids = format!("{}{}", plain(&format!(r#"intervalX="{x}" intervalY="{y}""#)), plain(r#"intervalX="250" intervalY="250""#)); + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &grids), &mut report); + assert_eq!(grid_of(&p).unwrap().step, 400.0, "{x} {y}"); + assert_eq!( + texts(&report), + ["its print layouts' map grids past the first one shown on a map item, which a frame draws (1)", STEPS], + "{x} {y}" + ); + } +} + +/// A grid whose map's system doesn't read is drawn by its map's extent as it is: how fine it +/// draws is told from that; one in a system of its own that the extent can't be converted to +/// says it went unchecked. +#[test] +fn fineness_with_a_system_that_doesnt_read() { + let fine = "map grids finer than RustGIS draws"; + let unchecked = "map grids whose map's extent doesn't convert to their coordinate system, how fine they draw unchecked"; + for (step, said) in [("10", true), ("20", false)] { + let mut report = Report::default(); + read(&project("USER:999999", &plain(&format!(r#"intervalX="{step}" intervalY="{step}""#))), &mut report); + let t = texts(&report); + assert_eq!(t.iter().any(|t| t.contains(fine)), said, "{step}: {t:?}"); + assert!(!t.iter().any(|t| t.contains(unchecked)), "{step}: {t:?}"); + } + let utm = r#"EPSG:32632"#; + let g = grid(r#"intervalX="10" intervalY="10""#, &format!("{}{TEXT}{utm}", line("0.3", "MM", "solid"))); + let mut report = Report::default(); + read(&project("USER:999999", &g), &mut report); + let t = texts(&report); + assert!(t.iter().any(|t| t.contains(unchecked)), "{t:?}"); + assert!(!t.iter().any(|t| t.contains(fine)), "{t:?}"); + // Its map's reading, nothing of the kind is said. + let mut report = Report::default(); + read(&project("EPSG:2056", &g), &mut report); + assert!(!texts(&report).iter().any(|t| t.contains(unchecked)), "{:?}", texts(&report)); +} + +/// A map turned a quarter shows latitudes (northings) along its top and bottom: a side's +/// latitudes or longitudes only follow them; turned otherwise, a side of one kind shows both, +/// said; facing south, as facing north. +#[test] +fn annotation_sides_on_a_turned_map() { + let attrs = r#"topAnnotationDisplay="1" bottomAnnotationDisplay="3" leftAnnotationDisplay="3" rightAnnotationDisplay="2""#; + let turned = |turn: &str, report: &mut Report| { + let text = project("EPSG:2056", &plain(attrs)).replace(r#"zValue="1""#, &format!(r#"zValue="1" mapRotation="{turn}""#)); + grid_of(&read(&text, report)).unwrap().edges + }; + let kinds = "its print layouts' map grids' annotations on a turned map's sides set to latitudes or longitudes only, showing both (1)"; + for (turn, want, said) in [ + ("0", GridEdges { top: false, bottom: false, left: false, right: false }, false), + ("180", GridEdges { top: false, bottom: false, left: false, right: false }, false), + ("90", GridEdges { top: true, bottom: false, left: false, right: true }, false), + ("-90", GridEdges { top: true, bottom: false, left: false, right: true }, false), + ("270", GridEdges { top: true, bottom: false, left: false, right: true }, false), + ("89.9999999", GridEdges { top: true, bottom: false, left: false, right: true }, false), + ("30", GridEdges { top: true, bottom: false, left: false, right: true }, true), + ] { + let mut report = Report::default(); + assert_eq!(turned(turn, &mut report), want, "{turn}"); + assert_eq!(texts(&report).contains(&kinds), said, "{turn}: {:?}", texts(&report)); + } + // Every side showing both kinds is said at no angle. + let mut report = Report::default(); + let text = project("EPSG:2056", &plain("")).replace(r#"zValue="1""#, r#"zValue="1" mapRotation="30""#); + assert_eq!(grid_of(&read(&text, &mut report)).unwrap().edges, GridEdges { top: true, bottom: true, left: true, right: true }); + assert!(!texts(&report).contains(&kinds), "{:?}", texts(&report)); } /// No step up is drawn at the step across, said; a setting past QGIS's is said once, as one @@ -525,7 +611,7 @@ fn a_custom_project_system_reads() { fn a_missing_step_up_and_odd_settings_are_said_once() { let mut report = Report::default(); read(&project("EPSG:2056", &plain(r#"intervalY="0""#)), &mut report); - assert_eq!(texts(&report), ["its print layouts' map grids with different steps across and up, drawn at the step across (1)"]); + assert_eq!(texts(&report), [STEPS]); let mut report = Report::default(); read(&project("EPSG:2056", &plain(r#"leftAnnotationPosition="5" topAnnotationDirection="40""#)), &mut report); assert_eq!(texts(&report), ["its print layouts' map grids' settings that don't read, drawn as RustGIS's (1)"]); diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index bd89d7ad08..26bb72341d 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -458,12 +458,17 @@ are noted; one QGIS hasn't sized yet is given room for a row a layer, and one of page shows its page's first map, noted. One on a page without a map is left out, noted. A map item's first grid shown becomes its frame's grid: in degrees a graticule, else a measured grid in its coordinate system, with its step (a step in millimetres or centimetres on the page as map -units at the map's scale), lines, ticks inside the map and their length, line colour and width, -and its annotations' sides, direction, format and size; a grid of no step, which QGIS draws -nothing of, isn't. Further grids, zebra, line border and nautical frames, crosses and markers -(drawn as lines), ticks or annotations outside the map (drawn inside), offsets, annotations' own -fonts, decimals and formats RustGIS writes otherwise, steps finer than RustGIS draws, a step fitted -to the page and a coordinate system that doesn't read are noted. Labels' and +units at the map's scale when the grid is in its map's coordinate system, else RustGIS's own), +lines, ticks inside the map and their length, line colour and width, and its annotations' sides +(following a map turned a quarter), direction, format and size. A grid with no step across or up, +unless fitted to the page, draws nothing in QGIS and isn't read: the next grid shown is taken +instead. Further grids, zebra, line border and nautical frames, crosses and markers (drawn as +lines), ticks or annotations outside the map (drawn inside), offsets, different steps across and +up, a step on the page (drawn at round map coordinates and labelled with them), annotations' own +fonts, decimals and formats RustGIS writes otherwise, a side of latitudes or longitudes only on a +map turned other than a quarter or half turn, steps finer than RustGIS draws (or unchecked, when +the map's extent doesn't convert to the grid's coordinate system), a step fitted to the page and a +coordinate system that doesn't read are 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: tables, HTML and other items, 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 From edbc4a2d3bb844818e0058f67d39edf70a122663 Mon Sep 17 00:00:00 2001 From: strebdom Date: Wed, 2 Dec 2026 17:30:54 +0100 Subject: [PATCH 3/4] fix(map): QGIS map grids' systems compared by where they put the map, and sides of one kind on askew lines said - The grid's and its map's systems are the same when they put the map's extent in the same place, however each is spelled: a page step converts at the map's scale. - A side set to latitudes or longitudes only, on a map whose edges don't run along the grid's lines (a graticule on a conic map, a measured grid turned from its map's system), shows both kinds: said. --- crates/map/src/qgis/layout/grid.rs | 81 ++++++++++++++++++-- crates/map/src/qgis/layout_grid_tests.rs | 94 ++++++++++++++++++++++++ docs/user-guide/workspace.md | 9 ++- 3 files changed, 174 insertions(+), 10 deletions(-) diff --git a/crates/map/src/qgis/layout/grid.rs b/crates/map/src/qgis/layout/grid.rs index 458216d03e..36a2e90117 100644 --- a/crates/map/src/qgis/layout/grid.rs +++ b/crates/map/src/qgis/layout/grid.rs @@ -37,6 +37,7 @@ pub(super) struct Counts { unchecked: usize, paper: usize, kinds: usize, + askew: usize, odd: usize, /// What reading its labels' size noted. notes: Report, @@ -95,6 +96,10 @@ impl Counts { ), (self.unchecked, "map grids whose map's extent doesn't convert to their coordinate system, how fine they draw unchecked"), (self.kinds, "map grids' annotations on a turned map's sides set to latitudes or longitudes only, showing both"), + ( + self.askew, + "map grids' annotations on sides set to latitudes or longitudes only, on a map their lines cross askew, showing both kinds on the sides they cross", + ), (self.odd, "map grids' settings that don't read, drawn as RustGIS's"), ]; for (n, what) in approximated { @@ -157,8 +162,10 @@ fn read_grid(g: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option (own.clone(), Some(c)), None => (map_crs.map(str::to_string), map_read), }; - // Its map's own when it names none, or the same: a step on the page converts to its units. - let same_system = own_read.is_none() || own.as_deref() == map_crs; + // Its map's own when it names none, or the same system however each spells it (one putting + // the map's extent where the other does): a step on the page converts to its units. + let same_system = + own_read.is_none() || own_read == map_read || matches!((own_read, map_read), (Some(o), Some(m)) if same_at(extent, m, o)); // A system that doesn't read (or none at all) is taken from the extent: degrees when it fits // the Earth's. let in_degrees = match crs { @@ -176,6 +183,15 @@ fn read_grid(g: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option !m.is_geographic() && !aligned(extent, m, None), + (GridKind::Measured, Some(m)) => !same_system && !aligned(extent, m, crs), + (_, None) => false, + }; // Its step: in its system's units (0), or in millimetres (1) or centimetres (2) on the page, // converted when its system is its map's; fitted to the page (3), RustGIS's own. @@ -315,30 +331,34 @@ fn read_grid(g: Node, map_crs: Option<&str>, extent: [f64; 4], per_mm: Option = [("left", grid.edges.left), ("right", grid.edges.right), ("bottom", grid.edges.bottom), ("top", grid.edges.top)] @@ -466,6 +486,55 @@ pub(super) fn readable_crs(node: Node) -> Option { named.iter().find(|c| c.chars().count() <= MAX_GRID_CRS && Crs::parse(c).is_ok()).or(named.first()).map(|c| c.to_string()) } +/// Whether `extent`'s edges (in `from`'s system) run along `to`'s lines (longitude/latitude when +/// none): its left and right edges each at one x, its top and bottom each at one y, within a +/// millionth of its size there. One that doesn't convert is taken as aligned, not to say a loss +/// that can't be told. +fn aligned(extent: [f64; 4], from: rustgis_data::raster::Crs, to: Option) -> bool { + let Ok(from) = from.transformer() else { return true }; + let to = match to.map(|c| c.transformer()) { + Some(Ok(t)) => Some(t), + Some(Err(_)) => return true, + None => None, + }; + let [x0, y0, x1, y1] = extent; + let (xm, ym) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); + let at = |x: f64, y: f64| { + from.to_lonlat(rustgis_geom::Coord::new(x, y)).and_then(|ll| match &to { + Some(t) => t.from_lonlat(ll), + None => Some(ll), + }) + }; + let points: Option> = [(x0, y0), (x0, ym), (x0, y1), (x1, y0), (x1, ym), (x1, y1), (xm, y0), (xm, y1)] + .into_iter() + .map(|(x, y)| at(x, y).filter(|c| c.x.is_finite() && c.y.is_finite())) + .collect(); + let Some([l0, lm, l1, r0, rm, r1, b, t]) = points.as_deref().and_then(|p| <[_; 8]>::try_from(p).ok()) else { return true }; + let size = (r0.x - l0.x).abs().max((l1.y - l0.y).abs()); + let near = |a: f64, b: f64| (a - b).abs() <= size * 1e-6; + near(l0.x, lm.x) + && near(l0.x, l1.x) + && near(r0.x, rm.x) + && near(r0.x, r1.x) + && near(l0.y, b.y) + && near(l0.y, r0.y) + && near(l1.y, t.y) + && near(l1.y, r1.y) +} + +/// Whether `a` and `b` put `extent` (in `a`'s system) in the same place: its corners and centre +/// converted from `a` to `b` land within a millionth of its size of where they are. +fn same_at(extent: [f64; 4], a: rustgis_data::raster::Crs, b: rustgis_data::raster::Crs) -> bool { + let (Ok(a), Ok(b)) = (a.transformer(), b.transformer()) else { return false }; + let [x0, y0, x1, y1] = extent; + let tolerance = (x1 - x0).abs().max((y1 - y0).abs()) * 1e-6; + [(x0, y0), (x1, y0), (x0, y1), (x1, y1), ((x0 + x1) / 2.0, (y0 + y1) / 2.0)].into_iter().all(|(x, y)| { + a.to_lonlat(rustgis_geom::Coord::new(x, y)) + .and_then(|ll| b.from_lonlat(ll)) + .is_some_and(|c| (c.x - x).abs() <= tolerance && (c.y - y).abs() <= tolerance) + }) +} + /// `extent` in `from`'s system as an extent in `to`'s (longitude/latitude when none), through /// points along its edges; none when either doesn't convert. fn extent_in(extent: [f64; 4], from: Option, to: Option) -> Option<[f64; 4]> { diff --git a/crates/map/src/qgis/layout_grid_tests.rs b/crates/map/src/qgis/layout_grid_tests.rs index 4fa339e0ed..0cfd9400fb 100644 --- a/crates/map/src/qgis/layout_grid_tests.rs +++ b/crates/map/src/qgis/layout_grid_tests.rs @@ -605,6 +605,100 @@ fn annotation_sides_on_a_turned_map() { assert!(!texts(&report).contains(&kinds), "{:?}", texts(&report)); } +/// The same system spelled by its code and by its PROJ string is one: a page step converts. +#[test] +fn a_page_step_converts_in_its_maps_system_however_spelled() { + let utm = "+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs"; + let by_code = r#"EPSG:32632"#; + let spelled = r#"USER:100001+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +type=crs"#; + let extent = [470000.0, 5250000.0, 471700.0, 5251275.0]; + let in_map = |own: &str, report: &mut Report| { + let g = grid(r#"unit="1" intervalX="15" intervalY="15""#, &format!("{}{TEXT}{own}", line("0.3", "MM", "solid"))); + let text = project_at("EPSG:2056", extent, &g) + .replace("EPSG:2056", &format!("USER:100002{utm}")); + grid_of(&read(&text, report)).unwrap().step + }; + for own in [by_code, spelled] { + let mut report = Report::default(); + assert!((in_map(own, &mut report) - 170.0).abs() < 1e-9, "{own}"); + assert!(!texts(&report).iter().any(|t| t.contains("fitted to the page")), "{own}: {:?}", texts(&report)); + } + // Another system is still another. + let mut report = Report::default(); + assert_eq!(in_map(r#"EPSG:32631"#, &mut report), 0.0); + assert!(texts(&report).iter().any(|t| t.contains("fitted to the page")), "{:?}", texts(&report)); +} + +/// Lines askew across the frame (a graticule on a projected map, a measured grid in another +/// system) may cross a side of the other kind: a side of one kind only is said; all sides of all, +/// or lines straight across, nothing. +#[test] +fn sides_of_one_kind_on_askew_lines_are_said() { + let askew = "map grids' annotations on sides set to latitudes or longitudes only, on a map their lines cross askew, showing both kinds on the sides they cross"; + let wgs84 = r#"EPSG:4326"#; + let utm = r#"EPSG:32632"#; + let sides = r#"topAnnotationDisplay="2" leftAnnotationDisplay="1" annotationFormat="3" annotationPrecision="2" intervalX="0.01" intervalY="0.01""#; + let with = |attrs: &str, srs: &str| grid(attrs, &format!("{}{TEXT}{srs}", line("0.3", "MM", "solid"))); + for (crs, extent, g, said) in [ + ("EPSG:2056", [2696300.0, 1261200.0, 2698000.0, 1262475.0], with(sides, wgs84), true), + ( + "EPSG:2056", + [2696300.0, 1261200.0, 2698000.0, 1262475.0], + with(r#"annotationFormat="3" annotationPrecision="2" intervalX="0.01" intervalY="0.01""#, wgs84), + false, + ), + ( + "EPSG:4326", + DEGREES, + with( + r#"topAnnotationDisplay="2" leftAnnotationDisplay="1" annotationFormat="3" annotationPrecision="1" intervalX="0.5" intervalY="0.5""#, + wgs84, + ), + false, + ), + ( + "EPSG:2056", + [2696300.0, 1261200.0, 2698000.0, 1262475.0], + with(r#"topAnnotationDisplay="2" leftAnnotationDisplay="1""#, utm), + true, + ), + ("EPSG:2056", [2696300.0, 1261200.0, 2698000.0, 1262475.0], plain(r#"topAnnotationDisplay="2" leftAnnotationDisplay="1""#), false), + // Mercator's graticules (Web Mercator's, however spelled, the world's) run straight. + ("EPSG:3857", [890000.0, 5940000.0, 1060000.0, 6100000.0], with(sides, wgs84), false), + ("EPSG:3395", [890000.0, 5900000.0, 1060000.0, 6060000.0], with(sides, wgs84), false), + // The map's own system spelled otherwise is no other. + ( + "EPSG:32632", + [470000.0, 5250000.0, 471700.0, 5251275.0], + with( + r#"topAnnotationDisplay="2" leftAnnotationDisplay="1""#, + r#"USER:100001+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs"#, + ), + false, + ), + ] { + let mut report = Report::default(); + let p = read(&project_at(crs, extent, &g), &mut report); + // Labelled as straight lines are, by the side's kind. + assert_eq!(grid_of(&p).unwrap().edges, GridEdges { top: true, bottom: true, left: true, right: true }); + assert_eq!(texts(&report).iter().any(|t| t.contains(askew)), said, "{crs} {g}: {:?}", texts(&report)); + } +} + +/// A Web Mercator map spelled as its PROJ string draws a graticule straight: nothing said. +#[test] +fn a_graticule_on_a_mercator_map_spelled_as_proj_is_straight() { + let wgs84 = r#"EPSG:4326"#; + let sides = r#"topAnnotationDisplay="2" leftAnnotationDisplay="1" annotationFormat="3" annotationPrecision="2" intervalX="0.01" intervalY="0.01""#; + let g = grid(sides, &format!("{}{TEXT}{wgs84}", line("0.3", "MM", "solid"))); + let merc = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +no_defs"; + let text = project_at("EPSG:2056", [890000.0, 5940000.0, 1060000.0, 6100000.0], &g) + .replace("EPSG:2056", &format!("USER:100003{merc}")); + let mut report = Report::default(); + read(&text, &mut report); + assert!(!texts(&report).iter().any(|t| t.contains("cross askew")), "{:?}", texts(&report)); +} + /// No step up is drawn at the step across, said; a setting past QGIS's is said once, as one /// that doesn't read, and annotations' settings only when it shows them. #[test] diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 26bb72341d..914fae0140 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -466,10 +466,11 @@ instead. Further grids, zebra, line border and nautical frames, crosses and mark lines), ticks or annotations outside the map (drawn inside), offsets, different steps across and up, a step on the page (drawn at round map coordinates and labelled with them), annotations' own fonts, decimals and formats RustGIS writes otherwise, a side of latitudes or longitudes only on a -map turned other than a quarter or half turn, steps finer than RustGIS draws (or unchecked, when -the map's extent doesn't convert to the grid's coordinate system), a step fitted to the page and a -coordinate system that doesn't read are noted. Labels' and -pictures' backgrounds and frames, a map's frame, hidden items and locked ones carry over. What a +map turned other than a quarter or half turn or with grid lines running askew across it, steps +finer than RustGIS draws (or unchecked, when the map's extent doesn't convert to the grid's +coordinate system), a step fitted to the page and a coordinate system that doesn't read are 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: tables, HTML and other items, 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 From d766af1ccfe1643d2d05fc5073c5b316186b46f0 Mon Sep 17 00:00:00 2001 From: strebdom Date: Wed, 2 Dec 2026 17:54:18 +0100 Subject: [PATCH 4/4] fix(map): QGIS map grids of no step keep their frames said, and the askew note says sides left off - A grid of no step either way draws no lines, but QGIS still draws its zebra, line border or nautical frame: counted with the frames left out. - A side of latitudes or longitudes only on askew lines is labelled as if straight: a side kept shows both kinds, one left off neither; the note says so. --- crates/map/src/qgis/layout/grid.rs | 8 +++-- crates/map/src/qgis/layout_grid_tests.rs | 40 +++++++++++++++++++++++- docs/user-guide/workspace.md | 28 ++++++++--------- 3 files changed, 58 insertions(+), 18 deletions(-) diff --git a/crates/map/src/qgis/layout/grid.rs b/crates/map/src/qgis/layout/grid.rs index 36a2e90117..00cc2dd550 100644 --- a/crates/map/src/qgis/layout/grid.rs +++ b/crates/map/src/qgis/layout/grid.rs @@ -98,7 +98,7 @@ impl Counts { (self.kinds, "map grids' annotations on a turned map's sides set to latitudes or longitudes only, showing both"), ( self.askew, - "map grids' annotations on sides set to latitudes or longitudes only, on a map their lines cross askew, showing both kinds on the sides they cross", + "map grids' annotations on sides set to latitudes or longitudes only, on a map their lines cross askew, labelled as if straight: a side kept shows both kinds, one left off neither", ), (self.odd, "map grids' settings that don't read, drawn as RustGIS's"), ]; @@ -130,8 +130,10 @@ pub(super) fn map_grid( if g.attribute("show") == Some("0") { tally.overviews_off += 1; } else if int(g, "unit") != Some(3) && !step("intervalX") && !step("intervalY") { - // A step of none either way (a new grid's) draws nothing in QGIS: nothing to carry - // over. (A step one way only draws that way's lines.) + // A step of none either way (a new grid's) draws no lines in QGIS: nothing to carry + // over. (A step one way only draws that way's lines.) Its zebra or line border frame + // is still drawn, a band along the map's edge: said as left out. + tally.grid.frames += usize::from(matches!(int(g, "gridFrameStyle"), Some(1 | 5..=7))); continue; } else if grid.is_some() { tally.grid.past += 1; diff --git a/crates/map/src/qgis/layout_grid_tests.rs b/crates/map/src/qgis/layout_grid_tests.rs index 0cfd9400fb..e4f7c47b8e 100644 --- a/crates/map/src/qgis/layout_grid_tests.rs +++ b/crates/map/src/qgis/layout_grid_tests.rs @@ -196,6 +196,20 @@ fn a_grid_of_no_step_draws_nothing() { assert!(texts(&report).is_empty(), "{:?}", texts(&report)); } +/// QGIS still draws a zebra or line border frame for a grid of no step: said as left out; one +/// of ticks (drawn at lines it hasn't) isn't. +#[test] +fn a_grid_of_no_step_keeps_its_frame_said() { + let frames = "its print layouts' map grids' zebra, line border and nautical frames (1)"; + for (style, said) in [("1", true), ("5", true), ("6", true), ("7", true), ("0", false), ("2", false)] { + let mut report = Report::default(); + let p = read(&project("EPSG:2056", &plain(&format!(r#"intervalX="0" intervalY="0" gridFrameStyle="{style}""#))), &mut report); + assert_eq!(grid_of(&p), None); + let want: &[&str] = if said { &[frames] } else { &[] }; + assert_eq!(texts(&report), want, "{style}"); + } +} + /// QGIS's plain decimals print no degree sign, and its minutes and seconds are unpadded and /// always written: all said; decimals with a suffix are written alike. #[test] @@ -634,7 +648,7 @@ fn a_page_step_converts_in_its_maps_system_however_spelled() { /// or lines straight across, nothing. #[test] fn sides_of_one_kind_on_askew_lines_are_said() { - let askew = "map grids' annotations on sides set to latitudes or longitudes only, on a map their lines cross askew, showing both kinds on the sides they cross"; + let askew = "map grids' annotations on sides set to latitudes or longitudes only, on a map their lines cross askew, labelled as if straight: a side kept shows both kinds, one left off neither"; let wgs84 = r#"EPSG:4326"#; let utm = r#"EPSG:32632"#; let sides = r#"topAnnotationDisplay="2" leftAnnotationDisplay="1" annotationFormat="3" annotationPrecision="2" intervalX="0.01" intervalY="0.01""#; @@ -685,6 +699,30 @@ fn sides_of_one_kind_on_askew_lines_are_said() { } } +/// On askew lines, a top side of latitudes only is left off, as on straight ones, though parallels +/// cross it: said. +#[test] +fn a_side_left_off_on_askew_lines_is_said() { + let wgs84 = r#"EPSG:4326"#; + let attrs = r#"topAnnotationDisplay="1" annotationFormat="3" annotationPrecision="2" intervalX="0.01" intervalY="0.01""#; + let g = grid(attrs, &format!("{}{TEXT}{wgs84}", line("0.3", "MM", "solid"))); + let mut report = Report::default(); + let p = read(&project_at("EPSG:2056", [2696300.0, 1261200.0, 2698000.0, 1262475.0], &g), &mut report); + assert_eq!(grid_of(&p).unwrap().edges, GridEdges { top: false, bottom: true, left: true, right: true }); + assert!( + texts(&report) + .iter() + .any(|t| t.contains("cross askew, labelled as if straight: a side kept shows both kinds, one left off neither")), + "{:?}", + texts(&report) + ); + // On a map in degrees, its lines straight: nothing said. + let mut report = Report::default(); + let p = read(&project_at("EPSG:4326", DEGREES, &g.replace("0.01", "0.5")), &mut report); + assert_eq!(grid_of(&p).unwrap().edges, GridEdges { top: false, bottom: true, left: true, right: true }); + assert!(!texts(&report).iter().any(|t| t.contains("cross askew")), "{:?}", texts(&report)); +} + /// A Web Mercator map spelled as its PROJ string draws a graticule straight: nothing said. #[test] fn a_graticule_on_a_mercator_map_spelled_as_proj_is_straight() { diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 914fae0140..40b4c48be4 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -461,20 +461,20 @@ its coordinate system, with its step (a step in millimetres or centimetres on th units at the map's scale when the grid is in its map's coordinate system, else RustGIS's own), lines, ticks inside the map and their length, line colour and width, and its annotations' sides (following a map turned a quarter), direction, format and size. A grid with no step across or up, -unless fitted to the page, draws nothing in QGIS and isn't read: the next grid shown is taken -instead. Further grids, zebra, line border and nautical frames, crosses and markers (drawn as -lines), ticks or annotations outside the map (drawn inside), offsets, different steps across and -up, a step on the page (drawn at round map coordinates and labelled with them), annotations' own -fonts, decimals and formats RustGIS writes otherwise, a side of latitudes or longitudes only on a -map turned other than a quarter or half turn or with grid lines running askew across it, steps -finer than RustGIS draws (or unchecked, when the map's extent doesn't convert to the grid's -coordinate system), a step fitted to the page and a coordinate system that doesn't read are 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: tables, HTML and other items, 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. +unless fitted to the page, draws no lines in QGIS and isn't read (a zebra, line border or nautical +frame it has, which QGIS still draws, is noted): the next grid shown is taken instead. Further +grids, zebra, line border and nautical frames, crosses and markers (drawn as lines), ticks or +annotations outside the map (drawn inside), offsets, different steps across and up, a step on the +page (drawn at round map coordinates and labelled with them), annotations' own fonts, decimals and +formats RustGIS writes otherwise, a side of latitudes or longitudes only on a map turned other than +a quarter or half turn or with grid lines running askew across it, steps finer than RustGIS draws +(or unchecked, when the map's extent doesn't convert to the grid's coordinate system), a step +fitted to the page and a coordinate system that doesn't read are 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: tables, HTML and other items, 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. QGIS filter expressions (a layer's filter, label and renderer rules) carry over: those that are SQL (fields compared with values, `LIKE`, `IN`, `IS NULL`, joined by `AND`, `OR` and `NOT`) as