From 769a537566be997a40c88145927892d45a647ed1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 19:04:42 -0500 Subject: [PATCH 1/5] feat(map, engine): a QGIS SVG marker draws its own SVG (#2266 part E2a) --- crates/engine/src/cmd/qgis.rs | 10 +- crates/engine/src/tests.rs | 44 ++++++++ crates/map/src/qgis/mod.rs | 20 ++-- crates/map/src/qgis/symbol.rs | 93 +++++++++++------ crates/map/src/qgis/tests.rs | 179 ++++++++++++++++++++++++++++++--- crates/map/src/symbology.rs | 2 +- docs/user-guide/cartography.md | 2 +- docs/user-guide/workspace.md | 10 +- 8 files changed, 297 insertions(+), 63 deletions(-) diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index c811d84af4..12a93e819a 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -63,7 +63,7 @@ fn file_dir(p: &Value) -> Option { /// 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`] +/// The importer's reader of raster image and SVG markers' images ([`qgis::ReadImage`]): [`marker_image`] /// within [`MARKER_READ_BYTES`] for the import. On the import's thread, as the rest of it is /// (`import_project` says why; `import_style` reads on a thread of its own in the desktop app, /// [`style_ahead`]): each read is one file of at most 1.5 MiB, only a regular file is opened (a @@ -84,7 +84,7 @@ fn marker_images() -> impl FnMut(&str) -> Result<(String, f32), &'static str> { } } -/// Reads a raster image marker's image for the importer: its `base64:` text, or its file's, +/// Reads a raster image or SVG marker's image for the importer: its `base64:` text, or its file's, /// within what a picture marker keeps (`symbology::MAX_PICTURE_BYTES` of base64, 2 MiB), checked /// as `layer.marker` checks an image; with its height over its width. Its base64's length is added /// to `read`, or for a file that doesn't read (past the limit, or failing part way) what was read @@ -113,7 +113,7 @@ fn marker_image(source: &str, read: &mut usize) -> Result<(String, f32), &'stati // doesn't open). *read += e.read().div_ceil(3) * 4; return Err(match e { - PictureFileError::Unopened(_) => "whose image file doesn't open", + PictureFileError::Unopened(_) => qgis::IMAGE_UNOPENED, PictureFileError::TooLarge(_) => TOO_LARGE, PictureFileError::Unread(..) => "whose image file fails as it is read", }); @@ -152,7 +152,7 @@ fn read_file(path: &str) -> Result, String> { /// wait for its metadata, as Add Data adds one.) Its work is bounded by the project: at most /// [`qgis::MAX_LAYERS`] layers, each read once by the command that adds it (a file's layers, and /// a virtual layer on one, each read their file), archives added without waiting for their -/// metadata, annotation pictures within [`MAX_PICTURE_BYTES`], raster image markers' images within +/// metadata, annotation pictures within [`MAX_PICTURE_BYTES`], raster image and SVG markers' images within /// [`MARKER_READ_BYTES`] (each file once, at most 1,024 of them, before any layer is added: see /// [`marker_images`]). A local archive's file is looked /// for on this thread (`is_file`), which a slow network share can hold up, and a web service's @@ -2091,7 +2091,7 @@ pub(crate) fn style_ahead(s: &Session, p: &Value) -> Option CmdResult { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e373d11c5c..f32ff01c9b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4304,6 +4304,50 @@ fn qgis_raster_image_markers_read_their_files_from_the_style_folder() { } } +/// A QGIS style's and project's SVG markers draw their file through the importer's one reader, and +/// saving asks for `svg-markers`; one whose colours the style sets is a circle, noted. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn qgis_svg_markers_draw_their_file_and_saving_requires_svg_markers() { + use base64::Engine; + use rustgis_map::{Marker, Picture}; + let dir = std::env::temp_dir().join(format!("rustgis-qgis-svg-markers-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let svg = r##""##; + std::fs::write(dir.join("pin.svg"), svg).unwrap(); + std::fs::write(dir.join("tinted.svg"), svg.replace("#c81e1e", "param(fill) #c81e1e")).unwrap(); + let qml = |file: &str| { + format!( + r#" + "# + ) + }; + let marker = |s: &Session| s.map().layer_by_name("Cities").unwrap().symbol(0).marker; + let notes = + |r: &serde_json::Value| r["notes"].as_array().unwrap().iter().map(|n| n["text"].as_str().unwrap().to_string()).collect::>(); + let b64 = base64::engine::general_purpose::STANDARD.encode(svg); + let path = dir.join("pins.qml"); + // From its file beside the style, and embedded in the text with no folder. + for params in + [json!({"layer": "Cities", "path": path.to_string_lossy()}), json!({"layer": "Cities", "text": qml(&format!("base64:{b64}"))})] + { + std::fs::write(&path, qml("pin.svg")).unwrap(); + let mut s = world(); + let r = s.run("style.importQgis", ¶ms).unwrap(); + assert_eq!(marker(&s), Marker::Picture(Picture::new(&b64)), "{params}"); + assert!(notes(&r).is_empty(), "{:?}", notes(&r)); + assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["picture-markers", "svg-markers"])); + } + std::fs::write(&path, qml("tinted.svg")).unwrap(); + let mut s = world(); + let r = s.run("style.importQgis", &json!({"layer": "Cities", "path": path.to_string_lossy()})).unwrap(); + assert_eq!(marker(&s), Marker::Circle); + assert_eq!(notes(&r), ["SVG markers whose colours the style sets, which RustGIS doesn't apply yet, drawn as circles"]); + let _ = std::fs::remove_dir_all(&dir); +} + /// A QGIS style's file and its raster image markers' images are read on a thread before the /// command lands (#2620): the landing needs neither file, says what the inline import says, can be /// undone, and a style read for a layer that was renamed meanwhile is refused. A cancelled read diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 6252493d72..b2c7df1698 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, Picture, Renderer}; +use crate::symbology::{Labeling, LineStroke, MarkerRotation, Renderer}; pub use annotation::{Annotation, MAX_ITEMS as MAX_ANNOTATIONS}; pub use expr::{reads_measure, to_sql}; use rustgis_data::loss::LossCode; @@ -64,18 +64,22 @@ pub struct Report { /// Where each closing note is in `notes`, kept in step by [`Report::forget`]. #[serde(skip)] closing: HashMap<(NoteKind, Option), 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 + /// Raster image and SVG markers' images by their path (`imageFile`, `name`), read before the + /// symbols showing them (`symbol::read_images`): each kept image, 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>, + images: HashMap>, } -/// Reads a raster image marker's image for the importer, which opens no file itself: given its +/// A [`ReadImage`]'s reason for a file that doesn't open. +pub const IMAGE_UNOPENED: &str = "whose image file doesn't open"; + +/// Reads a raster image or SVG 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"). +/// "raster image markers …, drawn as circles" or "SVG markers …, drawn as circles" (such as +/// [`IMAGE_UNOPENED`]). 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. @@ -569,7 +573,7 @@ pub struct ProjectLayer { } /// Reads a QGIS project. `dir` is the folder the project is in, which its relative paths start -/// from; `images` reads its raster image markers' images. Notes on what can't be carried over go +/// from; `images` reads its raster image and SVG 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")?; diff --git a/crates/map/src/qgis/symbol.rs b/crates/map/src/qgis/symbol.rs index 6746d73436..55476b4380 100644 --- a/crates/map/src/qgis/symbol.rs +++ b/crates/map/src/qgis/symbol.rs @@ -663,7 +663,7 @@ fn along(l: Node, p: &[(String, String)], hash: bool, reference: Option, la let stroke = if hash { hash_mark(class, &sp, p, base, reference, layer, report) } else { - marker_mark(class, &sp, class == "RasterMarker" && name_from_expression(sub), base, reference, layer, report) + marker_mark(class, &sp, image_file_key(class).is_some() && name_from_expression(sub), base, reference, layer, report) }; if let Some(mut st) = stroke { // An image mark is drawn at the layer's opacity alone. @@ -730,8 +730,10 @@ fn marker_mark( }) } "FontMarker" => font_char(p, layer, report)?, - "RasterMarker" => raster_image(p, from_expression, layer, report).map_or(Marker::Circle, |(picture, _)| Marker::Picture(picture)), - "SvgMarker" | "EllipseMarker" | "FilledMarker" => { + "RasterMarker" | "SvgMarker" => { + marker_image(class, p, from_expression, layer, report).map_or(Marker::Circle, |image| Marker::Picture(image.picture)) + } + "EllipseMarker" | "FilledMarker" => { report.approximated(layer, format!("{} markers, drawn as circles in their colour", marker_name(class))); Marker::Circle } @@ -744,7 +746,7 @@ fn marker_mark( 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"); + report.approximated(layer, "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) }; @@ -835,14 +837,14 @@ fn marker(layers: &[(Node, Props)], reference: Option, still: bool, layer: Some(m) => m, None => continue, }, - "RasterMarker" => match raster_image(p, name_from_expression(*l), layer, report) { - Some((picture, a)) => { - aspect = a; - Marker::Picture(picture) + "RasterMarker" | "SvgMarker" => match marker_image(class, p, name_from_expression(*l), layer, report) { + Some(image) => { + aspect = image.aspect; + Marker::Picture(image.picture) } None => Marker::Circle, }, - "SvgMarker" | "EllipseMarker" | "FilledMarker" => { + "EllipseMarker" | "FilledMarker" => { report.approximated(layer, format!("{} markers, drawn as circles in their colour", marker_name(class))); Marker::Circle } @@ -905,7 +907,7 @@ fn network_share(file: &str) -> bool { file.len() > 1 && file.chars().take(2).all(|c| c == '\\' || c == '/') } -/// Reads the images of the raster image markers under `root` (a project or a style), each +/// Reads the images of the raster image and SVG markers under `root` (a project or a style), each /// `imageFile` once (a file once for each spelling of its path from the folder: a leading `./` is /// dropped, so `./a.png` and `a.png` are one), into the report for [`raster_image`]: a `base64:` /// one as it is, a file's through `read` (relative to `dir`; a `file:` address is the file it names). @@ -919,11 +921,11 @@ fn network_share(file: &str) -> bool { pub(super) fn read_images(root: Node, dir: &str, read: &mut ReadImage, report: &mut Report) { let (mut bytes, mut reads) = (0, 0); // A file's image by its path from the folder (`./a.png` and `a.png` are one). - let mut files = std::collections::HashMap::>::new(); - 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 mut files = std::collections::HashMap::>::new(); + let layers = root.descendants().filter(|n| n.has_tag_name("layer") && n.attribute("enabled") != Some("0")); + for (l, key) in layers.filter_map(|l| Some((l, image_file_key(l.attribute("class")?)?))) { let p = props(l); - let Some(file) = prop(&p, "imageFile").map(str::trim).filter(|f| !f.is_empty()) else { continue }; + let Some(file) = prop(&p, key).map(str::trim).filter(|f| !f.is_empty()) else { continue }; if report.images.contains_key(file) { continue; } @@ -988,7 +990,7 @@ pub(super) fn read_images(root: Node, dir: &str, read: &mut ReadImage, report: & return Err("past the images RustGIS keeps".to_string()); } bytes += b64.len(); - Ok((picture, aspect)) + Ok(MarkerImage { picture, aspect, sets_colours: sets_colours(&b64) }) }); if let Ok(Some(path)) = source { files.insert(path, kept.clone()); @@ -999,36 +1001,68 @@ pub(super) fn read_images(root: Node, dir: &str, read: &mut ReadImage, report: & /// The note for image markers drawn opaque where QGIS draws them see-through: once per symbol /// ([`read`]). -const SEE_THROUGH_IMAGES: &str = "see-through raster image markers, drawn opaque"; +const SEE_THROUGH_IMAGES: &str = "see-through image markers, drawn opaque"; + +/// A marker's image as read for the import. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(super) struct MarkerImage { + picture: Picture, + /// Its height over its width. + aspect: f32, + /// Whether it is an SVG leaving colours to the style (`param(fill)` and the like). + sets_colours: bool, +} -/// 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. `from_expression`: its image -/// path is set by a field or an expression. -fn raster_image(p: &[(String, String)], from_expression: bool, layer: &str, report: &mut Report) -> Option<(Picture, f32)> { - let file = prop(p, "imageFile").map(str::trim).unwrap_or_default(); +/// The setting naming a marker layer `class`'s image file; none for one that shows no file. +fn image_file_key(class: &str) -> Option<&'static str> { + match class { + "RasterMarker" => Some("imageFile"), + "SvgMarker" => Some("name"), + _ => None, + } +} + +/// Whether the image `b64` holds QGIS's `param(…)`, written in any letter case. +fn sets_colours(b64: &str) -> bool { + use base64::Engine; + let bytes = base64::engine::general_purpose::STANDARD.decode(b64); + bytes.is_ok_and(|b| b.windows(6).any(|w| w.eq_ignore_ascii_case(b"param("))) +} + +/// The image of a raster image or SVG marker layer `class` (read before the symbols: +/// [`read_images`]), or `None` for one drawn as a circle (noted). +fn marker_image(class: &str, p: &[(String, String)], from_expression: bool, layer: &str, report: &mut Report) -> Option { + let file = image_file_key(class).and_then(|key| prop(p, key)).map(str::trim).unwrap_or_default(); + let svg = class == "SvgMarker"; + let kind = if svg { "SVG markers" } else { "raster image markers" }; let why = match report.images.get(file) { - // QGIS's image path as a field or an expression (`name`) has nothing in `imageFile` to read. + // QGIS's image path as a field or an expression (`name`) has nothing in its setting to read. _ if file.is_empty() && from_expression => { "whose image comes from a field or an expression, which RustGIS doesn't evaluate".to_string() } _ if file.is_empty() => "with no image".to_string(), - Some(Ok(got)) => { - let got = *got; + // Its `param(…)` values aren't set yet, so drawn as it is it would take the wrong colours. + Some(Ok(image)) if svg && image.sets_colours => "whose colours the style sets, which RustGIS doesn't apply yet".to_string(), + Some(Ok(image)) => { + let image = *image; // 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 ratio.is_some_and(|r| (r - image.aspect).abs() > 1e-3 * image.aspect) { + report.approximated(layer, "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_IMAGES); } - return Some(got); + return Some(image); + } + // QGIS names its own library's SVGs relative to that library, which RustGIS doesn't bring. + Some(Err(why)) if svg && why == super::IMAGE_UNOPENED && !file.starts_with("file:") && super::is_relative(file) => { + "whose file isn't beside the project (QGIS's own SVG library isn't part of RustGIS)".to_string() } Some(Err(why)) => why.clone(), None => "past the images an import reads".to_string(), }; - report.approximated(layer, format!("raster image markers {why}, drawn as circles")); + report.approximated(layer, format!("{kind} {why}, drawn as circles")); None } @@ -1247,7 +1281,6 @@ fn pattern_name(class: &str) -> &'static str { fn marker_name(class: &str) -> &'static str { match class { - "SvgMarker" => "SVG", "EllipseMarker" => "ellipse", _ => "filled", } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 9346f1a44c..fc9504e146 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -1136,14 +1136,18 @@ fn every_corpus_file_reads() { report.notes ); } - // Until the importer reads SVG markers (#2266 part E2a), which changes this on purpose. + // SVG markers draw their file; those whose colours the style sets (until #2266 part E2b) and + // QGIS's own library's are circles, and say why. if name.starts_with("symbol-svg-marker-") { - assert!( - report.notes.iter().any(|n| n.text.starts_with("SVG markers, drawn as circles")), - "{}: {:?}", - path.display(), - report.notes - ); + let circles: Vec<&str> = report.notes.iter().map(|n| n.text.as_str()).filter(|n| n.starts_with("SVG markers")).collect(); + let expected: &[&str] = if name.starts_with("symbol-svg-marker-params") { + &[SVG_COLOURS] + } else if name == "symbol-svg-marker-library.qml" { + &[SVG_LIBRARY] + } else { + &[] + }; + assert_eq!(circles, expected, "{}", path.display()); } } let projects = files("generated/qgs", &["qgs", "qgz"]); @@ -1163,6 +1167,12 @@ fn every_corpus_file_reads() { 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()); + if path.file_name().unwrap() == "svg-markers.qgs" { + let mut circles: Vec<&str> = report.notes.iter().map(|n| n.text.as_str()).filter(|n| n.starts_with("SVG markers")).collect(); + circles.sort_unstable(); + circles.dedup(); + assert_eq!(circles, [SVG_COLOURS, SVG_LIBRARY], "{:?}", report.notes); + } // 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()); } @@ -1394,6 +1404,152 @@ 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); } +const SVG_COLOURS: &str = "SVG markers whose colours the style sets, which RustGIS doesn't apply yet, drawn as circles"; +const SVG_LIBRARY: &str = + "SVG markers whose file isn't beside the project (QGIS's own SVG library isn't part of RustGIS), drawn as circles"; + +/// An SVG marker layer showing `file`, 4 mm wide, with `extra` settings. +fn svg_marker(file: &str, extra: &str) -> String { + format!( + r#""# + ) +} + +/// A reader giving every source as an SVG of `body`, half as tall as wide. +fn svg_reader(body: &'static str) -> impl FnMut(&str) -> Result<(String, f32), &'static str> { + use base64::Engine; + move |source| Ok((base64::engine::general_purpose::STANDARD.encode(format!("{body}")), 0.5)) +} + +#[test] +fn svg_markers_draw_their_file_read_once_from_the_style_folder() { + use crate::symbology::Picture; + let picture = |source: &str| Marker::Picture(Picture::new(&svg_reader("")(source).unwrap().0)); + // A file beside the style, and one embedded in it. + for (file, asked_for) in [("./pins/a.svg", "/styles/pins/a.svg"), ("base64:PHN2Zy8+", "base64:PHN2Zy8+")] { + let mut asked = Vec::new(); + let mut svg = svg_reader(""); + let mut read = |source: &str| { + asked.push(source.to_string()); + svg(source) + }; + let mut report = Report::default(); + let twice = format!("{}{}", svg_marker(file, ""), svg_marker(file, "")); + let s = super::read_style(&marker_qml("1", &twice), "Pins", "/styles", &mut read, &mut report).unwrap(); + assert_eq!(asked, [asked_for], "read once"); + let Some(Renderer::Single(sym)) = &s.renderer else { panic!("{:?}", s.renderer) }; + assert_eq!(sym.marker, picture(asked_for)); + assert!((sym.size - 4.0 * 96.0 / 25.4).abs() < 1e-3, "its width: {}", sym.size); + assert!(report.notes.is_empty(), "{:?}", report.notes); + } + + // Along a line, the SVG is the mark. + let line = |sub: &str| { + format!( + r#" + + {sub}"# + ) + }; + let mut report = Report::default(); + let s = super::read_style(&line(&svg_marker("base64:QUJD", "")), "Road", "", &mut svg_reader(""), &mut report).unwrap(); + assert_eq!(s.line_strokes.unwrap()[0].markers.map(|m| m.mark), Some(LineMark::Marker(picture("base64:QUJD")))); + assert!(report.notes.is_empty(), "{:?}", report.notes); + // A path from an expression along a line says so, as a point's does. + let by_expression = |file: &str| { + svg_marker(file, "").replace( + "", + r#""#, + ) + }; + let expression = "SVG markers whose image comes from a field or an expression, which RustGIS doesn't evaluate, drawn as circles"; + for qml in [marker_qml("1", &by_expression("")), line(&by_expression(""))] { + let mut report = Report::default(); + super::read_style(&qml, "Pins", "", &mut svg_reader(""), &mut report).unwrap(); + assert!(report.notes.iter().any(|n| n.text == expression), "{:?}", report.notes); + } + + // The raster marker's notes, said of image markers. + let anchored = r#"