From ccb3f73c66f612a3d9ce1af2aed9ccbd8736c89a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 21 Nov 2026 13:46:46 -0500 Subject: [PATCH 1/8] feat(map, engine): a QGIS raster image marker draws its own image (#2266 part D) The QGIS importer reads a RasterMarker symbol layer as an image marker of its PNG or JPEG instead of a circle in its (absent) colour, on points and along lines. Its image is embedded in the file (base64:) or a file of its own, relative to the project's folder, or in a style to the style's. Each image is read once, before the symbols are converted, through a reader the engine gives the importer, which opens no file itself; an import reads at most 64 MiB of images, those that don't draw counted too. Anchors use the image's own height. What can't be drawn is a circle with a note saying why: no image, a web address, an image kept inside a .qgz, a path relative to a drive or to no folder, a file that doesn't open, isn't a PNG or JPEG or is past 2 MiB of base64. A fixed aspect ratio, a see-through marker and an anchor along a line are noted as approximated. The QGIS corpus gains 13 raster marker styles, a project with each on a layer, and their two images, written by QGIS 4.2.3 through generate.py. --- ATTRIBUTION.md | 2 +- crates/engine/src/cmd/graphics.rs | 30 +- crates/engine/src/cmd/qgis.rs | 73 +- crates/engine/src/tests.rs | 82 +- crates/map/src/qgis/mod.rs | 25 +- crates/map/src/qgis/symbol.rs | 126 +- crates/map/src/qgis/tests.rs | 163 +- crates/map/testdata/qgis/README.md | 6 +- .../testdata/qgis/generated/data/marker.jpg | Bin 0 -> 752 bytes .../testdata/qgis/generated/data/marker.png | Bin 0 -> 133 bytes .../map/testdata/qgis/generated/generate.py | 106 + .../qgis/generated/qgs/raster-markers.qgs | 5378 +++++++++++++++++ .../qml/symbol-raster-marker-along-a-line.qml | 364 ++ ...mbol-raster-marker-anchor-bottom-right.qml | 321 + .../symbol-raster-marker-anchor-top-left.qml | 321 + .../qml/symbol-raster-marker-embedded.qml | 321 + ...ymbol-raster-marker-fixed-aspect-ratio.qml | 321 + .../qml/symbol-raster-marker-jpeg.qml | 321 + .../qml/symbol-raster-marker-offset.qml | 321 + .../qml/symbol-raster-marker-opacity.qml | 321 + .../qml/symbol-raster-marker-png.qml | 321 + .../qml/symbol-raster-marker-rotated.qml | 321 + .../symbol-raster-marker-size-map-units.qml | 321 + .../qml/symbol-raster-marker-size-pixels.qml | 321 + .../qml/symbol-raster-marker-size-points.qml | 321 + docs/user-guide/workspace.md | 9 +- 26 files changed, 10166 insertions(+), 50 deletions(-) create mode 100644 crates/map/testdata/qgis/generated/data/marker.jpg create mode 100644 crates/map/testdata/qgis/generated/data/marker.png create mode 100644 crates/map/testdata/qgis/generated/qgs/raster-markers.qgs create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-along-a-line.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-anchor-bottom-right.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-anchor-top-left.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-embedded.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-fixed-aspect-ratio.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-jpeg.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-offset.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-opacity.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-png.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-rotated.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-size-map-units.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-size-pixels.qml create mode 100644 crates/map/testdata/qgis/generated/qml/symbol-raster-marker-size-points.qml diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 1249ddb374..4d39a0f44b 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -26,7 +26,7 @@ of use. | Sample data (`countries`, `cities`, `rivers`, `lakes` GeoJSON), embedded at build time from [rustgis-assets](https://github.com/opengeos/rustgis-assets/tree/main/data) | Natural Earth 1:110m, attributes trimmed | Public domain | | Worldviews (`countries_.geojson` and `original/countries_.geojson.gz` on [source.coop](https://source.coop/opengeos/data/rustgis/worldviews)), downloaded by the app when one is chosen, not part of it | Natural Earth's Admin 0 Countries (1:10m) and its points of view, with the sample countries' attributes by `scripts/worldviews.py` in [rustgis-assets](https://github.com/opengeos/rustgis-assets): simplified to 1:110m density, or at their original detail | Public domain | | QGIS screenshot (`qgis-world-atlas.webp` in [rustgis-assets](https://github.com/opengeos/rustgis-assets/tree/main/images)), on the [RustGIS and QGIS](docs/comparison/qgis.md) page | Taken by the RustGIS project: [QGIS](https://qgis.org) 4.2 showing the Natural Earth sample data above | QGIS is GPL-2.0-or-later; the data is public domain | -| QGIS test corpus (`crates/map/testdata/qgis/generated/`: styles, projects and their sample data) | Dominik Strebel ([@pick2510](https://github.com/pick2510)) for the RustGIS project: written by [QGIS](https://qgis.org) 4.2.3 through its API, from `generate.py` there; the data is made up | Apache-2.0 | +| QGIS test corpus (`crates/map/testdata/qgis/generated/`: styles, projects and their sample data) | Dominik Strebel ([@pick2510](https://github.com/pick2510)) for the RustGIS project: written by [QGIS](https://qgis.org) 4.2.3 through its API, from `generate.py` there; the raster image marker styles and their two images (`marker.png`, `marker.jpg`) added the same way by the RustGIS project; the data is made up | Apache-2.0 | | CFF test font (`crates/render/testdata/test-cff.otf`), read only by the PDF font tests | The RustGIS project: generated for this test with [fontTools](https://github.com/fonttools/fonttools) by the script in `crates/render/testdata/README.md`; its glyphs are made up | Apache-2.0 | | JAXA Earth catalog test copy (`crates/tiles/tests/data/jaxa_catalog.v2.md`), read only by tests | JAXA: the [JAXA Earth API](https://data.earth.jaxa.jp/) dataset catalog ([catalog.v2.md](https://data.earth.jaxa.jp/app/mcp/catalog.v2.md)), copied on 2026-11-08 | JAXA's [terms of use](https://earth.jaxa.jp/en/data/policy/): free to use and redistribute, with credit to JAXA | | CityGML test mesh (`crates/data/tests/data/rocking-chair.gml`), read only by tests | 97 faces of the rocking chair in OGC's CityGML 3.0 sample `Building_LOD3-EPSG25832.gml` ([CityGML-3.0Encodings](https://github.com/opengeospatial/CityGML-3.0Encodings/blob/master/Moved_to_CITYGML-3.0Encoding_CityGML/Examples/Examples-from-CityGML-2.0/building/CityGMLv3/Building_LOD3-EPSG25832.gml)), copyright (c) 2013 3DXScape, copied on 2026-11-12 and rewritten as a CityGML 2.0 object, coordinates unchanged | MIT | diff --git a/crates/engine/src/cmd/graphics.rs b/crates/engine/src/cmd/graphics.rs index d7a6d8b2db..23561b43f0 100644 --- a/crates/engine/src/cmd/graphics.rs +++ b/crates/engine/src/cmd/graphics.rs @@ -267,18 +267,7 @@ fn color(p: &Value, k: &str) -> Result, String> { pub(crate) fn picture(p: &Value) -> Result { let b64 = match (ps(p, "image"), ps(p, "path")) { (Some(b), _) => b.trim().to_string(), - (None, Some(path)) => { - use std::io::Read; - // Read at most one byte past the limit, so a huge or endless file is refused. - let mut bytes = Vec::new(); - let file = rustgis_data::provenance::open(path).map_err(|e| format!("{path}: {e}"))?; - (&file).take(MAX_PICTURE as u64 + 1).read_to_end(&mut bytes).map_err(|e| format!("{path}: {e}"))?; - if bytes.len() > MAX_PICTURE { - return Err("the picture is too large".into()); - } - rustgis_data::provenance::buffer(std::path::Path::new(path), &file, &bytes); - base64::engine::general_purpose::STANDARD.encode(bytes) - } + (None, Some(path)) => base64::engine::general_purpose::STANDARD.encode(read_picture_file(path, MAX_PICTURE)?), (None, None) => return Err("a picture needs an image or a path".into()), }; if b64.len() > MAX_PICTURE / 3 * 4 + 4 { @@ -290,6 +279,23 @@ pub(crate) fn picture(p: &Value) -> Result { Ok(b64) } +/// What [`read_picture_file`] says of a file past its limit. +pub(crate) const TOO_LARGE: &str = "the picture is too large"; + +/// A picture file's bytes, at most `max` (refused past it: read at most one byte more, so a huge +/// or endless file is too), its provenance kept. +pub(crate) fn read_picture_file(path: &str, max: usize) -> Result, String> { + use std::io::Read; + let mut bytes = Vec::new(); + let file = rustgis_data::provenance::open(path).map_err(|e| format!("{path}: {e}"))?; + (&file).take(max as u64 + 1).read_to_end(&mut bytes).map_err(|e| format!("{path}: {e}"))?; + if bytes.len() > max { + return Err(TOO_LARGE.into()); + } + rustgis_data::provenance::buffer(std::path::Path::new(path), &file, &bytes); + Ok(bytes) +} + fn add(s: &mut Session, p: &Value) -> CmdResult { let shape = ps(p, "shape").ok_or("shape is required")?.trim().to_ascii_lowercase(); if !graphics::SHAPES.contains(&shape.as_str()) { diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 6b5803743e..2cde21d678 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -48,6 +48,66 @@ fn qgis_text(p: &Value) -> Result { String::from_utf8(bytes).map_err(|_| "not a QGIS file (it isn't text)".to_string()) } +/// The folder of the file `path` names (`.` for a file named without one), which its relative +/// paths start from. +fn file_dir(p: &Value) -> Option { + ps(p, "path").and_then(|path| std::path::Path::new(path).parent()).map(|d| match d.to_string_lossy() { + d if d.is_empty() => ".".to_string(), + d => d.into_owned(), + }) +} + +/// The most bytes of base64 of raster marker images one import reads: what a run keeps +/// (`MAX_PICTURES_BYTES`), counting those that turn out not to draw too, so a project naming many +/// files that aren't images reads no more than one of images (in tests, a few small images'). +const MARKER_READ_BYTES: usize = if cfg!(test) { 1 << 10 } else { rustgis_map::symbology::MAX_PICTURES_BYTES }; + +/// The importer's reader of raster image markers' images ([`qgis::ReadImage`]): [`marker_image`] +/// within [`MARKER_READ_BYTES`] for the import. +fn marker_images() -> impl FnMut(&str) -> Result<(String, f32), &'static str> { + let mut read = 0; + move |source| { + if read >= MARKER_READ_BYTES { + return Err("past the bytes of images an import reads"); + } + marker_image(source, &mut read) + } +} + +/// Reads a raster image marker's image for the importer: its `base64:` text, or its file's, +/// within what a picture marker keeps (`MAX_PICTURE_BYTES` of base64), checked as `layer.marker` +/// checks an image; with its height over its width. Its base64's length is added to `read`. +fn marker_image(source: &str, read: &mut usize) -> Result<(String, f32), &'static str> { + use base64::Engine; + use rustgis_map::symbology::MAX_PICTURE_BYTES; + const TOO_LARGE: &str = "whose image is past 2 MiB of base64"; + let b64 = match source.strip_prefix("base64:") { + Some(b64) => b64.trim().to_string(), + // Base64 is 4 characters for 3 bytes. + None => match super::graphics::read_picture_file(source, MAX_PICTURE_BYTES / 4 * 3) { + Ok(bytes) => base64::engine::general_purpose::STANDARD.encode(bytes), + Err(e) if e == super::graphics::TOO_LARGE => return Err(TOO_LARGE), + Err(_) => return Err("whose image file doesn't open"), + }, + }; + *read += b64.len(); + if b64.is_empty() { + return Err("with no image"); + } + if b64.len() > MAX_PICTURE_BYTES { + return Err(TOO_LARGE); + } + // As `layer.marker` checks one: one kept already decodes into the drawing's cache. + let readable = match rustgis_map::Picture::kept(&b64) { + Some(kept) => rustgis_render::picture_marker_draws(kept), + None => rustgis_render::picture_marker_readable(&b64), + }; + match rustgis_render::picture_size(&b64) { + Some((w, h)) if readable && w > 0 => Ok((b64, h as f32 / w as f32)), + _ => Err("whose image isn't a PNG or JPEG RustGIS reads"), + } +} + /// The most bytes of a QGIS file read (a `.qgz` can carry data files beside its project). const MAX_FILE: u64 = 256 << 20; /// The most bytes of a project's or style's XML parsed: its tree is several times larger than @@ -78,14 +138,9 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { let text = qgis_text(p)?; // The folder relative paths start from: `dir` (a blank one is none, so they don't start // from the working directory), else the file's own (`.` for a file named without one). - let dir = ps(p, "dir").filter(|d| !d.trim().is_empty()).map(str::to_string).or_else(|| { - ps(p, "path").and_then(|path| std::path::Path::new(path).parent()).map(|d| match d.to_string_lossy() { - d if d.is_empty() => ".".to_string(), - d => d.into_owned(), - }) - }); + let dir = ps(p, "dir").filter(|d| !d.trim().is_empty()).map(str::to_string).or_else(|| file_dir(p)); let mut report = Report::default(); - let project = qgis::read_project(&text, dir.as_deref().unwrap_or_default(), &mut report)?; + let project = qgis::read_project(&text, dir.as_deref().unwrap_or_default(), &mut marker_images(), &mut report)?; // A map of its own, named as the project. let name = if project.title.is_empty() { "QGIS project" } else { project.title.as_str() }; s.run_part("map.new", &json!({"name": name}))?; @@ -1936,7 +1991,9 @@ fn import_style(s: &mut Session, p: &Value) -> CmdResult { let id = s.layer_id(p)?; let name = s.map().layer(id).map(|l| l.name.clone()).ok_or("no such layer")?; let mut report = Report::default(); - let style = qgis::read_style(&text, &name, &mut report)?; + // Its raster image markers' relative files start from the style file's folder. + let dir = file_dir(p).unwrap_or_default(); + let style = qgis::read_style(&text, &name, &dir, &mut marker_images(), &mut report)?; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; if l.raster.is_some() { // A style that doesn't fit leaves the raster as it was, its opacity and scale range too. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 45548b2f8f..5063f9d715 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2905,6 +2905,86 @@ fn qgis_annotation_layers_import_as_graphics_layers() { assert_eq!(texts, 8, "the texts come in all the same"); } +/// A QGIS style's raster image markers draw their PNG or JPEG file, read from the style's folder; +/// one that isn't a PNG or JPEG, doesn't open or is past what a marker keeps is a circle, noted. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn qgis_raster_image_markers_read_their_files_from_the_style_folder() { + use base64::Engine; + use rustgis_map::{Marker, Picture}; + let dir = std::env::temp_dir().join(format!("rustgis-qgis-raster-markers-{}", std::process::id())); + std::fs::create_dir_all(dir.join("pins")).unwrap(); + let image = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + image.save(dir.join("pins/pin.png")).unwrap(); + image.save(dir.join("pins/pin.jpg")).unwrap(); + image.save(dir.join("pins/pin.gif")).unwrap(); + // Past the 2 MiB of base64 a marker keeps (1.5 MiB of file); its start a PNG's. + let mut big = std::fs::read(dir.join("pins/pin.png")).unwrap(); + big.resize(1600 << 10, 0); + std::fs::write(dir.join("pins/big.png"), big).unwrap(); + let qml = |file: &str| { + format!( + r#" + "# + ) + }; + let notes = + |r: &serde_json::Value| r["notes"].as_array().unwrap().iter().map(|n| n["text"].as_str().unwrap().to_string()).collect::>(); + let mut s = world(); + let marker = |s: &Session| s.map().layer_by_name("Cities").unwrap().symbol(0).marker; + for file in ["./pins/pin.png", "pins/pin.jpg"] { + let path = dir.join("pins.qml"); + std::fs::write(&path, qml(file)).unwrap(); + let r = s.run("style.importQgis", &json!({"layer": "Cities", "path": path.to_string_lossy()})).unwrap(); + let b64 = base64::engine::general_purpose::STANDARD.encode(std::fs::read(dir.join(file)).unwrap()); + assert_eq!(marker(&s), Marker::Picture(Picture::new(&b64)), "{file}"); + assert!(notes(&r).is_empty(), "{file}: {:?}", notes(&r)); + } + for (file, note) in [ + ("pins/pin.gif", "raster image markers whose image isn't a PNG or JPEG RustGIS reads, drawn as circles"), + ("pins/gone.png", "raster image markers whose image file doesn't open, drawn as circles"), + ("pins/big.png", "raster image markers whose image is past 2 MiB of base64, drawn as circles"), + ] { + let path = dir.join("pins.qml"); + std::fs::write(&path, qml(file)).unwrap(); + let r = s.run("style.importQgis", &json!({"layer": "Cities", "path": path.to_string_lossy()})).unwrap(); + assert_eq!(marker(&s), Marker::Circle, "{file}"); + assert_eq!(notes(&r), [note], "{file}"); + } + // Embedded in the style, it needs no folder. + let b64 = base64::engine::general_purpose::STANDARD.encode(std::fs::read(dir.join("pins/pin.png")).unwrap()); + let r = s.run("style.importQgis", &json!({"layer": "Cities", "text": qml(&format!("base64:{b64}"))})).unwrap(); + assert_eq!(marker(&s), Marker::Picture(Picture::new(&b64))); + assert!(notes(&r).is_empty(), "{:?}", notes(&r)); + // An import reads at most so many bytes of images (1 KiB in tests), those that don't draw too: + // of three of 600 characters that aren't images, the third isn't read. + let junk = |c: char| { + format!( + r#""#, + c.to_string().repeat(600) + ) + }; + let three = format!( + r#"{}{}{}"#, + junk('A'), + junk('B'), + junk('C') + ); + let r = s.run("style.importQgis", &json!({"layer": "Cities", "text": three})).unwrap(); + let mut said: Vec<(String, u64)> = + r["notes"].as_array().unwrap().iter().map(|n| (n["text"].as_str().unwrap().to_string(), n["count"].as_u64().unwrap())).collect(); + said.sort(); + assert_eq!( + said, + [ + ("raster image markers past the bytes of images an import reads, drawn as circles".to_string(), 1), + ("raster image markers whose image isn't a PNG or JPEG RustGIS reads, drawn as circles".to_string(), 2), + ] + ); + std::fs::remove_dir_all(&dir).ok(); +} + /// Pictures are charged to an import's budget (1 KiB in tests) only once placed: pictures that /// don't take to longitude and latitude leave it whole, and those past it are left out, noted. #[test] @@ -4773,7 +4853,7 @@ fn a_qgis_project_opens_as_a_map_and_a_qgis_style_styles_a_layer() { wurl=https://wms.example/wms&layers=aWebwms 6"#; let mut report = rustgis_map::qgis::Report::default(); - let project = rustgis_map::qgis::read_project(web, "", &mut report).unwrap(); + let project = rustgis_map::qgis::read_project(web, "", &mut |_| Err("whose image file doesn't open"), &mut report).unwrap(); let mut w = world(); let before = w.active_layer; w.active_layer = w.map().layers.iter().map(|l| l.id).find(|id| Some(*id) != before); diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 730975489d..8a4baee8a9 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -28,7 +28,7 @@ use serde::Serialize; use crate::Rgba; use crate::effects::Blend; -use crate::symbology::{Labeling, LineStroke, MarkerRotation, Renderer}; +use crate::symbology::{Labeling, LineStroke, MarkerRotation, Picture, Renderer}; pub use annotation::{Annotation, MAX_ITEMS as MAX_ANNOTATIONS}; pub use expr::{reads_measure, to_sql}; pub use source::{MAX_MEMORY_FIELDS, Source, VirtualFrom, WebOptions, is_drive_relative, is_relative}; @@ -56,8 +56,20 @@ pub struct Report { /// thousands of different notes, and a repeat is found without going through them all. #[serde(skip)] index: HashMap<(String, NoteKind, String), usize>, + /// Raster image markers' images by their `imageFile`, read before the symbols showing them + /// (`symbol::read_images`): each kept picture with its height over its width, or why it isn't + /// drawn. Carried here because every symbol reader already takes the report; passing them + /// beside it would add a parameter to each reader and to each of their callers. + #[serde(skip)] + images: HashMap>, } +/// Reads a raster image marker's image for the importer, which opens no file itself: given its +/// `base64:` text or its file's path (made absolute from the project's folder), the image as +/// base64 and its height over its width, or why it isn't drawn, as the end of a note's +/// "raster image markers …, drawn as circles" (such as "whose file doesn't open"). +pub type ReadImage<'a> = dyn FnMut(&str) -> Result<(String, f32), &'static str> + 'a; + /// One thing an import couldn't carry over as QGIS has it. #[derive(Clone, Debug, PartialEq, Serialize)] pub struct Note { @@ -493,13 +505,15 @@ pub struct ProjectLayer { } /// Reads a QGIS project. `dir` is the folder the project is in, which its relative paths start -/// from. Notes on what can't be carried over go to `report`. -pub fn read_project(text: &str, dir: &str, report: &mut Report) -> Result { +/// from; `images` reads its raster image markers' images. Notes on what can't be carried over go +/// to `report`. +pub fn read_project(text: &str, dir: &str, images: &mut ReadImage, report: &mut Report) -> Result { let doc = parse(text, "a QGIS project")?; let root = doc.root_element(); if !root.has_tag_name("qgis") { return Err("not a QGIS project (.qgs): its root element isn't ".into()); } + symbol::read_images(root, dir, images, report); // The main map canvas: its view, and (before QGIS 3) the project's coordinate system. let canvas = root.children().find(|c| c.has_tag_name("mapcanvas") && c.attribute("name").is_none_or(|n| n == "theMapCanvas")); let crs = child(root, "projectCrs") @@ -798,12 +812,15 @@ fn resolve_virtual_layers(layers: &mut [ProjectLayer], report: &mut Report) { const MAX_VIRTUAL_CHAIN: usize = 8; /// Reads a QGIS layer style (a `.qml` file's text) for the layer named `layer` (for the notes). -pub fn read_style(text: &str, layer: &str, report: &mut Report) -> Result { +/// `dir` is the folder relative image paths start from (empty: none); `images` reads its raster +/// image markers' images. +pub fn read_style(text: &str, layer: &str, dir: &str, images: &mut ReadImage, report: &mut Report) -> Result { let doc = parse(text, "a QGIS layer style")?; let root = doc.root_element(); if !root.has_tag_name("qgis") { return Err("not a QGIS layer style (.qml): its root element isn't ".into()); } + symbol::read_images(root, dir, images, report); Ok(read_style_node(root, layer, report)) } diff --git a/crates/map/src/qgis/symbol.rs b/crates/map/src/qgis/symbol.rs index 401107ab8a..e5b483f2bb 100644 --- a/crates/map/src/qgis/symbol.rs +++ b/crates/map/src/qgis/symbol.rs @@ -5,13 +5,13 @@ use roxmltree::Node; -use super::{Report, color, data_defined_on, has_effect, points, prop, props, signed_points}; +use super::{ReadImage, Report, color, data_defined_on, has_effect, points, prop, props, signed_points}; use crate::Rgba; use crate::fills::{FillLayer, FillPattern, GradientPoint, GradientShape, Spread, Stop, Stops}; use crate::symbol_by::SymbolBy; use crate::symbology::{ - Dash, Glyph, LineCap, LineJoin, LineMark, LineMarkers, LineStroke, MAX_DASH_STEPS, MAX_STROKES, Marker, MarkerRotation, Placements, - Symbol, + Dash, Glyph, LineCap, LineJoin, LineMark, LineMarkers, LineStroke, MAX_DASH_STEPS, MAX_PICTURES, MAX_PICTURES_BYTES, MAX_STROKES, + Marker, MarkerRotation, Picture, Placements, Symbol, }; /// A symbol layer's settings by name. @@ -156,6 +156,14 @@ pub(super) fn read(sym: Node, reference: Option, turned: bool, layer: &str, if alpha < 1.0 && (by.fill.is_some() || by.stroke.is_some()) { report.approximated(layer, "data-defined colours of a see-through symbol, drawn opaque"); } + // An image marker is drawn at the layer's opacity alone. + let picture = |m: Marker| matches!(m, Marker::Picture(_)); + if alpha < 1.0 + && (picture(out.symbol.marker) + || out.strokes.iter().any(|s| s.markers.is_some_and(|m| matches!(m.mark, LineMark::Marker(k) if picture(k))))) + { + report.approximated(layer, "see-through raster image markers, drawn opaque"); + } out.by = by; out.symbol.fill = fade(out.symbol.fill); out.symbol.stroke = fade(out.symbol.stroke); @@ -708,7 +716,8 @@ fn marker_mark( }) } "FontMarker" => font_char(p, layer, report)?, - "SvgMarker" | "RasterMarker" | "EllipseMarker" | "FilledMarker" => { + "RasterMarker" => raster_image(p, layer, report).map_or(Marker::Circle, |(picture, _)| Marker::Picture(picture)), + "SvgMarker" | "EllipseMarker" | "FilledMarker" => { report.approximated(layer, format!("{} markers, drawn as circles in their colour", marker_name(class))); Marker::Circle } @@ -720,6 +729,9 @@ fn marker_mark( if class == "FontMarker" && anchored(p) { report.approximated(layer, "font markers anchored off their centre, drawn centred"); } + if matches!(shape, Marker::Picture(_)) && anchored(p) { + report.approximated(layer, "raster image markers along lines anchored off their centre, drawn centred"); + } let fill = prop(p, "color").and_then(color).unwrap_or(Rgba::new(0, 0, 0, 0)); let outline = if prop(p, "outline_style") == Some("no") { None } else { prop(p, "outline_color").and_then(color) }; let width = if outline.is_some() { size(p, "outline_width", reference, layer, report).unwrap_or(0.0) } else { 0.0 }; @@ -795,6 +807,8 @@ fn marker(layers: &[(Node, Props)], reference: Option, still: bool, layer: let fill = prop(p, "color").and_then(color); let outline = prop(p, "outline_color").and_then(color); let sz = size(p, "size", reference, layer, report).unwrap_or(2.0 * 96.0 / 25.4); + // Its height over its width: an image's own, else a shape's square. + let mut aspect = 1.0; let shape = match class { "SimpleMarker" => { let name = prop(p, "name").unwrap_or("circle"); @@ -807,7 +821,14 @@ fn marker(layers: &[(Node, Props)], reference: Option, still: bool, layer: Some(m) => m, None => continue, }, - "SvgMarker" | "RasterMarker" | "EllipseMarker" | "FilledMarker" => { + "RasterMarker" => match raster_image(p, layer, report) { + Some((picture, a)) => { + aspect = a; + Marker::Picture(picture) + } + None => Marker::Circle, + }, + "SvgMarker" | "EllipseMarker" | "FilledMarker" => { report.approximated(layer, format!("{} markers, drawn as circles in their colour", marker_name(class))); Marker::Circle } @@ -819,7 +840,7 @@ fn marker(layers: &[(Node, Props)], reference: Option, still: bool, layer: let fill = fill.unwrap_or(Rgba::new(0, 0, 0, 0)); let width = size(p, "outline_width", reference, layer, report).unwrap_or(0.0); let angle = prop(p, "angle").and_then(|a| a.trim().parse::().ok()).filter(|a| a.is_finite()).unwrap_or(0.0); - let (x, y) = point_offset(p, sz, reference, layer, report); + let (x, y) = point_offset(p, (sz, sz * aspect), reference, layer, report); let drawn_outline = outline.filter(|_| prop(p, "outline_style") != Some("no") && width > 0.0); marks.push(LineStroke { color: Some(fill), @@ -856,11 +877,86 @@ fn marker(layers: &[(Node, Props)], reference: Option, still: bool, layer: Converted { symbol, strokes, rotation: None, by: SymbolBy::default(), fills: Vec::new() } } +/// Reads the images of the raster image markers under `root` (a project or a style), each +/// `imageFile` once, into the report for [`raster_image`]: a `base64:` one as it is, a file's +/// through `read` (relative to `dir`). One at a web address isn't fetched, nor one kept inside a +/// `.qgz` (`attachment:`); one relative to no folder (or to a drive's working folder) isn't looked +/// for, and those past the pictures a run keeps ([`MAX_PICTURES`], +/// [`MAX_PICTURES_BYTES`]) aren't read. An image is kept when read, before its symbol is: one +/// in a part of the project the import then leaves out stays kept for the run, within those +/// bounds. +pub(super) fn read_images(root: Node, dir: &str, read: &mut ReadImage, report: &mut Report) { + let mut bytes = 0; + let rasters = root.descendants().filter(|n| n.has_tag_name("layer") && n.attribute("class") == Some("RasterMarker")); + for l in rasters.filter(|l| l.attribute("enabled") != Some("0")) { + let p = props(l); + let Some(file) = prop(&p, "imageFile").map(str::trim).filter(|f| !f.is_empty()) else { continue }; + if report.images.contains_key(file) || report.images.len() >= MAX_PICTURES || bytes >= MAX_PICTURES_BYTES { + continue; + } + let got = if file.starts_with("base64:") { + read(file) + } else if file.starts_with("attachment:") { + Err("whose image is kept inside the .qgz project, which RustGIS doesn't read it from") + } else if file.contains("://") { + Err("whose image is at a web address, which RustGIS doesn't fetch") + } else if super::is_drive_relative(file) { + Err("whose image file is relative to a drive's working folder, which no project folder tells") + } else if super::is_relative(file) && dir.is_empty() { + Err("whose image file is relative to a folder the import wasn't given") + } else { + read(&super::source::absolute(file, dir)) + }; + let kept = got.map_err(str::to_string).and_then(|(b64, aspect)| { + // Past what a run keeps, it isn't (`Picture::new` gives the default then). + let picture = Picture::new(&b64); + if picture.is_default() || !(aspect.is_finite() && aspect > 0.0) { + return Err("past the images RustGIS keeps".to_string()); + } + bytes += b64.len(); + Ok((picture, aspect)) + }); + report.images.insert(file.to_string(), kept); + } +} + +/// A raster image marker's image (read before the symbols: [`read_images`]) and its height over +/// its width, or `None` (noted, with why) for it to be drawn as a circle. What QGIS draws +/// otherwise than RustGIS is noted: a ratio of its own, see-through. +fn raster_image(p: &[(String, String)], layer: &str, report: &mut Report) -> Option<(Picture, f32)> { + let file = prop(p, "imageFile").map(str::trim).unwrap_or_default(); + let why = match report.images.get(file) { + _ if file.is_empty() => "with no image".to_string(), + Some(Ok(got)) => { + let got = *got; + // QGIS's `fixedAspectRatio`: 0 keeps the image's own. + let ratio = prop(p, "fixedAspectRatio").and_then(|r| r.trim().parse::().ok()).filter(|r| r.is_finite() && *r > 0.0); + if ratio.is_some_and(|r| (r - got.1).abs() > 1e-3 * got.1) { + report.approximated(layer, "raster image markers of a fixed aspect ratio, drawn in their image's own"); + } + if prop(p, "alpha").and_then(|a| a.trim().parse::().ok()).is_some_and(|a| a < 1.0) { + report.approximated(layer, "see-through raster image markers, drawn opaque"); + } + return Some(got); + } + Some(Err(why)) => why.clone(), + None => "past the images RustGIS keeps".to_string(), + }; + report.approximated(layer, format!("raster image markers {why}, drawn as circles")); + None +} + /// A point marker layer's offset (`offset`, "x,y" in its unit: right and down) in points, its -/// anchor point added: anchored at its left or top edge, a marker of size `size` sits half its -/// size right of or below the point, as QGIS draws it. A font marker's baseline anchor is drawn -/// centred (noted). -fn point_offset(p: &[(String, String)], size: f32, reference: Option, layer: &str, report: &mut Report) -> (f32, f32) { +/// anchor point added: anchored at its left or top edge, a marker `width` wide and `height` tall +/// sits half its width right of or half its height below the point, as QGIS draws it. A font +/// marker's baseline anchor is drawn centred (noted). +fn point_offset( + p: &[(String, String)], + (width, height): (f32, f32), + reference: Option, + layer: &str, + report: &mut Report, +) -> (f32, f32) { let parse = |v: &str| v.trim().parse::().ok().filter(|v| v.is_finite()).unwrap_or(0.0); let (x, y) = prop(p, "offset").and_then(|o| o.split_once(',')).map_or((0.0, 0.0), |(x, y)| (parse(x), parse(y))); let unit = prop(p, "offset_unit").or(prop(p, SYMBOL_UNIT)); @@ -869,15 +965,14 @@ fn point_offset(p: &[(String, String)], size: f32, reference: Option, layer } else { (signed_points(x, unit, reference, layer, report), signed_points(y, unit, reference, layer, report)) }; - let half = size / 2.0; match prop(p, "horizontal_anchor_point").map(str::trim) { - Some("0") => x += half, - Some("2") => x -= half, + Some("0") => x += width / 2.0, + Some("2") => x -= width / 2.0, _ => {} } match prop(p, "vertical_anchor_point").map(str::trim) { - Some("0") => y += half, - Some("2") => y -= half, + Some("0") => y += height / 2.0, + Some("2") => y -= height / 2.0, Some("3") => report.approximated(layer, "markers anchored at their baseline, drawn centred"), _ => {} } @@ -1062,7 +1157,6 @@ fn pattern_name(class: &str) -> &'static str { fn marker_name(class: &str) -> &'static str { match class { "SvgMarker" => "SVG", - "RasterMarker" => "raster image", "EllipseMarker" => "ellipse", _ => "filled", } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 9015273803..72cb58810a 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -4,6 +4,16 @@ use super::*; use crate::layout::TextAlign; use crate::symbology::{Glyph, LabelPlacement, LineCap, LineMark, Marker, Placements}; +/// [`super::read_project`] given no image file (the tests of raster image markers give theirs). +fn read_project(text: &str, dir: &str, report: &mut Report) -> Result { + super::read_project(text, dir, &mut |_| Err("whose image file doesn't open"), report) +} + +/// [`super::read_style`] given no image file and no folder. +fn read_style(text: &str, layer: &str, report: &mut Report) -> Result { + super::read_style(text, layer, "", &mut |_| Err("whose image file doesn't open"), report) +} + const PROJECT: &str = r#" Towns @@ -1078,14 +1088,32 @@ fn every_corpus_file_reads() { }; // Pin the corpus sizes so a regeneration cannot silently drop fixtures. let styles = files("generated/qml", &["qml"]); - assert_eq!(styles.len(), 97, "style corpus changed: {styles:?}"); + assert_eq!(styles.len(), 110, "style corpus changed: {styles:?}"); + // Raster image markers' files are found from the style's folder and the project's. + let mut read = |source: &str| { + use base64::Engine; + let b64 = match source.strip_prefix("base64:") { + Some(b64) => b64.to_string(), + None => base64::engine::general_purpose::STANDARD.encode(std::fs::read(source).map_err(|_| "whose image file doesn't open")?), + }; + Ok((b64, 0.5)) + }; for path in &styles { let text = std::fs::read_to_string(path).unwrap(); + let dir = path.parent().unwrap().to_string_lossy().to_string(); let mut report = Report::default(); - read_style(&text, "layer", &mut report).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + super::read_style(&text, "layer", &dir, &mut read, &mut report).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + if path.to_string_lossy().contains("symbol-raster-marker-") { + assert!( + !report.notes.iter().any(|n| n.text.starts_with("raster image markers whose")), + "{}: {:?}", + path.display(), + report.notes + ); + } } let projects = files("generated/qgs", &["qgs", "qgz"]); - assert_eq!(projects.len(), 36, "project corpus changed: {projects:?}"); + assert_eq!(projects.len(), 37, "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") { @@ -1098,7 +1126,8 @@ fn every_corpus_file_reads() { let text = text.replace("password='secret'", &format!("password='{PASSWORD}'")); let dir = path.parent().unwrap().to_string_lossy().to_string(); let mut report = Report::default(); - let project = read_project(&text, &dir, &mut report).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let project = super::read_project(&text, &dir, &mut read, &mut report).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + assert!(!report.notes.iter().any(|n| n.text.starts_with("raster image markers whose")), "{}: {:?}", path.display(), report.notes); assert!(!project.layers.is_empty(), "{}: no layers", path.display()); // The PostGIS and SQL Server projects' made-up password reaches neither the layers nor the notes. assert!(!format!("{project:?} {report:?}").contains(PASSWORD), "{}: the password came through", path.display()); @@ -1331,6 +1360,132 @@ fn marker_symbols_of_several_layers_carry_over_as_marks_turned_by_their_field() assert!(report.notes.iter().any(|n| n.text.contains("data-defined")), "{:?}", report.notes); } +/// A raster image marker layer showing `file`, 4 mm wide, with `extra` settings. +fn raster_marker(file: &str, extra: &str) -> String { + format!( + r#""# + ) +} + +/// A style of one marker symbol of `layers`, at `alpha`. +fn marker_qml(alpha: &str, layers: &str) -> String { + format!( + r#"{layers}"# + ) +} + +#[test] +fn raster_image_markers_draw_their_image_read_once_from_the_style_folder() { + use crate::symbology::Picture; + let mm = 96.0 / 25.4; + let near = |a: f32, b: f32| (a - b).abs() < 1e-3; + // A file relative to the style's folder; the reader gives the image and its height over width. + let mut asked = Vec::new(); + let mut read = |source: &str| { + asked.push(source.to_string()); + Ok((format!("image of {source}"), 0.5)) + }; + let mut report = Report::default(); + let s = super::read_style(&marker_qml("1", &raster_marker("./pins/a.png", "")), "Pins", "/styles", &mut read, &mut report).unwrap(); + assert_eq!(asked, ["/styles/pins/a.png"]); + let Some(Renderer::Single(sym)) = &s.renderer else { panic!("{:?}", s.renderer) }; + assert_eq!(sym.marker, Marker::Picture(Picture::new("image of /styles/pins/a.png"))); + assert!(near(sym.size, 4.0 * mm), "its width: {}", sym.size); + assert_eq!(s.line_strokes, Some(Vec::new()), "centred and upright, it is the symbol itself"); + assert!(report.notes.is_empty(), "{:?}", report.notes); + + // Two layers of one image read it once, and anchored at their top left they sit half their + // width right of the point and half their height (the image's, not their width) below it. + asked.clear(); + let mut read = |source: &str| { + asked.push(source.to_string()); + Ok((format!("image of {source}"), 0.5)) + }; + let anchored = r#"