Skip to content
Merged
181 changes: 149 additions & 32 deletions crates/data/src/raster/pdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,10 @@ struct Group {
on_ancestors: Vec<ObjectIdentifier>,
}

/// A group named in [`groups`]: its id, its full name, whether that was cut, and its ancestors.
type Named = (ObjectIdentifier, String, bool, Vec<ObjectIdentifier>);
/// 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<ObjectIdentifier>);

/// The PDF's layers, in the order a reader lists them (the top first), with their names.
fn groups(pdf: &Pdf) -> (Vec<Group>, usize) {
Expand All @@ -201,28 +203,28 @@ fn groups(pdf: &Pdf) -> (Vec<Group>, usize) {
let set = |d: &Dict, key: &[u8]| -> HashSet<ObjectIdentifier> { 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::<Array>(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));
Expand All @@ -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
Expand All @@ -259,38 +266,38 @@ fn walk(
xref: &XRef,
all: &HashSet<ObjectIdentifier>,
(prefix, ancestors): (&str, &[ObjectIdentifier]),
(named, seen): (&mut Vec<Named>, &mut HashSet<ObjectIdentifier>),
(listed, seen): (&mut Vec<Listed>, &mut HashSet<ObjectIdentifier>),
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) => {
if let Some(a) = o.clone().into_array() {
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<ObjectIdentifier> = 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);
Expand Down Expand Up @@ -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<ObjectIdentifier>, Pixmap)> = None;
let mut on_under: Option<(Vec<ObjectIdentifier>, 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));
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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<bool>, Vec<String>) = (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());
Expand All @@ -430,11 +447,57 @@ fn layers_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, m
let with: Vec<ObjectIdentifier> = 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 {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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::<Vec<_>>().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)?);
}
Expand Down Expand Up @@ -1250,7 +1313,8 @@ mod tests {
let start = std::time::Instant::now();
let names: Vec<String> = 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]
Expand All @@ -1270,13 +1334,66 @@ mod tests {
let (groups, cut) = groups(&pdf);
let names: Vec<String> = 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<String> = (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]
Expand Down
Loading
Loading