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..34e6be67bd 100644 --- a/crates/engine/src/cmd/graphics.rs +++ b/crates/engine/src/cmd/graphics.rs @@ -268,16 +268,7 @@ 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) + base64::engine::general_purpose::STANDARD.encode(read_picture_file(path, MAX_PICTURE).map_err(PictureFileError::message)?) } (None, None) => return Err("a picture needs an image or a path".into()), }; @@ -290,6 +281,65 @@ pub(crate) fn picture(p: &Value) -> Result { Ok(b64) } +/// Why [`read_picture_file`] gave no picture, with how many of its bytes were read. +pub(crate) enum PictureFileError { + /// It isn't a regular file, or doesn't open: none read. + Unopened(String), + /// Past the limit: one byte more than it was read. + TooLarge(usize), + /// Its read failed after these bytes. + Unread(String, usize), +} + +impl PictureFileError { + /// The bytes read before it failed. + pub(crate) fn read(&self) -> usize { + match self { + Self::Unopened(_) => 0, + Self::TooLarge(n) | Self::Unread(_, n) => *n, + } + } + + /// What a command says of it. + pub(crate) fn message(self) -> String { + match self { + Self::Unopened(why) | Self::Unread(why, _) => why, + Self::TooLarge(_) => "the picture is too large".into(), + } + } +} + +/// 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. Only a regular file is opened: opening a named +/// pipe or a device (`/dev/stdin`) waits for a writer, and this runs on the command's thread. +pub(crate) fn read_picture_file(path: &str, max: usize) -> Result, PictureFileError> { + let unopened = |e: std::io::Error| PictureFileError::Unopened(format!("{path}: {e}")); + if !std::fs::metadata(path).map_err(unopened)?.is_file() { + return Err(PictureFileError::Unopened(format!("{path}: not a regular file"))); + } + let file = rustgis_data::provenance::open(path).map_err(unopened)?; + let bytes = read_within(&file, max).map_err(|(e, n)| match e { + Some(e) => PictureFileError::Unread(format!("{path}: {e}"), n), + None => PictureFileError::TooLarge(n), + })?; + rustgis_data::provenance::buffer(std::path::Path::new(path), &file, &bytes); + Ok(bytes) +} + +/// At most `max` bytes of `from`; past them (`None`) or on a read error, with how many were read. +fn read_within(from: impl std::io::Read, max: usize) -> Result, (Option, usize)> { + use std::io::Read; + let mut bytes = Vec::new(); + // Bytes read before an error are kept in `bytes`. + if let Err(e) = from.take(max as u64 + 1).read_to_end(&mut bytes) { + return Err((Some(e), bytes.len())); + } + if bytes.len() > max { + return Err((None, bytes.len())); + } + 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()) { @@ -458,3 +508,31 @@ fn restyle(s: &mut Session, p: &Value, one: Option<(u32, usize)>) -> CmdResult { } Ok(json!({"styled": n})) } + +#[cfg(test)] +mod tests { + /// Gives `good` bytes, then fails. + struct Failing(usize); + + impl std::io::Read for Failing { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.0 == 0 { + return Err(std::io::Error::other("the disk failed")); + } + let n = self.0.min(buf.len()); + buf[..n].fill(7); + self.0 -= n; + Ok(n) + } + } + + #[test] + fn a_picture_read_that_fails_says_how_much_it_read() { + let (e, n) = super::read_within(Failing(10), 100).unwrap_err(); + assert_eq!((e.map(|e| e.to_string()), n), (Some("the disk failed".to_string()), 10)); + // Past the most it takes: one byte more read, no error. + let (e, n) = super::read_within(&[7u8; 20][..], 10).unwrap_err(); + assert_eq!((e.is_none(), n), (true, 11)); + assert_eq!(super::read_within(&[7u8; 10][..], 10).unwrap().len(), 10); + } +} diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 6b5803743e..5a2141144e 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -48,6 +48,88 @@ 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. On the import's thread, as the rest of it is +/// (`import_project` and `import_style` say why): each read is one file of at most 1.5 MiB, only +/// a regular file is opened (a pipe or a device would wait for a writer), and the bound caps them +/// all. +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 (`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 +/// of it, so the import's bound overshoots by one file at most. Checking it decodes it, at most +/// 20,000 pixels a side within 512 MiB, as `layer.marker` does. +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"; + const NOT_AN_IMAGE: &str = "whose image isn't a PNG or JPEG RustGIS reads"; + let b64 = match source.strip_prefix("base64:") { + // Past the limit, refused before it is copied, and charged as a file past it is. + Some(b64) if b64.trim().len() > MAX_PICTURE_BYTES => { + *read += MAX_PICTURE_BYTES; + return Err(TOO_LARGE); + } + 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) if bytes.is_empty() => return Err(NOT_AN_IMAGE), + Ok(bytes) => base64::engine::general_purpose::STANDARD.encode(bytes), + Err(e) => { + use super::graphics::PictureFileError; + // What was read of it is charged, as its base64 would be (none for one that + // doesn't open). + *read += e.read().div_ceil(3) * 4; + return Err(match e { + PictureFileError::Unopened(_) => "whose image file doesn't open", + PictureFileError::TooLarge(_) => TOO_LARGE, + PictureFileError::Unread(..) => "whose image file fails as it is read", + }); + } + }, + }; + *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 && h > 0 => Ok((b64, h as f32 / w as f32)), + _ => Err(NOT_AN_IMAGE), + } +} + /// 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 @@ -68,7 +150,9 @@ 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`]. A local archive's file is looked +/// metadata, annotation pictures within [`MAX_PICTURE_BYTES`], raster image 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 /// layer (WMS, WMTS, WFS, OGC API, ArcGIS, WCS) asks its service on this thread, through /// `service.add`: its capabilities, then a WFS, OGC API or ArcGIS layer's features (each page @@ -78,14 +162,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}))?; @@ -1931,12 +2010,20 @@ fn notify_report(s: &mut Session, report: &Report) { } } +/// Imports a QGIS style onto a layer. On the thread that runs it: the style import isn't among +/// the commands whose reads the app makes on a thread first ([`super::reads`]), as it wasn't +/// before it read marker images. Reading the style and its images there, with Cancel, is its own +/// change. Its work is bounded by the style: one file of at most [`MAX_FILE`] bytes, its XML +/// parsed within [`MAX_XML`], and its raster image markers' images within [`MARKER_READ_BYTES`], +/// each file read once and decoded once to check it (see [`marker_images`] and [`marker_image`]). fn import_style(s: &mut Session, p: &Value) -> CmdResult { let text = qgis_text(p)?; 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..8e28e51ccf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2905,6 +2905,164 @@ 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}; + // Removed however the test ends. + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let guard = Dir(std::env::temp_dir().join(format!("rustgis-qgis-raster-markers-{}", std::process::id()))); + let dir = guard.0.clone(); + let _ = std::fs::remove_dir_all(&dir); + 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}"); + } + // An empty file isn't an image. + std::fs::write(dir.join("pins/empty.png"), b"").unwrap(); + let path = dir.join("pins.qml"); + std::fs::write(&path, qml("pins/empty.png")).unwrap(); + let r = s.run("style.importQgis", &json!({"layer": "Cities", "path": path.to_string_lossy()})).unwrap(); + assert_eq!(notes(&r), ["raster image markers whose image isn't a PNG or JPEG RustGIS reads, drawn as circles"]); + // A named pipe isn't opened: opening one waits for a writer, which would hold the import. + #[cfg(unix)] + if std::process::Command::new("mkfifo").arg(dir.join("pins/pipe.png")).status().is_ok_and(|s| s.success()) { + let path = dir.join("pins.qml"); + std::fs::write(&path, qml("pins/pipe.png")).unwrap(); + let r = s.run("style.importQgis", &json!({"layer": "Cities", "path": path.to_string_lossy()})).unwrap(); + assert_eq!(notes(&r), ["raster image markers whose image file doesn't open, drawn as circles"]); + } else { + eprintln!("skipped the named pipe: no mkfifo"); + } + // 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), + ] + ); + // A file past what a marker keeps is charged for what was read of it: two take the budget. + for name in ["big2.png", "big3.png"] { + std::fs::copy(dir.join("pins/big.png"), dir.join("pins").join(name)).unwrap(); + } + let file = |f: &str| { + format!( + r#""# + ) + }; + let path = dir.join("pins.qml"); + std::fs::write( + &path, + format!( + r#"{}{}{}"#, + file("big.png"), + file("big2.png"), + file("big3.png") + ), + ) + .unwrap(); + let r = s.run("style.importQgis", &json!({"layer": "Cities", "path": path.to_string_lossy()})).unwrap(); + let mut said = notes(&r); + said.sort(); + assert_eq!( + said, + [ + "raster image markers past the bytes of images an import reads, drawn as circles", + "raster image markers whose image is past 2 MiB of base64, drawn as circles", + ] + ); + // A file that doesn't open is charged nothing: an image after it still reads. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let locked = dir.join("pins/locked.png"); + std::fs::copy(dir.join("pins/big.png"), &locked).unwrap(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + // Run as root, it opens anyway. + if std::fs::File::open(&locked).is_err() { + std::fs::write( + &path, + format!( + r#"{}{}"#, + file("locked.png"), + file("pin.png") + ), + ) + .unwrap(); + let r = s.run("style.importQgis", &json!({"layer": "Cities", "path": path.to_string_lossy()})).unwrap(); + assert_eq!(notes(&r), ["raster image markers whose image file doesn't open, drawn as circles"]); + } else { + eprintln!("skipped the unopenable file: it opens as this user"); + } + } +} + /// 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 +4931,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..19e33f627c 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 { @@ -99,6 +111,12 @@ impl Report { self.note(layer, NoteKind::Skipped, text); } + /// How many times `text` was noted for `layer`. + fn noted(&self, layer: &str, kind: NoteKind, text: &str) -> usize { + let key = (layer.to_string(), kind, text.to_string()); + self.index.get(&key).and_then(|&i| self.notes.get(i)).map_or(0, |n| n.count) + } + /// Withdraws a provisional note once checking against the destination fields disproves it. fn forget(&mut self, layer: &str, kind: NoteKind, text: &str) { let key = (layer.to_string(), kind, text.to_string()); @@ -493,13 +511,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 +818,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..f9de955686 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::{NoteKind, 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. @@ -62,6 +62,9 @@ pub(super) fn turns_by_field(sym: Node) -> bool { /// they are in map units. `turned`: the layer's markers turn by a field, so a marker symbol that /// doesn't is drawn as a mark that keeps still. pub(super) fn read(sym: Node, reference: Option, turned: bool, layer: &str, report: &mut Report) -> Converted { + // Noted once for the symbol, whichever of its opacities (its own, an image layer's, a marker + // line's) is see-through. + let seen = report.noted(layer, NoteKind::Approximated, SEE_THROUGH_IMAGES); let alpha = sym.attribute("alpha").and_then(|a| a.trim().parse::().ok()).filter(|a| a.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0); let fade = |c: Rgba| c.with_alpha((f32::from(c.a()) * alpha).round() as u8); let unit = sym.attribute("outputUnit"); @@ -156,6 +159,19 @@ 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(_)); + let faded = 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))))); + let now = report.noted(layer, NoteKind::Approximated, SEE_THROUGH_IMAGES); + if now > seen + 1 { + for _ in seen + 1..now { + report.forget(layer, NoteKind::Approximated, SEE_THROUGH_IMAGES); + } + } else if now == seen && faded { + report.approximated(layer, SEE_THROUGH_IMAGES); + } out.by = by; out.symbol.fill = fade(out.symbol.fill); out.symbol.stroke = fade(out.symbol.stroke); @@ -650,6 +666,10 @@ fn along(l: Node, p: &[(String, String)], hash: bool, reference: Option, la marker_mark(class, &sp, base, reference, layer, report) }; if let Some(mut st) = stroke { + // An image mark is drawn at the layer's opacity alone. + if alpha < 1.0 && st.markers.is_some_and(|m| matches!(m.mark, LineMark::Marker(Marker::Picture(_)))) { + report.approximated(layer, SEE_THROUGH_IMAGES); + } st.offset += across; st.level = pass; st.color = st.color.map(fade); @@ -708,7 +728,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 +741,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 +819,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 +833,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 +852,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 +889,116 @@ 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 (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`). One at a web address isn't fetched, +/// nor one on a network share (`\\host\share`, `//host/share`), 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, 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 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) { + continue; + } + let source = if file.starts_with("base64:") { + Ok(None) + } 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 file.len() > 1 && file.chars().take(2).all(|c| c == '\\' || c == '/') { + // Looking a share up can sign in to the host the file names, which a style or + // project chose (as an archive on one isn't opened either). + Err("whose image is on a network share, which RustGIS doesn't open") + } 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 { + Ok(Some(super::source::absolute(file, dir))) + }; + if let Ok(Some(path)) = &source + && let Some(got) = files.get(path) + { + report.images.insert(file.to_string(), got.clone()); + continue; + } + if source.is_ok() && (reads >= MAX_PICTURES || bytes >= MAX_PICTURES_BYTES) { + continue; + } + let got = match &source { + Ok(Some(path)) => read(path), + Ok(None) => read(file), + Err(why) => Err(*why), + }; + reads += usize::from(source.is_ok()); + 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)) + }); + if let Ok(Some(path)) = source { + files.insert(path, kept.clone()); + } + report.images.insert(file.to_string(), kept); + } +} + +/// 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"; + +/// 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_IMAGES); + } + return Some(got); + } + 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")); + 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 +1007,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 +1199,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..e7ca51b5fc 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,158 @@ 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); + + // One file, however its path is written, is read once. + asked.clear(); + let mut read = |source: &str| { + asked.push(source.to_string()); + Ok((format!("image of {source}"), 0.5)) + }; + let twice = format!("{}{}", raster_marker("./pins/a.png", ""), raster_marker("pins/a.png", "")); + super::read_style(&marker_qml("1", &twice), "Pins", "/styles", &mut read, &mut Report::default()).unwrap(); + assert_eq!(asked, ["/styles/pins/a.png"]); + + // 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#"