diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index 4b78e9c6af..70f4022569 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -182,8 +182,10 @@ struct Group { on_ancestors: Vec, } -/// A group named in [`groups`]: its id, its full name, whether that was cut, and its ancestors. -type Named = (ObjectIdentifier, String, bool, Vec); +/// A group listed in [`groups`]: its id, the labels it is listed under ("Mapa / "), and its +/// ancestors. Only the first [`MAX_LAYERS`] are named (a parent's name is read for its +/// children's, wherever it is). +type Listed = (ObjectIdentifier, String, Vec); /// The PDF's layers, in the order a reader lists them (the top first), with their names. fn groups(pdf: &Pdf) -> (Vec, usize) { @@ -201,28 +203,28 @@ fn groups(pdf: &Pdf) -> (Vec, usize) { let set = |d: &Dict, key: &[u8]| -> HashSet { refs(d, key).into_iter().collect() }; let (on, off) = d.as_ref().map(|d| (set(d, b"ON"), set(d, b"OFF"))).unwrap_or_default(); let (member, mut seen): (HashSet<_>, HashSet<_>) = (all.iter().copied().collect(), HashSet::new()); - let mut named = Vec::new(); + let mut listed = Vec::new(); if let Some(order) = d.as_ref().and_then(|d| d.get::(b"Order".as_slice())) { - walk(&order, xref, &member, ("", &[]), (&mut named, &mut seen), 0); - } - for id in all { - if seen.insert(id) { - let (name, cut) = group_name(xref, id); - named.push((id, name, cut, Vec::new())); - } + walk(&order, xref, &member, ("", &[]), (&mut listed, &mut seen), 0); } + listed.extend(all.into_iter().filter(|id| seen.insert(*id)).map(|id| (id, String::new(), Vec::new()))); + // Only the first MAX_LAYERS are named; the others are layers of none, only counted. // A name a group shares with one before it is numbered, so each layer opens again as itself. // Each name's count goes on from its last number, so a run of one name is numbered in linear time. - let (mut groups, mut taken, mut next) = (Vec::with_capacity(named.len()), HashSet::new(), HashMap::new()); - let cut = named.iter().filter(|n| n.2).count(); - for (id, first, _, ancestors) in named { - let mut n = next.get(&first).copied().unwrap_or(1); - let mut name = first.clone(); - while !taken.insert(name.clone()) { - n += 1; - name = format!("{first} ({n})"); + let (mut groups, mut taken, mut next, mut cut) = (Vec::with_capacity(listed.len()), HashSet::new(), HashMap::new(), 0); + for (i, (id, prefix, ancestors)) in listed.into_iter().enumerate() { + let mut name = String::new(); + if i < MAX_LAYERS { + let (first, was_cut) = full_name(xref, &prefix, id); + cut += usize::from(was_cut); + let mut n = next.get(&first).copied().unwrap_or(1); + name.clone_from(&first); + while !taken.insert(name.clone()) { + n += 1; + name = format!("{first} ({n})"); + } + next.insert(first, n); } - next.insert(first, n); groups.push(Group { id, name, on: false, ancestors, on_ancestors: Vec::new() }); } let own = |id: &ObjectIdentifier| !off.contains(id) && (base || on.contains(id)); @@ -239,6 +241,11 @@ fn group_name(xref: &XRef, id: ObjectIdentifier) -> (String, bool) { name.filter(|n| !n.is_empty()).map_or_else(|| ("Unnamed".into(), false), |n| clip(&n)) } +/// A group's name after the labels it is listed under, cut as [`clip`] cuts it. +fn full_name(xref: &XRef, prefix: &str, id: ObjectIdentifier) -> (String, bool) { + clip(&format!("{prefix}{}", group_name(xref, id).0)) +} + /// `name` cut to [`MAX_NAME`] characters, with "…" where it is cut, so names nested under long /// labels stay short however deep they are. /// Whether it was cut is given too: a cut label or name always makes the full name it is in too @@ -259,22 +266,21 @@ fn walk( xref: &XRef, all: &HashSet, (prefix, ancestors): (&str, &[ObjectIdentifier]), - (named, seen): (&mut Vec, &mut HashSet), + (listed, seen): (&mut Vec, &mut HashSet), depth: usize, ) { if depth > 32 { return; } - // The last group listed: its name, id, and where it is in `named`. - let (mut prefix, mut parent): (String, Option<(String, ObjectIdentifier, usize)>) = (prefix.to_string(), None); + // The last group listed: its id, and where it is in `listed`. + let (mut prefix, mut parent): (String, Option<(ObjectIdentifier, usize)>) = (prefix.to_string(), None); for (i, item) in order.raw_iter().enumerate() { match item { MaybeRef::Ref(r) => { let id = r.into(); if all.contains(&id) && seen.insert(id) { - let (name, cut) = clip(&format!("{prefix}{}", group_name(xref, id).0)); - parent = Some((format!("{name} / "), id, named.len())); - named.push((id, name, cut, ancestors.to_vec())); + parent = Some((id, listed.len())); + listed.push((id, prefix.clone(), ancestors.to_vec())); } } MaybeRef::NotRef(o) => { @@ -282,15 +288,16 @@ fn walk( let labelled = a.raw_iter().next().is_some_and(|i| matches!(i, MaybeRef::NotRef(o) if o.clone().into_string().is_some())); match parent.as_mut().filter(|_| !labelled) { - Some((under, id, at)) => { + Some((id, at)) => { + let under = format!("{} / ", full_name(xref, &prefix, *id).0); let nested: Vec = ancestors.iter().copied().chain([*id]).collect(); let mut children = Vec::new(); - walk(&a, xref, all, (under, &nested), (&mut children, &mut *seen), depth + 1); + walk(&a, xref, all, (&under, &nested), (&mut children, &mut *seen), depth + 1); let n = children.len(); - named.splice(*at..*at, children); + listed.splice(*at..*at, children); *at += n; } - None => walk(&a, xref, all, (&prefix, ancestors), (&mut *named, &mut *seen), depth + 1), + None => walk(&a, xref, all, (&prefix, ancestors), (&mut *listed, &mut *seen), depth + 1), } } else if let Some(label) = o.into_string().filter(|_| i == 0) { prefix = format!("{} / ", clip(&format!("{prefix}{}", clip(&text(label.as_bytes())).0)).0); @@ -403,9 +410,19 @@ fn layers_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, m // Theirs is kept while the next group (a sibling, listed next to it) is in the same ones: one // drawing of them at a time, drawn once for each run of siblings; and so is the drawing of // those of them on as the PDF opens, for the check below. With the one of no group on and the - // group's, at most four drawings of the page are held at once. + // group's, and the page as the PDF opens it (for the check below, when all are read), at most + // five drawings of the page are held at once. let mut under: Option<(Vec, Pixmap)> = None; let mut on_under: Option<(Vec, Pixmap)> = None; + // The layers shown, stacked over the content in none, against the page as the PDF opens it: + // content shown only when several groups are on (an OCMD's `/AllOn`) is in no layer, and a + // layer drawn with a group it is in on can show content of it the PDF hides (one flag a layer). + // Where a layer shown changes the page, and each one's pixels the page as it opens hides. + let opened = only.is_none().then(|| render(page, scale, TRANSPARENT)); + let (opened_px, none_px) = + (opened.as_ref().map(|o| o.data_as_u8_slice().as_chunks::<4>().0), none.data_as_u8_slice().as_chunks::<4>().0); + let hides = |i: usize| opened_px.is_some_and(|o| o.get(i) == none_px.get(i)); + let (mut shown, mut showing): (Vec, Vec) = (Vec::new(), Vec::new()); // Each layer drawn is counted, for the progress, and Cancel is looked at after each. if !picked.is_empty() { crate::progress::begin(picked.len()); @@ -430,11 +447,57 @@ fn layers_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, m let with: Vec = g.on_ancestors.iter().copied().chain([g.id]).collect(); draw_with(&with)?.data_as_u8_slice() != without.data_as_u8_slice() }); + if visible && opened.is_some() { + let alpha = layer.0.bands.get(3).map(|b| b.data.as_slice()).unwrap_or_default(); + shown.resize(alpha.len(), false); + let mut hidden = false; + for (i, (s, _)) in shown.iter_mut().zip(alpha).enumerate().filter(|(_, (_, a))| **a > 0.0) { + *s = true; + hidden |= hides(i); + } + if hidden { + showing.push(format!("'{}'", g.name)); + } + } add(&mut out, &g.name, visible, layer); crate::progress::step(1)?; } // Cancel while the last was drawn: nothing is given back. crate::progress::check()?; + drop((draw_with, under, on_under)); + drop(copy); + if let Some(opened) = opened_px { + // Pixels in no layer shown, and pixels a layer shown has that the page hides. + let (mut missing, mut hidden) = (0, 0); + for (i, (o, n)) in opened.iter().zip(none_px).enumerate() { + let layered = shown.get(i).copied().unwrap_or(false); + missing += usize::from(o != n && !layered); + hidden += usize::from(o == n && layered); + } + let share = |n: usize| match 100.0 * n as f64 / opened.len().max(1) as f64 { + p if p < 0.1 => "less than 0.1%".to_string(), + p => format!("{p:.1}%"), + }; + if missing > 0 { + let missing = share(missing); + out.lost.push(format!( + "{missing} of the page as the PDF opens is in none of its PDF layers shown (such as content shown only when several are on)" + )); + } + let on = share(hidden); + let why = "(in a group that is off, where the layer has content outside it too)"; + if let [one] = showing.as_slice() { + out.lost.push(format!("its PDF layer {one} shows content the PDF hides as it opens, on {on} of the page {why}")); + } else if showing.len() > 1 { + let more = showing.len().saturating_sub(NAMED_PAGES); + let tail = if more > 0 { format!(", and {more} more") } else { String::new() }; + let named = showing.iter().take(NAMED_PAGES).cloned().collect::>().join(", "); + out.lost.push(format!( + "{} of its PDF layers show content the PDF hides as it opens: {named}{tail}, on {on} of the page {why}", + showing.len() + )); + } + } if only.is_none_or(str::is_empty) { add(&mut out, "", true, rgba(&none, None, OUTSIDE)?); } @@ -1250,7 +1313,8 @@ mod tests { let start = std::time::Instant::now(); let names: Vec = groups(&pdf).0.into_iter().map(|g| g.name).collect(); assert!(start.elapsed().as_secs() < 10, "{:?}", start.elapsed()); - assert_eq!((names.len(), names[0].as_str(), names[1].as_str(), names[n - 1].as_str()), (n, "Rio", "Rio (2)", "Rio (30000)")); + let named = (names[0].as_str(), names[1].as_str(), names[MAX_LAYERS - 1].as_str(), names[n - 1].as_str()); + assert_eq!((names.len(), named), (n, ("Rio", "Rio (2)", "Rio (64)", ""))); } #[test] @@ -1270,13 +1334,66 @@ mod tests { let (groups, cut) = groups(&pdf); let names: Vec = groups.into_iter().map(|g| g.name).collect(); assert!(start.elapsed().as_secs() < 10, "{:?}", start.elapsed()); - assert_eq!((names.len(), cut), (n, n)); + assert_eq!((names.len(), cut), (n, MAX_LAYERS)); let longest = names.iter().map(|name| name.chars().count()).max().unwrap_or(0); // The cut text, its "…", and the number a repeated name gets. assert!(longest <= MAX_NAME + 1 + " (30000)".len(), "{longest} characters"); assert!(names[0].starts_with("LLL") && names[0].ends_with('…'), "{}", &names[0][..40]); } + #[test] + fn groups_past_the_cap_are_counted_not_named() { + // 70 groups, the last with a name longer than MAX_NAME: past the cap it is never named, so + // no name of a layer that isn't one is said to be cut. + let mut objects = layered_objects(SQUARES, "<< >>"); + let refs: Vec = (5..75).map(|n| format!("{n} 0 R")).collect(); + objects[0] = format!("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [{}] /D << >> >> >>", refs.join(" ")); + objects.extend((9..74).map(|n| format!("<< /Type /OCG /Name (G{n}) >>"))); + objects.push(format!("<< /Type /OCG /Name ({}) >>", "A".repeat(300))); + let pdf = Pdf::new(build(&objects)).unwrap(); + let (groups, cut) = groups(&pdf); + assert_eq!((groups.len(), cut), (70, 0)); + assert_eq!((groups[MAX_LAYERS - 1].name.as_str(), groups[MAX_LAYERS].name.as_str()), ("G68", "")); + let all = read_layers("m", build(&objects).into(), None, true).unwrap(); + assert!(!all.lost.iter().any(|t| t.contains("cut to")), "{:?}", all.lost); + } + + #[test] + fn content_the_layers_show_otherwise_than_the_pdf_opens_is_said() { + // A magenta square shown only when Relevo and Água are both on (`/P /AllOn`): in no layer. + let mut objects = layered_objects(&format!("{SQUARES} /OC /m BDC 1 0 1 rg 0 20 10 10 re f EMC"), "<< >>"); + objects[2] = objects[2].replace("/c 7 0 R", "/c 7 0 R /m 9 0 R"); + objects.push("<< /Type /OCMD /OCGs [5 0 R 6 0 R] /P /AllOn >>".into()); + let all = read_layers("m", build(&objects).into(), None, true).unwrap(); + // How much of the page, and which layers, are said. + let said = |all: &PdfLayers, end: &str| all.lost.texts().find(|t| t.ends_with(end)).map(str::to_string); + let missing = " of the page as the PDF opens is in none of its PDF layers shown (such as content shown only when several are on)"; + let share = said(&all, missing).unwrap_or_else(|| panic!("{:?}", all.lost)); + assert!(share.starts_with(|c: char| c.is_ascii_digit()) && share.contains("% of"), "{share}"); + // Água's square at 40 points is in Relevo's content, its square at 60 outside: with Relevo + // off, the PDF shows only the one at 60, but Água's layer, shown, has both. + let content = "/OC /a BDC 0 1 0 rg 20 0 10 10 re f /OC /b BDC 0 0 1 rg 40 0 10 10 re f EMC EMC \ + /OC /b BDC 0 0 1 rg 60 0 10 10 re f EMC"; + let all = read_layers("m", layered(content, "<< /Order [5 0 R [6 0 R]] /OFF [5 0 R] >>").into(), None, true).unwrap(); + assert_eq!((all.layers[0].name.as_str(), all.layers[0].visible), ("Relevo / Água", true)); + let hidden = " of the page (in a group that is off, where the layer has content outside it too)"; + let layer = said(&all, hidden).unwrap_or_else(|| panic!("{:?}", all.lost)); + assert!(layer.starts_with("its PDF layer 'Relevo / Água' shows content the PDF hides as it opens, on "), "{layer}"); + assert!(said(&all, missing).is_none(), "{:?}", all.lost); + // Quadro, nested in Relevo too, hides Água's square at 40 points under its own there, and + // has one at 0 outside Relevo: both layers show content the PDF hides, and both are named. + let two = "/OC /a BDC 0 1 0 rg 20 0 10 10 re f /OC /b BDC 0 0 1 rg 40 0 10 10 re f EMC \ + /OC /c BDC 1 1 0 rg 40 0 10 10 re f EMC EMC /OC /b BDC 0 0 1 rg 60 0 10 10 re f EMC \ + /OC /c BDC 1 1 0 rg 0 0 10 10 re f EMC"; + let all = read_layers("m", layered(two, "<< /Order [5 0 R [7 0 R 6 0 R]] /OFF [5 0 R] >>").into(), None, true).unwrap(); + let layers = said(&all, hidden).unwrap_or_else(|| panic!("{:?}", all.lost)); + let both = "2 of its PDF layers show content the PDF hides as it opens: 'Relevo / Quadro', 'Relevo / Água', on "; + assert!(layers.starts_with(both), "{layers}"); + // Layers that stack up to the page as it opens say neither. + let all = read_layers("m", layered(SQUARES, "<< /Order [5 0 R [6 0 R]] /OFF [5 0 R] >>").into(), None, true).unwrap(); + assert!(said(&all, hidden).is_none() && said(&all, missing).is_none(), "{:?}", all.lost); + } + /// Each drawing of a layer rewrites the update at the end of one copy of the file: the file /// isn't copied again for each, and a copy holds one update, the last. #[test] diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 4f8f5b9c51..90d034b798 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -699,7 +699,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) 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. | +| 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. Only the first 64 are read as layers of their own; the others are counted, and the notices say what the PDF shows outside the layers read; a layer that draws nothing on the page is left out, and a notice names it. Content the PDF shows only when several layers are on together can be in none of them, and a layer whose content lies partly in a layer that is off can show all of it; a notice says how much of the page as the PDF opens is in no layer shown, and which layers show content it hides. The check compares each pixel of the page as it opens with the page drawn with no layer on and with where the layers shown have content, so it can miss some differences or count some that are not. 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). |