From 900ecc89a76091873def74f509d7607282e5d0ba Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 1 Dec 2026 08:58:44 -0300 Subject: [PATCH 1/2] feat(engine): open uploaded and downloaded PDFs with layers as a group, kept once in the project (#3442 part 4) layer.addDataBytes and layer.addDownload read a PDF page's layers as layer.addData does, from the bytes given; the app reads a download's off the frame. A project writes a raster sharing an earlier layer's embedded file as embedded_same instead of the file again, and requires raster-shared-files so an older RustGIS refuses it by name. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/mod.rs | 15 +++ crates/engine/command-surface.txt | 6 +- crates/engine/src/cmd/layer.rs | 4 +- crates/engine/src/cmd/raster.rs | 111 ++++++++++++++++++---- crates/engine/src/lib.rs | 8 +- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 11 ++- crates/engine/src/tests.rs | 91 +++++++++++++++++- crates/map/src/lib.rs | 1 + crates/map/src/raster.rs | 62 ++++++++++++ crates/ui-egui/src/lib.rs | 28 +++--- docs/user-guide/data-formats.md | 2 +- docs/user-guide/data.md | 2 +- 13 files changed, 298 insertions(+), 44 deletions(-) diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 4a91e30699..811f968341 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -225,6 +225,21 @@ pub fn read_pdf_layers(path: &Path, page: Option<&str>) -> Result { } } +/// [`read_pdf_layers`] for a PDF's contents (an upload, a download) named `file_name`, shared +/// with the layers read from them. +pub fn read_shared_pdf_layers(file_name: &str, bytes: std::sync::Arc>, page: Option<&str>) -> Result { + #[cfg(feature = "pdf")] + { + let name = Path::new(file_name).file_stem().and_then(|s| s.to_str()).unwrap_or("raster"); + pdf::read_layers(name, bytes, page, true) + } + #[cfg(not(feature = "pdf"))] + { + let _ = (file_name, bytes, page); + Ok(PdfLayers::default()) + } +} + /// Why a PDF isn't read in a build without the `pdf` feature (the browser, phones). pub const PDF_ELSEWHERE: &str = "PDFs are read in the desktop app, the command line and Python, not here: open it there"; diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 22dcee42c9..7742873808 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -214,16 +214,16 @@ labels.scaleRange layer? class? min? max? clear? labels.style layer? class? size? color? halo? haloColor? haloWidth? spacing? stretch? bold? italic? font? background? wrapChar? wrapLength? lineAlign? labels.viewUnplaced on? layer.addData path name? layer? pdfLayers? paperSpace? blocks? stream? as? crs? x? y? wkt? delimiter? -layer.addDataBytes fileName data zoom? layer? name? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? +layer.addDataBytes fileName data zoom? layer? name? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? pdfLayers? layer.addDataText fileName text name? x? y? wkt? crs? delimiter? layer? paperSpace? blocks? layer.addDatabase database password? layer? crs? name? stream? -layer.addDownload id url name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? service? bounds? coverage? coverageCrs? drawingInfo? geolibreProject? geolibreLayer? geolibreZarr? connection? anonymous? request? window? +layer.addDownload id url name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? pdfLayers? service? bounds? coverage? coverageCrs? drawingInfo? geolibreProject? geolibreLayer? geolibreZarr? connection? anonymous? request? window? layer.addEncodedPolyline polyline precision? name? layer.addLayerFile path? text? data? group? to? layer.addPhotos paths? folder? name? layer.addSample name layer.addSql sql name? database? password? crs? stream? ran? -layer.addUrl url bytes? format? name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? whole? cog? bbox? cellSize? cube? start? end? unit? interval? dates? connection? service? bounds? from? fromDocument? anonymous? coverage? coverageCrs? request? +layer.addUrl url bytes? format? name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? pdfLayers? whole? cog? bbox? cellSize? cube? start? end? unit? interval? dates? connection? service? bounds? from? fromDocument? anonymous? coverage? coverageCrs? request? layer.addZarr path url variable? index? cells? bbox? crs? name? time? start? end? ran? summary? anonymous? layer.aggregation layer? shape size? layer.blend layer? mode diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 2e0256d0e8..d5c32345f3 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,10 +51,10 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MiB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, its overviews in strips too when it has some, then takes one strip and column in as many as that size holds on that level", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MiB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "pdfLayers"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, its overviews in strips too when it has some, then takes one strip and column in as many as that size holds on that level", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) - .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), + .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "pdfLayers"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), C::new("layer.addEncodedPolyline", "Add Encoded Polyline", "Home › Add", add_encoded_polyline).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"polyline": "encoded polyline text" | [texts] (one line each), "precision"?: 5 (Google) | 6 (OSRM, Valhalla), "name"?: text}"#, ), diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index f99a9ab1d7..ee4cc06b5f 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -38,7 +38,7 @@ pub fn commands() -> Vec { .inputs(crate::cmd::Inputs::single_layer).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view() .params(r#"{"layer"?:name|id}"#), C::new("layer.addDataBytes", "Add Data (from file contents)", "Home › Add", add_bytes::).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"fileName": "name.tif|.tiff|.asc|.grb|.grib|.grb2|.grib2 (GRIB)|.hgt|.dt0|.dt1|.dt2|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData)}"#), + .params(r#"{"fileName": "name.tif|.tiff|.asc|.grb|.grib|.grb2|.grib2 (GRIB)|.hgt|.dt0|.dt1|.dt2|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "pdfLayers"? (as layer.addData)}"#), C::new("raster.symbology", "Symbology", "Style › Rendering", symbology).when(need_raster).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer"?, "type": "stretch"|"rgb"|"classify"|"unique"|"colormap"|"shadedRelief", "band"?: 1.., "ramp"?, "invert"?: bool, "classes"?: 1..32, "method"?, "azimuth"?, "altitude"?, "zFactor"?, "shadow"?: 0..1 (shadedRelief: how dark the shadows the terrain casts are; left out, kept; 0 casts none), "sky"?: 0..1 (shadedRelief: how much the share of the sky each cell sees dims its ambient light; left out, kept; 0 leaves it whole), "fill"?: 0..1 (shadedRelief: a fill light from the side opposite the sun that lightens the slopes turned toward it; left out, kept; 0 has none), "ambient"?: 0..1|null (shadedRelief: the share of the colour a slope turned fully from the sun keeps; left out, kept; null, the default: 0.25, or 0.5 balanced), "balanced"?: bool (shadedRelief: flat ground keeps the ramp's colour and slopes facing the sun brighten, up to 1.3; left out, kept; false, the default, lights as before), "shadowSoftness"?: 0.5..15|null (shadedRelief: how soft the edges of its cast shadows are, as half the sun's apparent size in degrees; left out, kept; outside 0.5 to 15, refused; null, the default: 5), "aerial"?: 0..1|null (shadedRelief: aerial perspective, low ground on the layer's stretch lit with less contrast and hazed toward #ECECEC, the more the lower; left out, kept; outside 0 to 1, refused; null or 0, the default: none), "terrain"?: -1..1|null (shadedRelief: terrain type, each cell's gradient g reshaped for the sun's light only as tan 30° × (g / tan 30°)^(1 − 0.5 × terrain), steepened at most 8 times: above 0 gentle relief shows, below 0 steep ground stands out; cast shadows, sky, fill light and rock keep the ground's slope; left out, kept; outside -1 to 1, refused; null or 0, the default: lit as before), "flats"?: {"amount"?: 0..1, "size"?: 1..32} | false (shadedRelief: flat ground's detail, each cell's direct light moved by its height above the mean within size cells around it, 40 per unit of height (a metre on most DEMs) within 80, times amount, fading out by 4° of slope; best on a terrain model, as a surface model's trees and roads show too; left out, kept; an object's missing keys keep the current one's, or 1 and 6; amount 0, false or null: none, the default; outside, refused), "generalize"?: 0..10000|null (shadedRelief: generalisation, in metres: the lights read from the slopes (sun, fill light, rock) are worked out from the heights smoothed with a Gaussian of that size, so small landforms fade and large ones stay; the colour ramp keeps each cell's own height; left out, kept; outside 0 to 10000, refused; null or 0, the default: none), "rock"?: {"from"?: 0..90, "to"?: 0..90, "color"?: #RRGGBB} | false (shadedRelief: steep slopes tinted toward a rock colour before the light, from the ground's own slope in degrees, without the Z factor: the ramp below from, the colour above to, blended between; left out, kept; an object's missing keys keep the current rock's, or 25, 40 and #B2ACA4; false or null removes it), "grey"?: bool (shadedRelief without its colour ramp)}"#, ), @@ -671,7 +671,7 @@ pub(crate) fn pdf_key(path: &str, page: Option<&str>) -> String { /// has none, saying why when they couldn't be read. pub(crate) fn add_pdf(s: &mut Session, path: &str, name: Option<&str>, page: Option<&str>, ignored: Option) -> CmdResult { let (lost, picture) = match super::reads::take::(s, &pdf_key(path, page)).unwrap_or_else(|| read_pdf(path, page)) { - (Ok(all), None) => return add_pdf_layers(s, path, name, all, ignored), + (Ok(all), None) => return add_pdf_layers(s, PdfFile::Path(path), name, all, ignored, None), (Ok(all), Some(picture)) => (all.lost, picture), (Err(e), Some(picture)) => (vec![format!("{e}: the page is read as one picture")].into(), picture), (Err(e), None) => return Err(format!("{path}: {e}")), @@ -683,13 +683,31 @@ pub(crate) fn add_pdf(s: &mut Session, path: &str, name: Option<&str>, page: Opt add_path_read(s, path, name, page, false, ignored, picture) } +/// Where a PDF's layers are read again from: its file, or its contents (an upload or a download) +/// and their file name. +pub(crate) enum PdfFile<'a> { + Path(&'a str), + Bytes(&'a str, &'a std::sync::Arc>), +} + /// Adds a PDF page's layers as a group named `name` or after the file: the PDF's first on top, /// each shown or hidden as the PDF opens it, and what was read of them said, with `ignored` (the -/// options given that don't apply to it). -fn add_pdf_layers(s: &mut Session, path: &str, name: Option<&str>, mut all: raster::PdfLayers, ignored: Option) -> CmdResult { +/// options given that don't apply to it). `zoom` is the adding command's. +fn add_pdf_layers( + s: &mut Session, + file: PdfFile<'_>, + name: Option<&str>, + mut all: raster::PdfLayers, + ignored: Option, + zoom: Option, +) -> CmdResult { if s.map().groups.len() >= rustgis_map::MAX_GROUPS { return Err(format!("a map holds at most {} groups", rustgis_map::MAX_GROUPS)); } + let (path, full) = match file { + PdfFile::Path(path) => (path, std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string())), + PdfFile::Bytes(file_name, _) => (file_name, file_name.to_string()), + }; let stem = Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or("PDF"); // Cut to MAX_LAYER_NAME characters and said. layer.rename refuses a longer name instead (#1817). let mut title = name.unwrap_or(stem).to_string(); @@ -699,7 +717,6 @@ fn add_pdf_layers(s: &mut Session, path: &str, name: Option<&str>, mut all: rast all.lost.push(format!("the group's name is cut to {most} characters")); } all.lost.extend(ignored); - let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string()); let names: Vec = all.layers.iter().map(|l| l.name.clone()).collect(); let mut ids = Vec::with_capacity(names.len()); // A page without coordinates: its layers laid over one part of the view, though the first @@ -707,10 +724,16 @@ fn add_pdf_layers(s: &mut Session, path: &str, name: Option<&str>, mut all: rast let laid = all.layers.first().filter(|l| !l.raster.georeferenced).map(|l| scan_box(s, l.raster.width, l.raster.height)); // The bottom first, so that each lies over those under it, as in the PDF. for l in all.layers.into_iter().rev() { - let mut rl = RasterLayer::from_path(l.raster, full.clone()); + let mut rl = match file { + PdfFile::Path(_) => RasterLayer::from_path(l.raster, full.clone()), + PdfFile::Bytes(file_name, bytes) => RasterLayer::from_shared(l.raster, file_name, bytes.clone()), + }; rl.subdataset = Some(l.subdataset); rl.placement = laid; - let id = add_raster(s, &l.name, rl)?["layer"].as_u64().and_then(|i| u32::try_from(i).ok()).ok_or("the layer wasn't added")?; + let id = add_raster_after(s, &l.name, rl, zoom)?["layer"] + .as_u64() + .and_then(|i| u32::try_from(i).ok()) + .ok_or("the layer wasn't added")?; if let Some(layer) = s.map_mut().layer_mut(id) { layer.visible = l.visible; } @@ -756,11 +779,12 @@ pub(crate) fn pdf_page(path: &str, p: &Value) -> Result, String> /// Whether a whole file downloaded from `url` is read off the frame before it is added /// (`layer.addDownload` with `p`): a PDF's page to draw, or a GRIB file (whose fields can be -/// many). Its file name, page and whether it is placed by its coordinates (not `"as": "scan"`). +/// many). Its file name, page, whether it is placed by its coordinates (not `"as": "scan"`), and +/// whether a PDF's page is read as its PDF layers (#3442). /// `None` for anything else, or a page that can't be read here, which `layer.addDownload` reads /// (or refuses) as it adds it. #[cfg(not(target_arch = "wasm32"))] -pub fn download_page(url: &str, p: &Value, bytes: &[u8]) -> Option<(String, Option, bool)> { +pub fn download_page(url: &str, p: &Value, bytes: &[u8]) -> Option<(String, Option, bool, bool)> { let plain = ["service", "coverage", "geolibreProject", "geolibreLayer"] .iter() .all(|k| p.get(k).is_none_or(|v| v.is_null() || v.as_bool() == Some(false))); @@ -772,15 +796,54 @@ pub fn download_page(url: &str, p: &Value, bytes: &[u8]) -> Option<(String, Opti .filter(|n| (raster::PDF_PAGES && raster::is_pdf_name(n)) || raster::grib::is_grib_name(n))?; let page = pdf_page(&name, p).ok()?; let scan = wants_scan(p, &name).ok()?; - Some((name, page, !scan)) + let layers = wants_pdf_layers(&name, p, page.as_deref(), scan).ok()?; + Some((name, page, !scan, layers)) } -/// Draws a downloaded PDF's page, or reads a downloaded GRIB file, off the frame -/// ([`download_page`]), for [`crate::Session::download_landed_page`]: from bytes its retry or -/// landing state already shares, without copying a PDF. +/// A downloaded file read off the frame ([`read_download_shared_page`]): a page as one picture +/// (or a GRIB file's field), or a PDF page's layers (#3442). +pub enum DownloadRead { + Page(Raster), + Layers(raster::PdfLayers), +} + +/// Draws a downloaded PDF's page (as its PDF layers when `layers`), or reads a downloaded GRIB +/// file, off the frame ([`download_page`]), for [`crate::Session::download_landed_page`]: from +/// bytes its retry or landing state already shares, without copying a PDF. #[cfg(not(target_arch = "wasm32"))] -pub fn read_download_shared_page(name: &str, bytes: std::sync::Arc>, page: Option<&str>, place: bool) -> Result { - raster::read_shared_page(name, bytes, page, place).map_err(|e| format!("{name}: {e}")) +pub fn read_download_shared_page( + name: &str, + bytes: std::sync::Arc>, + page: Option<&str>, + place: bool, + layers: bool, +) -> Result { + if layers { + return read_shared_pdf(name, bytes, page); + } + raster::read_shared_page(name, bytes, page, place).map(DownloadRead::Page).map_err(|e| format!("{name}: {e}")) +} + +/// A PDF's contents named `name` read as [`read_pdf`] reads its file: its page's PDF layers, or +/// the page as one picture when it has none, or they can't be read (said); Cancel ends the read. +pub(crate) fn read_shared_pdf(name: &str, bytes: std::sync::Arc>, page: Option<&str>) -> Result { + let picture = |lost: rustgis_data::loss::Notes, r: Option| -> Result { + let mut r = match r { + Some(r) => r, + None => raster::read_shared_page(name, bytes.clone(), page, true).map_err(|e| format!("{name}: {e}"))?, + }; + r.lost.extend(lost); + Ok(DownloadRead::Page(r)) + }; + match raster::read_shared_pdf_layers(name, bytes.clone(), page) { + Ok(all) if !all.layers.is_empty() => Ok(DownloadRead::Layers(all)), + Ok(mut all) => { + let r = all.picture.take(); + picture(all.lost, r) + } + Err(e @ rustgis_data::DataError::Cancelled) => Err(format!("{name}: {e}")), + Err(e) => picture(vec![format!("{e}: the page is read as one picture")].into(), None), + } } /// The raster at `path` (a PDF's `page`), read whole, or for a large tiled GeoTIFF on this @@ -1034,7 +1097,7 @@ pub(crate) fn add_named_bytes_read( name: String, bytes: Vec, zoom: Option, - drawn: Option, + drawn: Option, asked: Option, ) -> CmdResult { // A geotagged photo (an upload, a drop): a point in the photo layer, so several uploads @@ -1055,6 +1118,20 @@ pub(crate) fn add_named_bytes_read( let bytes = std::sync::Arc::new(bytes); // A PDF's page, kept so the project reads the same page from its copy again. let page = pdf_page(&name, p)?; + // A PDF with layers: a group of them (#3442), read again from this copy. + let drawn = match drawn { + None if wants_pdf_layers(&name, p, page.as_deref(), scan)? => Some(read_shared_pdf(&name, bytes.clone(), page.as_deref())?), + drawn => drawn, + }; + let ignored = raster::elevation_ignores(&name, ps(p, "layer"), ps(p, "crs")); + let drawn = match drawn { + Some(DownloadRead::Layers(all)) => { + let title = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()); + return add_pdf_layers(s, PdfFile::Bytes(&name, &bytes), title, all, ignored, zoom); + } + Some(DownloadRead::Page(r)) => Some(r), + None => None, + }; let mut r = match drawn { Some(r) => r, // A WCS coverage asked for in its own system (#2032): an answer that doesn't say its @@ -1068,7 +1145,7 @@ pub(crate) fn add_named_bytes_read( None => raster::read_shared_page(&name, bytes.clone(), page.as_deref(), !scan).map_err(|e| format!("{name}: {e}"))?, }, }; - r.lost.extend(raster::elevation_ignores(&name, ps(p, "layer"), ps(p, "crs"))); + r.lost.extend(ignored); if scan { r = r.into_scan().map_err(|e| format!("{name}: {e}"))?; } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6146806621..b51c4cf952 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -781,7 +781,7 @@ struct PutAside { #[cfg(not(target_arch = "wasm32"))] landed_windows: Vec<(u64, cmd::layer::CogWindow)>, #[cfg(not(target_arch = "wasm32"))] - landed_pages: Vec<(u64, rustgis_data::raster::Raster)>, + landed_pages: Vec<(u64, cmd::raster::DownloadRead)>, plugin_retries: Vec, url_waits: cmd::plugins::fetch::UrlWaits, /// A style of the project still loading, which mustn't move the next one's view. @@ -1133,7 +1133,7 @@ pub struct Session { /// PDF pages the app drew off the frame from a download whose bytes landed with them, waiting /// for `layer.addDownload` too (#2336). #[cfg(not(target_arch = "wasm32"))] - pub(crate) landed_pages: Vec<(u64, rustgis_data::raster::Raster)>, + pub(crate) landed_pages: Vec<(u64, cmd::raster::DownloadRead)>, /// Downloads a command asked for where nothing may wait (the browser): the parameters of /// `layer.addUrl` calls, for the front end to fetch and add (see [`Session::take_url_requests`]). pub(crate) url_requests: Vec, @@ -1767,11 +1767,11 @@ impl Session { landed } - /// Hands over a PDF download's bytes with its page drawn off the frame + /// Hands over a PDF download's bytes with its page (or its PDF layers) drawn off the frame /// ([`cmd::raster::read_download_shared_page`]), for `layer.addDownload {"id"}` as /// [`Session::download_landed`] does. #[cfg(not(target_arch = "wasm32"))] - pub fn download_landed_page(&mut self, id: u64, bytes: Vec, page: rustgis_data::raster::Raster) -> bool { + pub fn download_landed_page(&mut self, id: u64, bytes: Vec, page: cmd::raster::DownloadRead) -> bool { let landed = self.landed(id); if landed { self.downloaded.push((id, bytes)); diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index c80dd73c82..77cec356ce 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -101,6 +101,7 @@ pub const CAPABILITIES: &[&str] = &[ "graticule-mgrs", "graticule-on-top", "graticule-color", + "raster-shared-files", "layout-element-ink", "layout-element-wrap", "layout-text-block", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index ba63ebfd65..93e541e9d9 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1654,6 +1654,13 @@ fn keeps_class_order(renderer: &rustgis_map::Renderer) -> bool { matches!(renderer, rustgis_map::Renderer::Unique { keep_order: true, .. }) } +/// Whether two of a map's rasters share one embedded file (the layers of an uploaded PDF, #3442), +/// which is written once: an older reader would leave the others without it, and save them so. +fn shares_embedded_files(map: &Map) -> bool { + let mut seen = std::collections::HashSet::new(); + map.layers.iter().filter_map(|l| l.raster.as_ref()?.embedded.as_ref()).any(|f| !seen.insert(std::sync::Arc::as_ptr(f))) +} + /// The capabilities a layer needs, in [`map_capabilities`]'s order. fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { [ @@ -1700,7 +1707,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static mut on_top, mut grid_color, ) = (false, false, false, false, false, false, false, false, false, false, false, false, false, false, false); - let (mut polygon, mut svg, mut raster_mask, mut class_order) = (false, false, false, false); + let (mut polygon, mut svg, mut raster_mask, mut class_order, mut shared) = (false, false, false, false, false); let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) = (false, false, false, false, false, false, false); let (mut crisp, mut bed, mut walls_top, mut soft, mut aerial, mut terrain_type, mut flats, mut generalize) = @@ -1753,6 +1760,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static native |= map.layers.iter().any(|layer| held_natively(&layer.dataset)); raster_mask |= map.layers.iter().any(|layer| layer.raster_mask.is_some()); class_order |= map.layers.iter().any(|layer| keeps_class_order(&layer.renderer)); + shared |= shares_embedded_files(map); legends |= map.tiles.iter().any(|tile| { tile.legends.iter().any(|legend| rustgis_data::login_address::inner(&legend.url).len() > rustgis_map::tiles::MAX_LEGEND_URL) }); @@ -1792,6 +1800,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (mgrs, "graticule-mgrs"), (on_top, "graticule-on-top"), (grid_color, "graticule-color"), + (shared, "raster-shared-files"), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 41dbf6e9ff..d12a7ba22f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -56189,7 +56189,7 @@ fn a_grib_download_is_read_off_the_frame() { // A GRIB1 message of 52 octets: "GRIB", its length, its edition. let message = b"GRIB\0\0\x34\x01"; let found = download_page("https://example.org/bam/PREC.grb", &asked, message); - assert_eq!(found, Some(("PREC.grb".to_string(), None, true))); + assert_eq!(found, Some(("PREC.grb".to_string(), None, true, false))); let (sniffed, ..) = download_page("https://example.org/record?id=7", &asked, message).unwrap(); assert!(rustgis_data::raster::grib::is_grib_name(&sniffed), "{sniffed}"); assert!(download_page("https://example.org/PREC.grb", &json!({"as": "scan"}), message).is_none()); @@ -56564,14 +56564,15 @@ fn a_pdf_is_added_back_as_a_raster() { let bytes = std::fs::read(&series).unwrap(); let url = "https://example.org/maps/atlas.pdf"; let asked = json!({"url": url, "layer": "2"}); - let (name, page, place) = crate::cmd::raster::download_page(url, &asked, &bytes).unwrap(); + let (name, page, place, layers) = crate::cmd::raster::download_page(url, &asked, &bytes).unwrap(); assert_eq!((name.as_str(), page.as_deref(), place), ("atlas.pdf", Some("2"), true)); assert!(crate::cmd::raster::download_page("https://example.org/a.tif", &asked, &bytes).is_none()); // An address without a file name: a PDF by its contents. let (sniffed, ..) = crate::cmd::raster::download_page("https://example.org/download?id=42", &asked, &bytes).unwrap(); assert!(rustgis_data::raster::is_pdf_name(&sniffed), "{sniffed}"); let drawn = - crate::cmd::raster::read_download_shared_page(&name, std::sync::Arc::new(bytes.clone()), page.as_deref(), place).unwrap(); + crate::cmd::raster::read_download_shared_page(&name, std::sync::Arc::new(bytes.clone()), page.as_deref(), place, layers) + .unwrap(); let id = s.download_started(); assert!(s.download_landed_page(id, bytes, drawn)); let r = s.run("layer.addDownload", &json!({"id": id, "url": url, "layer": "2"})).unwrap(); @@ -56771,6 +56772,90 @@ fn a_pdf_with_layers_is_added_as_a_group_of_them() { assert!(!said.iter().any(|t| t.contains("ignored")), "{said:?}"); } +/// A PDF with layers uploaded or downloaded opens as a group of them too, read again from its +/// copy: the downloaded one drawn off the frame by the app, as a page without layers is (#3442). +#[test] +fn an_uploaded_or_downloaded_pdf_with_layers_is_added_as_a_group_of_them() { + use base64::Engine; + let mut s = world(); + s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "map"})).unwrap(); + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let dir = Dir(std::env::temp_dir().join(format!("rustgis-pdf-layers-bytes-{}-{nanos}", std::process::id()))); + std::fs::create_dir_all(&dir.0).unwrap(); + let path = dir.0.join("camadas.pdf"); + s.run("layout.export", &json!({"path": path, "dpi": 36})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + // Each layer as the file's are, read from the copy. + type Kept = (String, rustgis_geom::Extent, usize, Option, Option, bool); + let kept = |t: &Session, id: u32| -> Kept { + let l = t.map().layer(id).unwrap(); + let r = l.raster.as_ref().unwrap(); + let d = r.data.as_ref().unwrap(); + (l.name.clone(), d.extent(), d.band_count(), r.file_name.clone(), r.subdataset.clone(), l.visible) + }; + let ids = |r: &Value| -> Vec { r["layers"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap() as u32).collect() }; + let mut t = Session::new(Project::default()); + let mut f = Session::new(Project::default()); + let from_file = ids(&f.run("layer.addData", &json!({"path": path})).unwrap()); + let data = base64::engine::general_purpose::STANDARD.encode(&bytes); + let mark = t.notice_mark(); + let r = t.run("layer.addDataBytes", &json!({"fileName": "enviado.pdf", "data": data})).unwrap(); + let said: Vec = t.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let uploaded = ids(&r); + assert_eq!(uploaded.len(), from_file.len(), "{r}"); + let group = t.map().groups.iter().find(|g| Some(u64::from(g.id)) == r["group"].as_u64()).unwrap(); + assert_eq!(group.name, "enviado"); + assert!(said.iter().any(|t| t.starts_with(&format!("enviado: added {} PDF layers (", uploaded.len()))), "{said:?}"); + let layers: Vec = uploaded.iter().map(|id| kept(&t, *id)).collect(); + for ((n, e, b, file, sub, v), id) in layers.iter().zip(&from_file) { + let (fname, fe, fb, _, fsub, fv) = kept(&f, *id); + assert_eq!((n, e, b, file.as_deref(), sub, v), (&fname, &fe, &fb, Some("enviado.pdf"), &fsub, &fv)); + } + // As one picture when asked. + let r = t.run("layer.addDataBytes", &json!({"fileName": "enviado.pdf", "data": data, "pdfLayers": false})).unwrap(); + assert_eq!((r["bands"].as_u64(), r.get("group")), (Some(3), None)); + // Saved and opened again: the same layers, from the copy the project keeps, kept once (an + // older RustGIS refuses the project by name rather than leave the other layers empty). + let rgis = dir.0.join("enviado.rgis"); + t.run("project.saveAs", &json!({"path": rgis.display().to_string()})).unwrap(); + let saved = std::fs::read_to_string(&rgis).unwrap(); + assert_eq!(saved.matches(&data).count(), 2, "one copy for the group's {} layers, one for the picture", uploaded.len()); + assert!(saved.len() < 3 * data.len(), "{} bytes for a {}-byte PDF", saved.len(), data.len()); + let saved: Value = serde_json::from_str(&saved).unwrap(); + assert!(saved["requires"].as_array().unwrap().contains(&json!("raster-shared-files")), "{}", saved["requires"]); + let mut u = Session::new(Project::default()); + u.run("project.open", &json!({"path": rgis.display().to_string()})).unwrap(); + for before in &layers { + let l = u.map().layers.iter().find(|l| l.name == before.0).unwrap_or_else(|| panic!("no {}", before.0)); + assert_eq!(&kept(&u, l.id), before); + } + // A download: its layers read off the frame by the app, and added as read. + let url = "https://example.org/mapas/baixado.pdf"; + let asked = json!({"url": url}); + let (name, page, place, layers_wanted) = crate::cmd::raster::download_page(url, &asked, &bytes).unwrap(); + assert!(place && layers_wanted); + let (.., one) = crate::cmd::raster::download_page(url, &json!({"url": url, "pdfLayers": false}), &bytes).unwrap(); + assert!(!one); + let read = + crate::cmd::raster::read_download_shared_page(&name, std::sync::Arc::new(bytes.clone()), page.as_deref(), place, layers_wanted) + .unwrap(); + let mut d = Session::new(Project::default()); + let id = d.download_started(); + assert!(d.download_landed_page(id, bytes.clone(), read)); + let r = d.run("layer.addDownload", &json!({"id": id, "url": url})).unwrap(); + let downloaded = ids(&r); + assert_eq!(downloaded.len(), from_file.len(), "{r}"); + let group = d.map().groups.iter().find(|g| Some(u64::from(g.id)) == r["group"].as_u64()).unwrap(); + assert_eq!(group.name, "baixado"); + assert!(downloaded.iter().all(|id| kept(&d, *id).3.as_deref() == Some("baixado.pdf"))); +} + /// A frame drawn over another (an inset on the main map) is cut out of the other's viewport, so /// that a reader shows the main map's coordinates around the inset and not in it: none there when /// the inset is left out of georeferencing (tilted), the inset's own when it isn't (#1191). No two diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 04073d485b..e09a54a766 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -2308,6 +2308,7 @@ pub struct Map { /// The home project's offline area this map edits, independent of the tab title. #[serde(default, skip_serializing_if = "Option::is_none")] pub offline_area_id: Option, + #[serde(with = "raster::shared_files")] pub layers: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub service_groups: Vec, diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index c34aec5678..168170ea40 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -37,6 +37,10 @@ pub struct RasterLayer { /// The original file, kept in the project when there is no path (a browser upload). #[serde(default, skip_serializing_if = "Option::is_none", with = "b64")] pub embedded: Option>>, + /// Only in a saved map: the id of an earlier layer whose embedded file this one shares, written + /// instead of the file again (see [`shared_files`]). Reading gives it that file and clears it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub embedded_same: Option, /// For a raster GDAL reads: the subdataset added (a NetCDF variable), so it is read again. #[serde(default, skip_serializing_if = "Option::is_none")] pub subdataset: Option, @@ -332,6 +336,7 @@ impl RasterLayer { tiled, file_name: None, embedded: None, + embedded_same: None, subdataset: sub.filter(|_| !elevation).map(String::from), crs: self.crs.clone().filter(|_| !elevation), time_zarr: None, @@ -384,6 +389,7 @@ impl RasterLayer { tiled: false, file_name: None, embedded: None, + embedded_same: None, subdataset: None, crs: None, time_zarr: None, @@ -442,6 +448,7 @@ impl RasterLayer { tiled: false, file_name: Some(file_name.into()), embedded: Some(bytes), + embedded_same: None, subdataset: None, crs: None, time_zarr: None, @@ -488,6 +495,7 @@ impl RasterLayer { tiled: false, file_name: None, embedded: None, + embedded_same: None, subdataset: None, crs: None, time_zarr: None, @@ -941,6 +949,7 @@ impl RasterLayer { // Read into `data`, compared itself. file_name: _, embedded: _, + embedded_same: _, subdataset, crs, time_zarr, @@ -1875,6 +1884,58 @@ pub(crate) mod b64 { } } +/// A map's layers with each embedded file written once (#3442): a raster sharing an earlier +/// layer's (the layers of one uploaded PDF) names that layer in `embedded_same` instead, and +/// reading shares the file again. Projects that use it require `raster-shared-files`. +pub(crate) mod shared_files { + use std::collections::HashMap; + use std::sync::Arc; + + use serde::ser::SerializeSeq; + use serde::{Deserialize, Deserializer, Serializer}; + + use crate::Layer; + + pub fn serialize(layers: &[Layer], s: S) -> Result { + let mut first = HashMap::new(); + let mut seq = s.serialize_seq(Some(layers.len()))?; + for layer in layers { + let file = layer.raster.as_ref().and_then(|r| r.embedded.as_ref()); + match file.and_then(|f| first.get(&Arc::as_ptr(f))) { + Some(&id) => { + let mut same = layer.clone(); + if let Some(r) = &mut same.raster { + (r.embedded, r.embedded_same) = (None, Some(id)); + } + seq.serialize_element(&same)?; + } + None => { + if let Some(f) = file { + first.insert(Arc::as_ptr(f), layer.id); + } + seq.serialize_element(layer)?; + } + } + } + seq.end() + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let mut layers = Vec::::deserialize(d)?; + let files: HashMap>> = layers.iter().filter_map(|l| Some((l.id, l.raster.as_ref()?.embedded.clone()?))).collect(); + for r in layers.iter_mut().filter_map(|l| l.raster.as_mut()) { + // One naming a layer without a file (a hand edit) is left without data, as a corrupt + // embedded file is. + if let Some(id) = r.embedded_same.take() + && r.embedded.is_none() + { + r.embedded = files.get(&id).cloned(); + } + } + Ok(layers) + } +} + /// How pixel values map onto the colour range. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub enum Stretch { @@ -3030,6 +3091,7 @@ impl RasterLayer { path, file_name: _, embedded, + embedded_same: _, subdataset: _, crs: _, time_zarr, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 30133aec89..1a8315a428 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -425,7 +425,7 @@ pub(crate) struct UnderWay { /// Where a PDF download's bytes and drawn page land ([`UiState::page_reads`]). #[cfg(not(target_arch = "wasm32"))] -type PageRead = Slot, rustgis_engine::data::raster::Raster), String>>; +type PageRead = Slot, rustgis_engine::cmd::raster::DownloadRead), String>>; /// See [`UiState::window_reads`]. #[cfg(not(target_arch = "wasm32"))] @@ -469,13 +469,12 @@ fn window_turn(left: &std::sync::atomic::AtomicBool) -> Option>, - page: Option<&str>, - place: bool, + (page, place, layers): (Option<&str>, bool, bool), left: &std::sync::Arc, -) -> Result { +) -> Result { let _probe = rustgis_engine::data::progress::install(Some(std::sync::Arc::new(syncmark::Stop(left.clone())))); std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::raster::read_download_shared_page(name, bytes.clone(), page, place) + rustgis_engine::cmd::raster::read_download_shared_page(name, bytes.clone(), page, place, layers) })) .unwrap_or_else(|payload| Err(crate::bug(tl!("Reading the download"), payload.as_ref()))) } @@ -1194,7 +1193,7 @@ pub struct UiState { /// [`MAX_WINDOW_READS`] reads under way), oldest first: the download, its bytes, and its page /// to draw ([`rustgis_engine::cmd::raster::download_page`]). #[cfg(not(target_arch = "wasm32"))] - pub(crate) page_queue: Vec<(serviceui::Landed, Vec, (String, Option, bool))>, + pub(crate) page_queue: Vec<(serviceui::Landed, Vec, (String, Option, bool, bool))>, /// Service layers whose features are being read page by page (an ArcGIS layer's description /// first). pub service_pages: Vec, @@ -7035,12 +7034,17 @@ impl RustGisApp { /// /// [`download_page`]: rustgis_engine::cmd::raster::download_page #[cfg(not(target_arch = "wasm32"))] - fn draw_page(&mut self, landed: serviceui::Landed, bytes: Vec, (name, page, place): (String, Option, bool)) -> bool { + fn draw_page( + &mut self, + landed: serviceui::Landed, + bytes: Vec, + (name, page, place, layers): (String, Option, bool, bool), + ) -> bool { if self.ui.page_reads.len() + self.ui.window_reads.len() >= MAX_WINDOW_READS { - self.ui.page_queue.push((landed, bytes, (name, page, place))); + self.ui.page_queue.push((landed, bytes, (name, page, place, layers))); return false; } - let asked = (name.clone(), page.clone(), place); + let asked = (name.clone(), page.clone(), place, layers); let slot: PageRead = Slot::default(); let land = slot.clone(); let left = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -7052,7 +7056,7 @@ impl RustGisApp { let turn = window_turn(&leaving); let read = match turn { // On a thread no command's catch reaches: a bug must not leave it running forever. - Some(_) => read_download(&name, &bytes, page.as_deref(), place, &leaving), + Some(_) => read_download(&name, &bytes, (page.as_deref(), place, layers), &leaving), None => Err(tl!("given up before it was read: it was cancelled, or its project was closed").to_string()), }; let bytes = std::sync::Arc::try_unwrap(bytes).unwrap_or_else(|shared| (*shared).clone()); @@ -9586,10 +9590,10 @@ mod record_tests { bytes.resize(64, 0); let bytes = std::sync::Arc::new(bytes); let left = std::sync::Arc::new(AtomicBool::new(false)); - let read = crate::read_download("t.grb", &bytes, None, true, &left).unwrap_err(); + let read = crate::read_download("t.grb", &bytes, (None, true, false), &left).err().unwrap(); assert!(!read.contains("cancel"), "{read}"); left.store(true, Ordering::Relaxed); - let cancelled = crate::read_download("t.grb", &bytes, None, true, &left).unwrap_err(); + let cancelled = crate::read_download("t.grb", &bytes, (None, true, false), &left).err().unwrap(); assert!(cancelled.to_lowercase().contains("cancel"), "{cancelled}"); } diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 9cce8358e7..a1420770c9 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -697,7 +697,7 @@ databases](data.md#sql-queries-and-duckdb-databases). | --- | --- | --- | --- | | GeoTIFF / Cloud-optimised GeoTIFF | `.tif`, `.tiff` | Add Data, or upload | Regular or cloud-optimised, striped or tiled; grey, RGB(A), palette (with its colour table) or multiband; Deflate, LZW, PackBits, JPEG, Zstandard or LERC compression (LERC alone or wrapped in Deflate or Zstandard, as GDAL writes it, in the browser too). Supported EPSG systems or the file's own GeoKey projection are reprojected as it draws. Rotated or skewed images are resampled north-up. Large files open from an overview, or one made while reading. A GDAL internal transparency mask (a 1-bit image in its own IFD, as written for JPEG/YCbCr RGB) is read as transparency: masked pixels are see-through, as no-data is, using the mask of the image or overview opened; one that can't be read is said, and the image still opens. Tiles read in place from a cloud-optimised file don't apply the mask, and say so; external `.msk` sidecars aren't read. Browser uploads over 256 MiB read only the parts needed for a fitting overview, provided those parts fit the upload limit; the project keeps those parts, not the full-resolution file. | | JPEG 2000 | `.jp2`, `.j2k` | Add Data, byte upload (`layer.addDataBytes`), or From URL… (desktop, with [GDAL](https://gdal.org) installed) | Converted through GDAL. Uploads and downloads keep the converted GeoTIFF in the project, so reopening it needs neither GDAL nor the original file or address; their output and workspace limits are described under [Files on the web](#files-on-the-web). The web app rejects JPEG 2000 uploads and downloads with an explicit GDAL limitation: use GeoTIFF instead. | -| PDF and GeoPDF | `.pdf` | Add Data, upload or From URL… (desktop, command line and Python; the browser and phones say to open it there) | A page drawn as a picture at 150 dots an inch (less when that wouldn't fit in memory, and a notice says so). A GeoPDF page is placed by its map frame's coordinates (ISO 32000 viewports, as layouts export them), which run across the whole page, its title and legend included; a turned frame is resampled north up. A page with several map frames is placed by the largest, the others counted in a notice. A page without coordinates opens as a scan to georeference, as does any page with `"as": "scan"`. A world file beside a PDF isn't read: only its own coordinates place it. The first page is added and the others named in a notice; `"layer": "2"` adds page 2, which a project keeps. A page with PDF layers (optional content groups) added by its path opens as a group of them, named after the file or `"name"`: one raster each (red, green, blue and alpha), the PDF's first on top, each shown or hidden as the PDF opens it, and **Not in a PDF layer** for what is in none. A layer nested in another is named after it (`Mapa / Rios`) and lies over it. Each layer holds what changes on the page when it is turned on, so where it draws the very colour already under it, that part stays with the layer under it. The first 64 are layers of their own, and the others are drawn in **Not in a PDF layer** when the PDF shows them; a layer that draws nothing on the page is left out, and a notice names it. A project opens each layer again by its page and name. `"pdfLayers": false` opens the page as one picture, as an uploaded or downloaded PDF opens for now. Encrypted PDFs aren't read. | +| PDF and GeoPDF | `.pdf` | Add Data, upload or From URL… (desktop, command line and Python; the browser and phones say to open it there) | A page drawn as a picture at 150 dots an inch (less when that wouldn't fit in memory, and a notice says so). A GeoPDF page is placed by its map frame's coordinates (ISO 32000 viewports, as layouts export them), which run across the whole page, its title and legend included; a turned frame is resampled north up. A page with several map frames is placed by the largest, the others counted in a notice. A page without coordinates opens as a scan to georeference, as does any page with `"as": "scan"`. A world file beside a PDF isn't read: only its own coordinates place it. The first page is added and the others named in a notice; `"layer": "2"` adds page 2, which a project keeps. A page with PDF layers (optional content groups) opens as a group of them, named after the file or `"name"`: one raster each (red, green, blue and alpha), the PDF's first on top, each shown or hidden as the PDF opens it, and **Not in a PDF layer** for what is in none. A layer nested in another is named after it (`Mapa / Rios`) and lies over it. Each layer holds what changes on the page when it is turned on, so where it draws the very colour already under it, that part stays with the layer under it. The first 64 are layers of their own, and the others are drawn in **Not in a PDF layer** when the PDF shows them; a layer that draws nothing on the page is left out, and a notice names it. Uploaded and downloaded PDFs open alike, and a project opens each layer again by its page and name; it keeps an uploaded or downloaded PDF once for all its layers, so a RustGIS older than this refuses such a project by name rather than open the other layers empty. `"pdfLayers": false` opens the page as one picture. Encrypted PDFs aren't read. | | Scans with no coordinates | an untagged `.tif` or `.png`, or a PDF page without coordinates; any `.tif`, `.png`, `.jpg`/`.jpeg` or `.pdf` with `"as": "scan"` | Add Data, or upload (`layer.addData`, `layer.addDataBytes`) | Grey or RGB(A), 8- or 16-bit pixels. An untagged TIFF or PNG opens as a scan by default; a JPEG needs `"as": "scan"` (otherwise it is a photo). `"as": "scan"` also discards a GeoTIFF's coordinates. A world file beside a TIFF, PNG or JPEG (`.tfw`, `.jgw`, `.pgw`, the four-letter `.tifw`, `.jpgw`, `.pngw`, or `.wld`), with a `.prj` beside it for the coordinate system, places it instead (a JPEG too, which is then not a photo): a turned or skewed one is resampled north up; without a `.prj`, with one RustGIS can't use, or with a world file that can't be read or places the picture nowhere it can be drawn (UTM meters with a longitude/latitude `.prj`), it stays a scan and a notice says why. `"as": "scan"` passes the world file over. World files are read for files added by their path (an upload doesn't bring the files beside it). A project reopens a picture as it was added: one that opened as a scan stays one (add it again once its `.prj` is there), and one a world file placed still opens if its `.prj` or world file is gone, at a stand-in place, with a notice saying it has no coordinates now. A world file is compared with a GeoTIFF's own tags only when both are north up (a turned GeoTIFF is resampled as it is read). A GeoTIFF keeps its own tags, and a notice says when a world file places it differently. The scan initially covers the current view and is marked not georeferenced (`georeferenced: false`) until **Georeference** places it. Export and tools needing ground coordinates refuse it until then. PNG/JPEG decoding is bounded and may reduce the image; large TIFFs can be read at reduced resolution. | | ASCII grid | `.asc` (with an optional `.prj` on desktop) | Add Data, or upload | A single numeric band with square `CELLSIZE` or separate `DX` and `DY` pixel sizes. Desktop files use the neighbouring `.prj`; uploaded and downloaded grids have no sidecar and must have coordinates that fit WGS 84 longitude/latitude. A grid with no `.prj` is read as WGS 84, and a notice says so. | | Zarr | a store's folder (`.zarr`, desktop) or web address (desktop and browser), format 2 (consolidated) or 3 | Home › Add › Add Data › Zarr… (`layer.addZarr`), Add Data on a local folder, or a `?zarr=` link | A variable's latitude/longitude (or y/x) map at the steps picked of its other dimensions (time, level), read chunk by chunk in pure Rust (blosc, zlib, gzip, zstd, LZ4; sharded arrays too). See [Zarr stores](data.md#zarr-stores). | diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index cade556269..982b964ee8 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -29,7 +29,7 @@ Formats](data-formats.md). | GRIB editions 1 and 2, simple packing and GRIB2's complex packing on latitude/longitude grids (`.grb`, `.grib`, `.grb2`, `.grib2`) | Yes | No | | SRTM height tiles (`.hgt`) and DTED (`.dt0`–`.dt2`) | Yes | No | | Unreferenced TIFF and PNG scans; JPEG with `"as": "scan"` | Yes | GeoTIFF after georeferencing | -| PDF pages: GeoPDFs placed by their coordinates, other pages as scans; a page with PDF layers opened by its path as a group of them (uploaded or downloaded, still as one picture) | Yes (desktop, command line and Python) | GeoTIFF after georeferencing | +| PDF pages: GeoPDFs placed by their coordinates, other pages as scans; a page with PDF layers as a group of them | Yes (desktop, command line and Python) | GeoTIFF after georeferencing | | Through GDAL: JPEG 2000, ERDAS Imagine, NetCDF, HDF, ENVI, SAGA… | Yes (desktop, when GDAL is installed) | No | | Web tiles: XYZ/TMS/WMS rasters, Mapbox Vector Tiles, MapLibre styles, PMTiles and MBTiles archives | Yes | Yes (Imagery › Create Hosted Imagery) | | RustGIS project (`.rgis`; older `.rgisx` files open too) | Yes | Yes | From 7debf33c039f25c548cd4b6226d4ae4af757ea8c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 1 Dec 2026 15:06:49 -0300 Subject: [PATCH 2/2] chore(schema): list the raster-shared-files capability in the project schema Co-Authored-By: Claude Opus 5.5 --- schema/project.schema.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/schema/project.schema.json b/schema/project.schema.json index 840902116b..d45777a2c9 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1270,6 +1270,7 @@ "graticule-mgrs", "graticule-on-top", "graticule-color", + "raster-shared-files", "layout-element-ink", "layout-element-wrap", "layout-text-block", @@ -1417,6 +1418,7 @@ "graticule-mgrs", "graticule-on-top", "graticule-color", + "raster-shared-files", "layout-element-ink", "layout-element-wrap", "layout-text-block",