Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ATTRIBUTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<code>.geojson` and `original/countries_<code>.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 |
Expand Down
98 changes: 88 additions & 10 deletions crates/engine/src/cmd/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,16 +268,7 @@ pub(crate) fn picture(p: &Value) -> Result<String, String> {
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()),
};
Expand All @@ -290,6 +281,65 @@ pub(crate) fn picture(p: &Value) -> Result<String, String> {
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<Vec<u8>, 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<Vec<u8>, (Option<std::io::Error>, 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()) {
Expand Down Expand Up @@ -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<usize> {
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);
}
}
105 changes: 96 additions & 9 deletions crates/engine/src/cmd/qgis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,88 @@ fn qgis_text(p: &Value) -> Result<String, String> {
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<String> {
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 };
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved

/// 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;
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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) {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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),
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
};
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
Expand All @@ -68,7 +150,9 @@ fn read_file(path: &str) -> Result<Vec<u8>, 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
Expand All @@ -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)?;
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
// 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}))?;
Expand Down Expand Up @@ -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();
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
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.
Expand Down
Loading
Loading