mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-10 13:01:29 +00:00
Merge #4396: M2: layers open in the state the view auto state sets, and the Layers panel follows /Order (view.layers-panel)
# Conflicts: # crates/render/src/inspect.rs # crates/render/src/lib.rs # vendor/README.md
This commit is contained in:
commit
0dda66820c
19 files changed
+614
-25
No files matched your search
@@ -334,6 +334,12 @@ pub(crate) fn info(d: &Document) -> Value {
|
||||
"target": link_target(i, &l.target),
|
||||
})).collect::<Vec<_>>(),
|
||||
"layers": i.layers.iter().map(|l| json!({ "name": l.name, "visible": l.visible, "initial": l.initial })).collect::<Vec<_>>(),
|
||||
// The Layers panel's rows, the default configuration's /Order (ISO 32000-2 Table 99): a
|
||||
// layer by its 1-based position in `layers`, or a label; `depth` 0 at the top.
|
||||
"layer_order": i.layer_order.iter().map(|r| match &r.item {
|
||||
pdfcraft_render::LayerItem::Layer(n) => json!({ "depth": r.depth, "layer": n.saturating_add(1), "name": i.layers.get(*n).map(|l| l.name.as_str()) }),
|
||||
pdfcraft_render::LayerItem::Label(s) => json!({ "depth": r.depth, "label": s }),
|
||||
}).collect::<Vec<_>>(),
|
||||
// Full-screen presentation settings a page carries (ISO 32000-2 §12.4.4): only pages with
|
||||
// a `/Trans` or `/Dur` appear; `style` is null for a display time alone.
|
||||
"transitions": i.transitions.iter().map(|t| json!({
|
||||
|
||||
@@ -175,7 +175,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.cmd("file.open")
|
||||
.with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])),
|
||||
t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])),
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, the destination it opens at, attachments, fonts, security, repair notes and the objects that could not be read.")
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers and the Layers panel's tree (layer_order), page transitions and display times, the destination it opens at, attachments, fonts, security, repair notes and the objects that could not be read.")
|
||||
.ro()
|
||||
.cmd("file.properties")
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
|
||||
@@ -9946,6 +9946,38 @@ fn doc_info_describes_set_layer_links() {
|
||||
})
|
||||
);
|
||||
assert_eq!(info["layers"], json!([{ "name": "Red", "visible": true, "initial": true }, { "name": "Green", "visible": false, "initial": false }]));
|
||||
// No /Order: the Layers panel presents none (ISO 32000-2 Table 99), though both are layers.
|
||||
assert_eq!(info["layer_order"], json!([]));
|
||||
}
|
||||
|
||||
/// `doc_info`'s `layer_order` follows the default configuration's /Order (ISO 32000-2 Table 99):
|
||||
/// a group by its 1-based position in `layers` and its name, a nested array one level deeper,
|
||||
/// a label that starts one, and a group /Order does not list left out.
|
||||
#[test]
|
||||
fn doc_info_lists_the_layer_order_tree() {
|
||||
let dir = workdir("layer-order");
|
||||
let pdf = pdf_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [4 0 R 5 0 R 6 0 R 7 0 R] /D << /Order [6 0 R [(Inks) 4 0 R [5 0 R]]] >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>",
|
||||
"<< /Type /OCG /Name (Red) >>",
|
||||
"<< /Type /OCG /Name (Green) >>",
|
||||
"<< /Type /OCG /Name (Blue) >>",
|
||||
"<< /Type /OCG /Name (Unlisted) >>",
|
||||
]);
|
||||
std::fs::write(dir.join("order.pdf"), pdf).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "order.pdf" }))["doc"].as_u64().unwrap();
|
||||
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
|
||||
assert_eq!(
|
||||
info["layer_order"],
|
||||
json!([
|
||||
{ "depth": 0, "layer": 3, "name": "Blue" },
|
||||
{ "depth": 0, "label": "Inks" },
|
||||
{ "depth": 1, "layer": 1, "name": "Red" },
|
||||
{ "depth": 2, "layer": 2, "name": "Green" },
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
mod close_argument_tests {
|
||||
|
||||
@@ -22,6 +22,9 @@ pub fn rasterize(doc: &Document, pages: &[usize], raster: &Raster, content: Cont
|
||||
let mut config = src.config.clone();
|
||||
// The copy below holds only what prints, so the viewer's own comment hiding plays no part.
|
||||
config.hide_comments = false;
|
||||
// Printing is not the View event: a layer the auto state turns off on screen keeps its
|
||||
// configured state on paper, as in a print that goes out as vectors.
|
||||
config.for_print = true;
|
||||
let (printed, layers) = guard(|| -> Result<(Vec<u8>, Option<Vec<pdfcraft_render::Layer>>), String> {
|
||||
let mut cos = pdfcraft_cos::Document::open_with_password(src.bytes.clone(), config.password.as_deref()).map_err(|e| e.to_string())?;
|
||||
pdfcraft_print::keep_printed(&mut cos, content);
|
||||
|
||||
@@ -36,14 +36,16 @@ pub use core::{check_pages, inspect, pretty_date};
|
||||
#[cfg(test)]
|
||||
use core::{inspect_structure, spend};
|
||||
pub use model::{
|
||||
Annotation, Attachment, AttachmentSource, DestView, Field, FieldKind, FontInfo, Layer, LayerOp, Link, LinkTarget, OutlineItem, PageInfo,
|
||||
PageTransition, RemoteDestination, ReviewStates, TransitionStyle, Xfa, link_replies, thread_tops,
|
||||
Annotation, Attachment, AttachmentSource, DestView, Field, FieldKind, FontInfo, Layer, LayerItem, LayerOp, LayerRow, Link, LinkTarget,
|
||||
OutlineItem, PageInfo, PageTransition, RemoteDestination, ReviewStates, TransitionStyle, Xfa, link_replies, thread_tops,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use navigation::{OUTLINE_DEPTH, OUTLINE_WINDOW};
|
||||
#[cfg(test)]
|
||||
use resources::LABEL_DECODES;
|
||||
pub use resources::attachment_data;
|
||||
#[cfg(test)]
|
||||
use resources::{xfa_config_dynamic_render, xfa_packet_text};
|
||||
use resources::{MAX_LAYER_LABEL_CHARS, MAX_LAYER_ORDER_ROWS, xfa_config_dynamic_render, xfa_packet_text};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DocInfo {
|
||||
@@ -74,6 +76,10 @@ pub struct DocInfo {
|
||||
/// Radio-button layer groups (`/OCProperties /D /RBGroups`): turning one layer of a group on
|
||||
/// turns the others off.
|
||||
pub layer_groups: Vec<Vec<(u32, u16)>>,
|
||||
/// The Layers panel's rows: the default configuration's `/Order` (ISO 32000-2 Table 99), a
|
||||
/// tree of layers (indices into `layers`) and labels. A layer it doesn't list isn't presented,
|
||||
/// though it still draws in its state; no `/Order` presents none.
|
||||
pub layer_order: Vec<LayerRow>,
|
||||
pub fonts: Vec<FontInfo>,
|
||||
pub attachments: Vec<Attachment>,
|
||||
/// Pages with a presentation transition (`/Trans`) or display time (`/Dur`), in page order.
|
||||
|
||||
@@ -267,6 +267,7 @@ impl<'a> Inspector<'a> {
|
||||
}
|
||||
self.layers(catalog, &mut info.layers);
|
||||
info.layer_groups = self.layer_groups(catalog);
|
||||
info.layer_order = self.layer_order(catalog, &info.layers);
|
||||
self.fonts(&mut info.fonts);
|
||||
if let Some(names) = catalog.get(b"Names").ok().and_then(|o| self.dict(o)) {
|
||||
if let Some(ef) = names.get(b"EmbeddedFiles").ok().and_then(|o| self.dict(o)) {
|
||||
|
||||
@@ -652,6 +652,23 @@ pub struct Layer {
|
||||
pub initial: bool,
|
||||
}
|
||||
|
||||
/// One row of the Layers panel ([`DocInfo::layer_order`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LayerRow {
|
||||
/// Nesting level, 0 at the top: a nested array's entries are one deeper than the layer or
|
||||
/// label before them.
|
||||
pub depth: usize,
|
||||
pub item: LayerItem,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LayerItem {
|
||||
/// A layer, by its index in [`DocInfo::layers`].
|
||||
Layer(usize),
|
||||
/// A text label heading a nested array: not a layer, so it can't be selected or toggled.
|
||||
Label(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Attachment {
|
||||
pub name: String,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#[cfg(test)]
|
||||
use super::core::inspect;
|
||||
use super::core::{Inspector, load_options};
|
||||
use super::model::{Attachment, AttachmentSource, FontInfo, Layer, PageTransition, TransitionStyle};
|
||||
use super::navigation::NameTreeSeen;
|
||||
use super::{AssertUnwindSafe, Dictionary, DocInfo, Document, HashSet, Object, ObjectId, catch_unwind};
|
||||
use super::model::{Attachment, AttachmentSource, FontInfo, Layer, LayerItem, LayerRow, PageTransition, TransitionStyle};
|
||||
use super::navigation::{NameTreeSeen, text_string};
|
||||
use super::{AssertUnwindSafe, Dictionary, DocInfo, Document, HashMap, HashSet, Object, ObjectId, catch_unwind};
|
||||
|
||||
/// Decoded bytes read from an XFA form's configuration packet (or a whole-XDP `/XFA` stream) to
|
||||
/// find `dynamicRender`. Designer's packets are a few kilobytes; a whole XDP can hold the template.
|
||||
@@ -12,6 +12,25 @@ const MAX_XFA_CONFIG_BYTES: usize = 16 << 20;
|
||||
/// At most this many layers are read from all of `/RBGroups` together.
|
||||
const MAX_LAYER_GROUP_ENTRIES: usize = 4096;
|
||||
|
||||
/// The configuration's auto state (`/AS`): at most this many usage application dictionaries,
|
||||
/// `/OCGs` entries across them, and `/Category` names in each are read. The renderer's
|
||||
/// (vendored hayro-interpret patch (103)) have the same values.
|
||||
const MAX_AUTO_STATE_APPLICATIONS: usize = 256;
|
||||
const MAX_AUTO_STATE_GROUPS: usize = 4096;
|
||||
const MAX_AUTO_STATE_CATEGORIES: usize = 16;
|
||||
|
||||
/// The Layers panel's rows from `/Order`: at most this many rows, nested at most this deep, and
|
||||
/// a label keeps at most this many characters.
|
||||
pub(super) const MAX_LAYER_ORDER_ROWS: usize = 4096;
|
||||
const MAX_LAYER_ORDER_DEPTH: usize = 32;
|
||||
pub(super) const MAX_LAYER_LABEL_CHARS: usize = 256;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Layer labels decoded by [`Inspector::layer_order`] on this thread.
|
||||
pub(super) static LABEL_DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl<'a> Inspector<'a> {
|
||||
// ── object helpers ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -100,11 +119,14 @@ impl<'a> Inspector<'a> {
|
||||
.and_then(|o| self.resolve(o).as_array().ok())
|
||||
.map(|a| a.iter().filter_map(|x| x.as_reference().ok()).collect())
|
||||
.unwrap_or_default();
|
||||
let auto = config.map(|c| self.view_auto_state(c)).unwrap_or_default();
|
||||
let Ok(Object::Array(ocgs)) = props.get(b"OCGs").map(|o| self.resolve(o)) else { return };
|
||||
for g in ocgs {
|
||||
let Some(d) = self.dict(g) else { continue };
|
||||
let id = g.as_reference().ok();
|
||||
// The View auto state, when it manages the group, then the configuration.
|
||||
let visible = match id {
|
||||
Some(id) if let Some(&state) = auto.get(&id) => state,
|
||||
Some(id) if off.contains(&id) => false,
|
||||
Some(id) if on.contains(&id) => true,
|
||||
_ => !base_off,
|
||||
@@ -114,6 +136,129 @@ impl<'a> Inspector<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The state the configuration's auto state (`/AS`) gives each group it manages for the View
|
||||
/// event (ISO 32000-2 §8.11.4.4, Table 101), which overrides `/BaseState`, `/ON` and `/OFF`
|
||||
/// as the document opens. Keep in step with the renderer's (vendored hayro-interpret patch
|
||||
/// (103), `apply_view_auto_state`): each usage application with `/Event /View` and `/View` in
|
||||
/// its `/Category` recommends the `/ViewState` of each group in its `/OCGs` whose `/Usage`
|
||||
/// gives one; a group is on only if all its recommendations are. Groups with none are absent.
|
||||
/// Other categories (`/Zoom`, `/User`, `/Language`) give no recommendation here.
|
||||
fn view_auto_state(&self, config: &Dictionary) -> HashMap<ObjectId, bool> {
|
||||
let mut out: HashMap<ObjectId, bool> = HashMap::new();
|
||||
let Some(applications) = config.get(b"AS").ok().and_then(|o| self.resolve(o).as_array().ok()) else { return out };
|
||||
let mut groups_left = MAX_AUTO_STATE_GROUPS;
|
||||
for application in applications.iter().take(MAX_AUTO_STATE_APPLICATIONS) {
|
||||
let Some(application) = self.dict(application) else { continue };
|
||||
if self.name(application, b"Event").as_deref() != Some("View") {
|
||||
continue;
|
||||
}
|
||||
let views = application.get(b"Category").ok().and_then(|o| self.resolve(o).as_array().ok()).is_some_and(|categories| {
|
||||
categories.iter().take(MAX_AUTO_STATE_CATEGORIES).any(|c| matches!(c, Object::Name(n) if n.as_slice() == b"View"))
|
||||
});
|
||||
if !views {
|
||||
continue;
|
||||
}
|
||||
let Some(groups) = application.get(b"OCGs").ok().and_then(|o| self.resolve(o).as_array().ok()) else { continue };
|
||||
for g in groups {
|
||||
if groups_left == 0 {
|
||||
return out;
|
||||
}
|
||||
groups_left -= 1;
|
||||
let Ok(id) = g.as_reference() else { continue };
|
||||
let state = self
|
||||
.dict(g)
|
||||
.and_then(|d| d.get(b"Usage").ok())
|
||||
.and_then(|o| self.dict(o))
|
||||
.and_then(|u| u.get(b"View").ok())
|
||||
.and_then(|o| self.dict(o))
|
||||
.and_then(|v| self.name(v, b"ViewState"));
|
||||
let on = match state.as_deref() {
|
||||
Some("ON") => true,
|
||||
Some("OFF") => false,
|
||||
_ => continue,
|
||||
};
|
||||
let entry = out.entry(id).or_insert(true);
|
||||
*entry &= on;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The Layers panel's rows: the default configuration's `/Order` (ISO 32000-2 Table 99). Its
|
||||
/// entries are groups, shown by name, and nested arrays, shown as a tree one level deeper;
|
||||
/// a nested array may start with a text string, a label that is not a group. Groups not
|
||||
/// listed aren't presented, and `/Order` defaults to the empty array in the default
|
||||
/// configuration, so a document without one presents no layers. An entry that is neither a
|
||||
/// group in `/OCGs` nor an array is skipped. Bounded by `MAX_LAYER_ORDER_*`, an indirect
|
||||
/// array is read once, so a cycle ends, and an indirect label is decoded once, however many
|
||||
/// arrays it heads.
|
||||
pub(super) fn layer_order(&self, catalog: &Dictionary, layers: &[Layer]) -> Vec<LayerRow> {
|
||||
let mut out = Vec::new();
|
||||
let Some(config) = catalog.get(b"OCProperties").ok().and_then(|o| self.dict(o)).and_then(|p| p.get(b"D").ok()).and_then(|o| self.dict(o))
|
||||
else {
|
||||
return out;
|
||||
};
|
||||
let Some(order) = config.get(b"Order").ok() else { return out };
|
||||
let index: HashMap<ObjectId, usize> = layers.iter().enumerate().map(|(i, l)| ((l.id.0, l.id.1), i)).collect();
|
||||
let mut seen = HashSet::new();
|
||||
if let Object::Reference(id) = order {
|
||||
seen.insert(*id);
|
||||
}
|
||||
if let Ok(items) = self.resolve(order).as_array() {
|
||||
self.layer_order_rows(items, 0, &index, &mut seen, &mut HashMap::new(), &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `labels` holds each indirect label already decoded: one string object can head any
|
||||
/// number of direct arrays, and each decode costs its full length before the cut.
|
||||
fn layer_order_rows(
|
||||
&self,
|
||||
items: &'a [Object],
|
||||
depth: usize,
|
||||
index: &HashMap<ObjectId, usize>,
|
||||
seen: &mut HashSet<ObjectId>,
|
||||
labels: &mut HashMap<ObjectId, String>,
|
||||
out: &mut Vec<LayerRow>,
|
||||
) {
|
||||
if depth > MAX_LAYER_ORDER_DEPTH {
|
||||
return;
|
||||
}
|
||||
for item in items {
|
||||
if out.len() >= MAX_LAYER_ORDER_ROWS {
|
||||
return;
|
||||
}
|
||||
if let Object::Reference(id) = item {
|
||||
if let Some(&layer) = index.get(id) {
|
||||
out.push(LayerRow { depth, item: LayerItem::Layer(layer) });
|
||||
continue;
|
||||
}
|
||||
// An indirect nested array, read once.
|
||||
if !seen.insert(*id) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Ok(nested) = self.resolve(item).as_array() else { continue };
|
||||
let rest = match nested.split_first() {
|
||||
Some((first, rest)) if let Object::String(bytes, _) = self.resolve(first) => {
|
||||
let decode = || {
|
||||
#[cfg(test)]
|
||||
LABEL_DECODES.with(|n| n.set(n.get().saturating_add(1)));
|
||||
text_string(bytes).chars().take(MAX_LAYER_LABEL_CHARS).collect::<String>()
|
||||
};
|
||||
let label = match first {
|
||||
Object::Reference(id) => labels.entry(*id).or_insert_with(decode).clone(),
|
||||
_ => decode(),
|
||||
};
|
||||
out.push(LayerRow { depth, item: LayerItem::Label(label) });
|
||||
rest
|
||||
}
|
||||
_ => nested.as_slice(),
|
||||
};
|
||||
self.layer_order_rows(rest, depth.saturating_add(1), index, seen, labels, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The default configuration's radio-button groups (`/RBGroups`) of two or more layers.
|
||||
pub(super) fn layer_groups(&self, catalog: &Dictionary) -> Vec<Vec<ObjectId>> {
|
||||
let groups = catalog
|
||||
|
||||
@@ -769,6 +769,103 @@ trailer << /Root 1 0 R >>
|
||||
assert_eq!(layers, [("Red", true), ("Green", false), ("Blue", false)]);
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 99 `/Order`: the Layers panel presents the groups it lists, as a tree,
|
||||
/// with nested arrays one level deeper and a leading text string as a label. Groups it
|
||||
/// doesn't list are not presented (they stay in `layers` and keep their state), and without
|
||||
/// `/Order` none are. Malformed entries are skipped; cycles and depth are bounded.
|
||||
#[test]
|
||||
fn the_layers_panel_presents_the_order_tree() {
|
||||
let rows = |order: &str, extra: &str| {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R 8 0 R] /D << /OFF [8 0 R] {order} >> >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >> endobj
|
||||
5 0 obj << /Type /OCG /Name (A) >> endobj
|
||||
6 0 obj << /Type /OCG /Name (B) >> endobj
|
||||
7 0 obj << /Type /OCG /Name (C) >> endobj
|
||||
8 0 obj << /Type /OCG /Name (D) >> endobj
|
||||
9 0 obj << /Type /OCG /Name (Unlisted) >> endobj
|
||||
{extra}
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF"
|
||||
);
|
||||
let info = inspect(Arc::new(pdf.into_bytes()), None).expect("opens");
|
||||
assert_eq!(info.layers.len(), 4, "every group in /OCGs keeps its state: {order}");
|
||||
info.layer_order
|
||||
.iter()
|
||||
.map(|r| match &r.item {
|
||||
LayerItem::Layer(i) => format!("{}{}", " ".repeat(r.depth), info.layers.get(*i).map_or("?", |l| l.name.as_str())),
|
||||
LayerItem::Label(s) => format!("{}[{s}]", " ".repeat(r.depth)),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// A layer with sublayers, and a group not listed (D) that isn't presented.
|
||||
assert_eq!(rows("/Order [5 0 R 6 0 R [7 0 R]]", ""), ["A", "B", " C"]);
|
||||
// A labelled collection heads its own level, with a nested array under B.
|
||||
assert_eq!(rows("/Order [5 0 R [(Set) 6 0 R [7 0 R]] 8 0 R]", ""), ["A", "[Set]", " B", " C", "D"]);
|
||||
// Without /Order, or with an empty one, nothing is presented.
|
||||
assert!(rows("", "").is_empty());
|
||||
assert!(rows("/Order []", "").is_empty());
|
||||
// An indirect /Order and nested array; a group outside /OCGs, a missing object and junk
|
||||
// are skipped.
|
||||
assert_eq!(rows("/Order 10 0 R", "10 0 obj [5 0 R 11 0 R 9 0 R 12 0 R 1 (x) /N] endobj\n11 0 obj [6 0 R] endobj"), ["A", " B"]);
|
||||
// Cycles: an array holding itself, and an /Order holding itself.
|
||||
assert_eq!(rows("/Order 10 0 R", "10 0 obj [5 0 R 10 0 R 11 0 R] endobj\n11 0 obj [6 0 R 11 0 R 10 0 R] endobj"), ["A", " B"]);
|
||||
// Nesting past the limit is cut off; a long label is cut short.
|
||||
let deep = format!("/Order [5 0 R {}6 0 R{}]", "[".repeat(40), "]".repeat(40));
|
||||
assert_eq!(rows(&deep, ""), ["A"]);
|
||||
let long = format!("/Order [[({}) 5 0 R]]", "x".repeat(1000));
|
||||
let got = rows(&long, "");
|
||||
assert_eq!(got.first().map(|s| s.len()), Some(MAX_LAYER_LABEL_CHARS + 2));
|
||||
// Many rows stop at the cap.
|
||||
let many = format!("/Order [{}]", "5 0 R ".repeat(MAX_LAYER_ORDER_ROWS + 10));
|
||||
assert_eq!(rows(&many, "").len(), MAX_LAYER_ORDER_ROWS);
|
||||
// One long indirect label heading many direct arrays is decoded once, and cut short in
|
||||
// every row.
|
||||
let shared = format!("/Order [{}]", "[13 0 R 5 0 R] ".repeat(100));
|
||||
let label = format!("13 0 obj ({}) endobj", "y".repeat(10_000));
|
||||
let before = LABEL_DECODES.with(std::cell::Cell::get);
|
||||
let got = rows(&shared, &label);
|
||||
assert_eq!(LABEL_DECODES.with(std::cell::Cell::get) - before, 1);
|
||||
assert_eq!(got.len(), 200);
|
||||
assert!(got.iter().step_by(2).all(|s| s.len() == MAX_LAYER_LABEL_CHARS + 2), "{:?}", got.first());
|
||||
}
|
||||
|
||||
/// ISO 32000-2 §8.11.4.4: the View auto state (`/AS`) decides the initial state of the groups
|
||||
/// it manages, over `/ON` and `/OFF`; the others keep the configuration's. Malformed entries
|
||||
/// are ignored.
|
||||
#[test]
|
||||
fn initial_layer_visibility_applies_the_view_auto_state() {
|
||||
let initial = |config: &str| {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R] /D {config} >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >> endobj
|
||||
5 0 obj << /Type /OCG /Name (ViewOff) /Usage << /View << /ViewState /OFF >> >> >> endobj
|
||||
6 0 obj << /Type /OCG /Name (ViewOn) /Usage 8 0 R >> endobj
|
||||
7 0 obj << /Type /OCG /Name (Plain) >> endobj
|
||||
8 0 obj << /View << /ViewState /ON >> >> endobj
|
||||
9 0 obj 9 0 R endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF"
|
||||
);
|
||||
let info = inspect(Arc::new(pdf.into_bytes()), None).expect("opens");
|
||||
// Opened, so each is shown as it starts.
|
||||
info.layers.iter().inspect(|l| assert_eq!(l.initial, l.visible, "{}", l.name)).map(|l| l.initial).collect::<Vec<_>>()
|
||||
};
|
||||
let managed = "/AS [<< /Event /View /Category [/View] /OCGs [5 0 R 6 0 R 7 0 R] >>]";
|
||||
assert_eq!(initial(&format!("<< /OFF [6 0 R 7 0 R] {managed} >>")), [false, true, false]);
|
||||
assert_eq!(initial("<< /OFF [6 0 R 7 0 R] >>"), [true, false, false], "without /AS");
|
||||
assert_eq!(initial("<< /OFF [6 0 R] /AS [<< /Event /Print /Category [/View] /OCGs [5 0 R 6 0 R] >>] >>"), [true, false, true], "Print event");
|
||||
assert_eq!(initial("<< /AS [<< /Event /View /Category [/Zoom] /OCGs [5 0 R] >>] >>"), [true, true, true], "Zoom only");
|
||||
for bad in ["/AS 9 0 R", "/AS [9 0 R 1 null]", "/AS [<< /Event /View /OCGs [5 0 R] >>]", "/AS [<< /Event /View /Category [/View] /OCGs 9 0 R >>]"]
|
||||
{
|
||||
assert_eq!(initial(&format!("<< {bad} >>")), [true, true, true], "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
const ORPHAN_FIELDS: &[u8] = b"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
|
||||
@@ -18,9 +18,9 @@ pub mod text;
|
||||
pub mod transition;
|
||||
|
||||
pub use inspect::{
|
||||
Annotation, Attachment, AttachmentSource, DestView, DocInfo, Field, FieldKind, FontInfo, Layer, LayerOp, Link, LinkTarget, OutlineItem, PageInfo,
|
||||
PageTransition, RemoteDestination, ReviewStates, TransitionStyle, Xfa, attachment_data, check_pages, inspect, link_replies, pretty_date,
|
||||
thread_tops,
|
||||
Annotation, Attachment, AttachmentSource, DestView, DocInfo, Field, FieldKind, FontInfo, Layer, LayerItem, LayerOp, LayerRow, Link, LinkTarget,
|
||||
OutlineItem, PageInfo, PageTransition, RemoteDestination, ReviewStates, TransitionStyle, Xfa, attachment_data, check_pages, inspect,
|
||||
link_replies, pretty_date, thread_tops,
|
||||
};
|
||||
pub use pixels::Pixels;
|
||||
pub use raster::{
|
||||
|
||||
@@ -83,6 +83,9 @@ pub struct RenderConfig {
|
||||
/// viewer and preview rasters: exports, printing and OCR render without it, so nothing drawn with an
|
||||
/// installed font is saved or printed (AGENTS.md §1.2, §1.4).
|
||||
pub system_fonts: bool,
|
||||
/// The render is output for printing (print as image): the configuration's auto state for
|
||||
/// the View event (ISO 32000-2 §8.11.4.4) is not applied, since printing is not viewing.
|
||||
pub for_print: bool,
|
||||
/// Steps of JBIG2 decoding a render may take across the page's images, instead of the usual
|
||||
/// `hayro_syntax::MAX_PAGE_JBIG2_WORK`. Those past it aren't drawn, like an image that can't
|
||||
/// be decoded.
|
||||
@@ -113,6 +116,7 @@ impl RenderConfig {
|
||||
let system_fonts = self.system_fonts;
|
||||
InterpreterSettings {
|
||||
ocg_overrides: self.layers.clone(),
|
||||
view_auto_state: !self.for_print,
|
||||
hide_comments: self.hide_comments,
|
||||
font_resolver: Arc::new(move |query| {
|
||||
japanese_fallback(query).or_else(|| system_fonts.then(|| system_fallback(query)).flatten()).or_else(|| standard(query))
|
||||
@@ -461,6 +465,8 @@ fn render_page<'a>(
|
||||
// Previews render at low detail (tiny images are skipped); finals always draw all.
|
||||
let mut preview_settings = settings.clone();
|
||||
preview_settings.preview = req.preview;
|
||||
// A print preview shows what prints, and printing is not the View event.
|
||||
preview_settings.view_auto_state &= req.tag & PRINT_TAG == 0;
|
||||
render_into(page, cache, &preview_settings, &rs, pixels.bytes_mut());
|
||||
Ok((w.into(), h.into(), pixels, None))
|
||||
}));
|
||||
|
||||
@@ -2888,6 +2888,126 @@ trailer << /Root 1 0 R >>
|
||||
assert_eq!(px(off), vec![255, 255, 255, 255], "toggled-off layer must not draw");
|
||||
}
|
||||
|
||||
/// A page whose red square is in group 5 0 R (`ocg` its dictionary), under the default
|
||||
/// configuration `config`; `extra` adds objects from number 8.
|
||||
fn auto_state_pdf(ocg: &str, config: &str, extra: &str) -> Vec<u8> {
|
||||
format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R] /D {config} >> >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << /Properties << /L1 5 0 R >> >> >> endobj
|
||||
4 0 obj << /Length 44 >> stream
|
||||
/OC /L1 BDC 1 0 0 rg 0 0 100 100 re f EMC
|
||||
endstream endobj
|
||||
5 0 obj {ocg} endobj
|
||||
{extra}
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF"
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// Whether the red square in group 5 0 R draws.
|
||||
fn auto_state_red(pdf: Vec<u8>, config: RenderConfig) -> bool {
|
||||
let mut r = PageRenderer::new(Arc::new(pdf), config);
|
||||
let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 0.5, tag: 0, ..Default::default() });
|
||||
p.rgba.get(..4) == Some(&[255, 0, 0, 255][..])
|
||||
}
|
||||
|
||||
const VIEW_OFF: &str = "<< /Type /OCG /Name (A) /Usage << /View << /ViewState /OFF >> >> >>";
|
||||
const VIEW_ON: &str = "<< /Type /OCG /Name (A) /Usage << /View << /ViewState /ON >> >> >>";
|
||||
const AS_VIEW: &str = "/AS [<< /Event /View /Category [/View] /OCGs [5 0 R] >>]";
|
||||
|
||||
/// ISO 32000-2 §8.11.4.4: the configuration's auto state (`/AS`) sets a group's state for
|
||||
/// the View event from its usage, over `/BaseState`, `/ON` and `/OFF`. It was ignored, so a
|
||||
/// group whose `/ViewState` is OFF still drew on screen.
|
||||
#[test]
|
||||
fn the_view_auto_state_sets_a_groups_state_on_screen() {
|
||||
let shown = |ocg: &str, config: &str| auto_state_red(auto_state_pdf(ocg, config, ""), RenderConfig::default());
|
||||
assert!(!shown(VIEW_OFF, &format!("<< {AS_VIEW} >>")), "ViewState OFF, managed: hidden");
|
||||
assert!(shown(VIEW_OFF, "<< >>"), "no /AS: the usage alone changes nothing");
|
||||
assert!(shown(VIEW_OFF, "<< /AS [<< /Event /View /Category [/View] /OCGs [] >>] >>"), "not listed in /OCGs");
|
||||
assert!(shown(VIEW_ON, &format!("<< /OFF [5 0 R] {AS_VIEW} >>")), "ViewState ON wins over /OFF");
|
||||
assert!(shown(VIEW_ON, &format!("<< /BaseState /OFF {AS_VIEW} >>")), "and over /BaseState /OFF");
|
||||
assert!(!shown(VIEW_ON, "<< /OFF [5 0 R] >>"), "without /AS, /OFF decides");
|
||||
// The View event only, and the View category only.
|
||||
assert!(shown(VIEW_OFF, "<< /AS [<< /Event /Print /Category [/View] /OCGs [5 0 R] >>] >>"), "Print event: not on screen");
|
||||
assert!(shown(VIEW_OFF, "<< /AS [<< /Event /Export /Category [/View] /OCGs [5 0 R] >>] >>"), "Export event: not on screen");
|
||||
assert!(shown(VIEW_OFF, "<< /AS [<< /Event /View /Category [/Print] /OCGs [5 0 R] >>] >>"), "a category without a View entry");
|
||||
// A category it cannot evaluate gives no recommendation; the View one still applies.
|
||||
assert!(!shown(VIEW_OFF, "<< /AS [<< /Event /View /Category [/Zoom /View] /OCGs [5 0 R] >>] >>"), "Zoom alongside View");
|
||||
let zoomed = "<< /Type /OCG /Name (A) /Usage << /Zoom << /min 4 >> >> >>";
|
||||
assert!(shown(zoomed, "<< /AS [<< /Event /View /Category [/Zoom] /OCGs [5 0 R] >>] >>"), "Zoom alone: unchanged");
|
||||
// Indirect applications, arrays and usage dictionaries are followed.
|
||||
let indirect = "<< /Type /OCG /Name (A) /Usage 10 0 R >>";
|
||||
let extra = "8 0 obj [9 0 R] endobj\n9 0 obj << /Event /View /Category [/View] /OCGs 11 0 R >> endobj\n10 0 obj << /View << /ViewState /OFF >> >> endobj\n11 0 obj [5 0 R] endobj";
|
||||
assert!(!auto_state_red(auto_state_pdf(indirect, "<< /AS 8 0 R >>", extra), RenderConfig::default()), "indirect");
|
||||
}
|
||||
|
||||
/// The Layers panel's toggles still decide over the auto state, and a render for printing
|
||||
/// does not apply it (printing is not the View event).
|
||||
#[test]
|
||||
fn layer_toggles_and_print_renders_are_not_the_view_auto_state() {
|
||||
let pdf = auto_state_pdf(VIEW_OFF, &format!("<< {AS_VIEW} >>"), "");
|
||||
let on = RenderConfig { layers: Arc::new(vec![(5, 0, true)]), ..Default::default() };
|
||||
assert!(auto_state_red(pdf.clone(), on), "toggled on in the Layers panel");
|
||||
assert!(auto_state_red(pdf.clone(), RenderConfig { for_print: true, ..Default::default() }), "printed: its configured state");
|
||||
assert!(!auto_state_red(pdf, RenderConfig::default()), "on screen: hidden");
|
||||
}
|
||||
|
||||
/// A print preview ([`PRINT_TAG`], with or without the canvas's scale and grayscale bits)
|
||||
/// shows what prints, so the View auto state is not applied to it either.
|
||||
#[test]
|
||||
fn print_previews_are_not_the_view_auto_state() {
|
||||
let pdf = Arc::new(auto_state_pdf(VIEW_OFF, &format!("<< {AS_VIEW} >>"), ""));
|
||||
let mut r = PageRenderer::new(pdf, RenderConfig::default());
|
||||
for tag in [PRINT_TAG, PRINT_TAG | 1 << 59 | 7] {
|
||||
let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 0.5, tag, ..Default::default() });
|
||||
assert_eq!(p.rgba.get(..4), Some(&[255, 0, 0, 255][..]), "tag {tag:#x}: printed state");
|
||||
}
|
||||
let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 0.5, tag: 7, ..Default::default() });
|
||||
assert_ne!(p.rgba.get(..4), Some(&[255, 0, 0, 255][..]), "on screen: hidden");
|
||||
}
|
||||
|
||||
/// Malformed auto state is ignored without a panic, and the walk is bounded.
|
||||
#[test]
|
||||
fn malformed_view_auto_state_is_ignored() {
|
||||
let shown = |config: &str, extra: &str| auto_state_red(auto_state_pdf(VIEW_OFF, config, extra), RenderConfig::default());
|
||||
for config in [
|
||||
"<< /AS 5 >>",
|
||||
"<< /AS << /Event /View /Category [/View] /OCGs [5 0 R] >> >>",
|
||||
"<< /AS [1 null /x (s) [5 0 R]] >>",
|
||||
"<< /AS [<< /Event /View /Category [/View] >>] >>",
|
||||
"<< /AS [<< /Event /View /OCGs [5 0 R] >>] >>",
|
||||
"<< /AS [<< /Category [/View] /OCGs [5 0 R] >>] >>",
|
||||
"<< /AS [<< /Event (View) /Category [/View] /OCGs [5 0 R] >>] >>",
|
||||
"<< /AS [<< /Event /View /Category /View /OCGs [5 0 R] >>] >>",
|
||||
"<< /AS [<< /Event /View /Category [/View] /OCGs 5 0 R >>] >>",
|
||||
"<< /AS [<< /Event /View /Category [/View] /OCGs [(5) 5 /OCG] >>] >>",
|
||||
] {
|
||||
assert!(shown(config, ""), "{config}: ignored");
|
||||
}
|
||||
let bad_state = |s: &str| {
|
||||
let ocg = format!("<< /Type /OCG /Name (A) /Usage << /View << /ViewState {s} >> >> >>");
|
||||
auto_state_red(auto_state_pdf(&ocg, &format!("<< {AS_VIEW} >>"), ""), RenderConfig::default())
|
||||
};
|
||||
for s in ["/Off", "(OFF)", "0", "null", "[/OFF]"] {
|
||||
assert!(bad_state(s), "ViewState {s}: no recommendation");
|
||||
}
|
||||
// Cyclic references: an /AS, an application and a usage that refer to themselves.
|
||||
assert!(shown("<< /AS 8 0 R >>", "8 0 obj 8 0 R endobj"), "self-referencing /AS");
|
||||
assert!(shown("<< /AS [8 0 R] >>", "8 0 obj 8 0 R endobj"), "self-referencing application");
|
||||
let cyclic = "<< /Type /OCG /Name (A) /Usage 8 0 R >>";
|
||||
assert!(auto_state_red(auto_state_pdf(cyclic, &format!("<< {AS_VIEW} >>"), "8 0 obj 8 0 R endobj"), RenderConfig::default()));
|
||||
// Huge arrays: the group listed after 4096 other entries is past the cap.
|
||||
let many = format!("<< /AS [<< /Event /View /Category [/View] /OCGs [{}5 0 R] >>] >>", "9 0 R ".repeat(4096));
|
||||
assert!(shown(&many, "9 0 obj << /Type /OCG /Name (B) >> endobj"), "past the cap: unchanged");
|
||||
let within = format!("<< /AS [<< /Event /View /Category [/View] /OCGs [{}5 0 R] >>] >>", "9 0 R ".repeat(4095));
|
||||
assert!(!shown(&within, "9 0 obj << /Type /OCG /Name (B) >> endobj"), "within the cap: applied");
|
||||
let apps = format!("<< /AS [{}<< /Event /View /Category [/View] /OCGs [5 0 R] >>] >>", "<< /Event /Print >> ".repeat(256));
|
||||
assert!(shown(&apps, ""), "past the application cap: unchanged");
|
||||
}
|
||||
|
||||
/// #2986: an optional content membership dictionary with a visibility expression (`/VE`,
|
||||
/// ISO 32000-2 §8.11.2.2) shows its content only when the expression is true, and the
|
||||
/// expression takes precedence over `/OCGs` and `/P`. It was ignored, so content under it
|
||||
|
||||
@@ -49,7 +49,9 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
RightPanel::Bookmarks => ("Bookmarks", None),
|
||||
RightPanel::Pages => ("Pages", Some(info.pages.len())),
|
||||
RightPanel::Fields => ("Fields", Some(info.fields.len())),
|
||||
RightPanel::Layers => ("Layers", Some(info.layers.len())),
|
||||
RightPanel::Layers => {
|
||||
("Layers", Some(info.layer_order.iter().filter(|r| matches!(r.item, pdfcraft_render::LayerItem::Layer(_))).count()))
|
||||
}
|
||||
RightPanel::Attachments => ("Attachments", Some(info.attachments.len())),
|
||||
RightPanel::Signatures => ("Signatures", Some(doc.signatures.iter().filter(|s| s.signed).count())),
|
||||
RightPanel::Accessibility => ("Accessibility Checker", None),
|
||||
@@ -234,8 +236,31 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
RightPanel::Layers => {
|
||||
if info.layers.is_empty() {
|
||||
empty(ui, &t, "layers", "This document has no layers.");
|
||||
} else if info.layer_order.is_empty() {
|
||||
// ISO 32000-2 Table 99: only the groups /Order lists are presented.
|
||||
empty(ui, &t, "layers", "This document lists no layers to show.");
|
||||
}
|
||||
for (li, l) in info.layers.iter().enumerate() {
|
||||
// The default configuration's /Order, as a tree: a level is indented
|
||||
// 16 points, up to eight levels; a label is a heading, not a layer.
|
||||
for row in &info.layer_order {
|
||||
let indent = 16.0 * row.depth.min(8) as f32;
|
||||
let li = match &row.item {
|
||||
pdfcraft_render::LayerItem::Layer(li) => *li,
|
||||
pdfcraft_render::LayerItem::Label(label) => {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 28.0), Sense::hover());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, label));
|
||||
crate::widgets::paint_left(
|
||||
ui,
|
||||
rect.left_center() + vec2(8.0 + indent, 0.0),
|
||||
label,
|
||||
theme::medium(12.0),
|
||||
t.text_faint,
|
||||
(rect.width() - 12.0 - indent).max(0.0),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(l) = info.layers.get(li) else { continue };
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 32.0), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, l.visible, &l.name));
|
||||
let press = theme::Press::track(ui, &resp);
|
||||
@@ -243,7 +268,7 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
let body = rect.translate(press.offset());
|
||||
icons::paint(
|
||||
ui,
|
||||
Rect::from_min_size(body.min + vec2(4.0, 7.0), vec2(18.0, 18.0)),
|
||||
Rect::from_min_size(body.min + vec2(4.0 + indent, 7.0), vec2(18.0, 18.0)),
|
||||
if l.visible { "eye" } else { "eye-off" },
|
||||
16.0,
|
||||
t.icon,
|
||||
@@ -251,11 +276,11 @@ pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
|
||||
let fg = if l.visible { t.text } else { t.text_faint };
|
||||
crate::widgets::paint_left(
|
||||
ui,
|
||||
body.left_center() + vec2(32.0, 0.0),
|
||||
body.left_center() + vec2(32.0 + indent, 0.0),
|
||||
&l.name,
|
||||
theme::regular(13.0),
|
||||
fg,
|
||||
(rect.width() - 40.0).max(0.0),
|
||||
(rect.width() - 40.0 - indent).max(0.0),
|
||||
);
|
||||
if theme::hand(resp).on_hover_text(if l.visible { tl!("Hide layer") } else { tl!("Show layer") }).clicked() {
|
||||
toggle_layer = Some((li, !l.visible));
|
||||
|
||||
@@ -9,9 +9,14 @@ use pdfcraft_ui_egui::PdfCraftApp;
|
||||
/// One page with layers Red (on) and Green (off), a radio-button group, each drawing a band;
|
||||
/// a "show-red" push button turns Red on and a link toggles Green.
|
||||
fn fixture() -> Vec<u8> {
|
||||
fixture_with("")
|
||||
}
|
||||
|
||||
/// [`fixture`] with `order` added to the default configuration.
|
||||
fn fixture_with(order: &str) -> Vec<u8> {
|
||||
let content = "/OC /R BDC 1 0 0 rg 20 300 260 40 re f EMC /OC /G BDC 0 1 0 rg 20 240 260 40 re f EMC";
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [7 0 R] >> /OCProperties << /OCGs [5 0 R 6 0 R] /D << /OFF [6 0 R] /RBGroups [[5 0 R 6 0 R]] >> >> >>".to_string(),
|
||||
format!("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [7 0 R] >> /OCProperties << /OCGs [5 0 R 6 0 R] /D << /OFF [6 0 R] /RBGroups [[5 0 R 6 0 R]] {order} >> >> >>"),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] /Contents 4 0 R /Resources << /Properties << /R 5 0 R /G 6 0 R >> >> /Annots [7 0 R 8 0 R] >>".into(),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||||
@@ -36,10 +41,14 @@ fn fixture() -> Vec<u8> {
|
||||
}
|
||||
|
||||
fn harness(setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> {
|
||||
harness_with(fixture(), setup)
|
||||
}
|
||||
|
||||
fn harness_with(pdf: Vec<u8>, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
|
||||
let mut app = PdfCraftApp::new();
|
||||
app.set_option("language", "en").unwrap();
|
||||
app.open_bytes("layers.pdf", None, fixture()).unwrap();
|
||||
app.open_bytes("layers.pdf", None, pdf).unwrap();
|
||||
app.set_option("zoom", "150").unwrap();
|
||||
setup(&mut app);
|
||||
app
|
||||
@@ -124,3 +133,28 @@ fn layer_options_reset_to_initial_visibility() {
|
||||
assert!(!doc.dirty, "showing and hiding layers doesn't change the document");
|
||||
assert_eq!(doc.can_undo(), None, "nor is it an edit to undo");
|
||||
}
|
||||
|
||||
/// ISO 32000-2 Table 99 `/Order`: the Layers panel shows the tree it gives, a leading text
|
||||
/// string as a label, and not the groups it leaves out, which still draw in their state. Without
|
||||
/// `/Order` it presents none.
|
||||
#[test]
|
||||
fn the_layers_panel_shows_the_order_tree() {
|
||||
let mut h = harness_with(fixture_with("/Order [[(Colours) 5 0 R]]"), |app| app.set_option("panel", "layers").unwrap());
|
||||
h.run_steps(2);
|
||||
let label = h.get_by_label("Colours").rect();
|
||||
let red = h.get_by_label("Red").rect();
|
||||
assert!(red.min.y > label.max.y - 1.0, "Red is listed under its label");
|
||||
assert!(h.query_by_label("Green").is_none(), "Green isn't in /Order, so it isn't presented");
|
||||
assert_eq!(shown(&h), layers(true, false), "but it is still a layer, in its state");
|
||||
// Clicking the label changes nothing; clicking Red hides it.
|
||||
h.get_by_label("Colours").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(shown(&h), layers(true, false));
|
||||
h.get_by_label("Red").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(shown(&h), layers(false, false));
|
||||
|
||||
let h = harness(|app| app.set_option("panel", "layers").unwrap());
|
||||
assert!(h.query_by_label("Red").is_none() && h.query_by_label("Green").is_none(), "no /Order: none presented");
|
||||
h.get_by_label("This document lists no layers to show.");
|
||||
}
|
||||
@@ -1346,8 +1346,8 @@ milestone = "M3"
|
||||
status = "shipped"
|
||||
commands = []
|
||||
tools = ["doc_info", "layer_set"]
|
||||
evidence = ["crates/render/src/raster/tests.rs::layer_override_hides_content", "crates/engine/src/tests.rs::layer_choices_survive_edits", "crates/automation/tests/it/automation.rs::layers_and_hidden_comments_change_what_page_render_draws"]
|
||||
notes = "layer_set shows or hides a layer by name (every group with that name, as CAD exporters repeat names) or by position, and page_render draws with the document's layer visibility. Still missing: Reset to initial visibility (view.layers-reset), layer properties, and /OC on annotations (#2176)."
|
||||
evidence = ["crates/render/src/raster/tests.rs::layer_override_hides_content", "crates/engine/src/tests.rs::layer_choices_survive_edits", "crates/automation/tests/it/automation.rs::layers_and_hidden_comments_change_what_page_render_draws", "crates/render/src/raster/tests.rs::the_view_auto_state_sets_a_groups_state_on_screen", "crates/render/src/raster/tests.rs::layer_toggles_and_print_renders_are_not_the_view_auto_state", "crates/render/src/raster/tests.rs::malformed_view_auto_state_is_ignored", "crates/render/src/inspect/tests.rs::the_layers_panel_presents_the_order_tree", "crates/ui-egui/tests/it/layer_actions.rs::the_layers_panel_shows_the_order_tree"]
|
||||
notes = "layer_set shows or hides a layer by name (every group with that name, as CAD exporters repeat names) or by position, and page_render draws with the document's layer visibility. Still missing: Reset to initial visibility (view.layers-reset), layer properties, and /OC on annotations (#2176). The default configuration's auto state for the View event (/AS, ISO 32000-2 8.11.4.4) sets the groups it manages from their /Usage /View /ViewState as the document opens, on screen and in the panel, and toggles still override it; renders for printing and print previews don't apply it; printing takes the Print event's auto state instead (print.print-ready-pdf). Not yet: the /Zoom, /User and /Language categories. The panel presents the default configuration's /Order (ISO 32000-2 Table 99) as a tree: a nested array one level deeper, a leading text string as a label that can't be toggled. Groups /Order leaves out aren't listed but still draw in their state, and a document without /Order lists none, the default Table 99 gives; doc_info reports the rows as layer_order. Not yet: /ListMode /VisiblePages."
|
||||
|
||||
[[feature]]
|
||||
id = "view.layers-reset"
|
||||
@@ -1358,7 +1358,7 @@ milestone = "M12"
|
||||
status = "partial"
|
||||
commands = []
|
||||
tools = ["doc_info"]
|
||||
evidence = ["crates/engine/src/tests.rs::reset_layers_returns_to_the_files_visibility", "crates/render/src/inspect/tests.rs::initial_layer_visibility_is_the_default_configuration"]
|
||||
evidence = ["crates/engine/src/tests.rs::reset_layers_returns_to_the_files_visibility", "crates/render/src/inspect/tests.rs::initial_layer_visibility_is_the_default_configuration", "crates/render/src/inspect/tests.rs::initial_layer_visibility_applies_the_view_auto_state"]
|
||||
notes = "Layers panel ▸ Layer options ▸ Reset to Initial Visibility shows each layer as the default configuration (/OCProperties /D) has it; doc_info reports it as `initial`. Not yet: listing the layers of all pages or the current page only."
|
||||
|
||||
[[feature]]
|
||||
|
||||
Vendored
+1
-1
@@ -39,7 +39,7 @@ Other resource categories retain their existing parent-chain lookup.
|
||||
|
||||
| Crate | Version | Licence | Patches | Test |
|
||||
|---|---|---|---|---|
|
||||
| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.nLine truncated
|
||||
| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.nLine truncated
|
||||
| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour (since (21), only inside Type 3 glyphs), planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk image that is interpolated (or, since (21), area-averaged) and whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle (halves round up, so a tile snaps an edge where the whole page does) and drawn 1:1 from the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroLine truncated
|
||||
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (11) `Image::decode_within` spends from what a run of images may still do, starting with its page's pixels, and `charge_reading` charges reading a stream and its globals before anything is parsed, so an operation over a document can bound what `MAX_WORK` bounds for one image, and images that fail or decode nothing add up too: a file of thousands of images made to reach that limit took as many times as long; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change; (13) a bitmap filled with a default pixel of 1 (a page, or an intermediate text or halftone region) had 1s past its width in the last word of each row, and a refinement, which reads its reference a word at a time, read them as pixels where the standard has 0 (6.3.5.2): refining such a reference not a multiple of 32 wide decoded to other pixels than were coded, release builds too. `Bitmap::clear_padding` clears those bits when a bitmap is filled with 1s, as cutting symbols and patterns from a collective bitmap already did. Ghostscript reads the test's page and text streams as they decode now; (14) a region's location is unsigned (5.4.4), so one past `i32::MAX` is off the page, where the decoder took it for a signed one: a region there was drawn back onto the page from the left or the top (at 0xFFFFFFFC, four pixels left of it), and a refinement there, of the page or of a region at the same place (7.4.7.5), was refused as an overflow, and the page with it. `Bitmap::combine_region` keeps such a location past the page. A refinement of another region refines it where it is, as Table 35 has it (GRREFERENCEDX and GRREFERENCEDY 0), whatever the two locations say; a refinement of the page, see (16); (15) a refinement whose reference is offset right of it (GRREFERENCEDX above 0, which a refined text instance has from a wider bitmap, TaLine truncated
|
||||
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` |
|
||||
|
||||
+1
-1
@@ -315,7 +315,7 @@ impl<'a> Context<'a> {
|
||||
let mut ocg_state = {
|
||||
let root_ref = xref.root_id();
|
||||
xref.get::<Dict<'_>>(root_ref)
|
||||
.map(|catalog| OcgState::from_catalog(&catalog))
|
||||
.map(|catalog| OcgState::from_catalog(&catalog, xref, settings.view_auto_state))
|
||||
.unwrap_or_default()
|
||||
};
|
||||
// PdfCraft patch: apply viewer layer toggles.
|
||||
|
||||
+6
@@ -111,6 +111,11 @@ pub struct InterpreterSettings {
|
||||
/// PdfCraft patch: viewer overrides for optional content groups (object number, generation,
|
||||
/// visible), applied on top of the document's default configuration (Layers panel toggles).
|
||||
pub ocg_overrides: Arc<Vec<(i32, i32, bool)>>,
|
||||
/// PdfCraft patch (103): apply the default configuration's auto state for the View event
|
||||
/// (`/AS` usage applications with `/Event /View`, ISO 32000-2 §8.11.4.4) before
|
||||
/// `ocg_overrides`. On by default: that is the state for viewing. Off for output made for
|
||||
/// printing, which the View event is not.
|
||||
pub view_auto_state: bool,
|
||||
/// PdfCraft patch: once this is `true`, interpretation stops before the next content
|
||||
/// operator. What was drawn is then incomplete, so only set it when the output will be
|
||||
/// thrown away (a viewer's render whose result nobody can receive any more).
|
||||
@@ -144,6 +149,7 @@ impl Default for InterpreterSettings {
|
||||
render_annotations: true,
|
||||
hide_comments: false,
|
||||
ocg_overrides: Arc::new(Vec::new()),
|
||||
view_auto_state: true,
|
||||
cancelled: None,
|
||||
preview: false,
|
||||
jbig2_work: hayro_syntax::MAX_PAGE_JBIG2_WORK,
|
||||
|
||||
Vendored
+94
-3
@@ -1,6 +1,9 @@
|
||||
use hayro_syntax::object::dict::keys::{BASE_STATE, D, OCGS, OCMD, OCPROPERTIES, OFF, ON, P, TYPE, VE};
|
||||
use hayro_syntax::object::dict::keys::{
|
||||
AS, BASE_STATE, D, OCGS, OCMD, OCPROPERTIES, OFF, ON, P, TYPE, USAGE, VE, VIEW, VIEW_STATE,
|
||||
};
|
||||
use hayro_syntax::object::{Array, Dict, MaybeRef, Name, Object, ObjectIdentifier};
|
||||
use std::collections::HashSet;
|
||||
use hayro_syntax::xref::XRef;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub(crate) struct OcgState {
|
||||
inactive_ocgs: HashSet<ObjectIdentifier>,
|
||||
@@ -30,7 +33,10 @@ impl OcgState {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_catalog(catalog: &Dict<'_>) -> Self {
|
||||
/// The groups' states as the document opens: the default configuration (`/BaseState`, then
|
||||
/// `/ON` and `/OFF`), then, when `view_auto_state` is set (PdfCraft patch (103)), the auto
|
||||
/// state its `/AS` array gives for the View event ([`apply_view_auto_state`]).
|
||||
pub(crate) fn from_catalog(catalog: &Dict<'_>, xref: &XRef, view_auto_state: bool) -> Self {
|
||||
let Some(oc_properties) = catalog.get::<Dict<'_>>(OCPROPERTIES) else {
|
||||
return Self::dummy();
|
||||
};
|
||||
@@ -83,6 +89,10 @@ impl OcgState {
|
||||
read_ocg_array(ON, true);
|
||||
read_ocg_array(OFF, false);
|
||||
|
||||
if view_auto_state {
|
||||
apply_view_auto_state(&config, xref, &mut inactive);
|
||||
}
|
||||
|
||||
Self {
|
||||
inactive_ocgs: inactive,
|
||||
known_ocgs: known,
|
||||
@@ -213,6 +223,87 @@ impl Default for OcgState {
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (103): at most this many usage application dictionaries of an `/AS` array are
|
||||
/// read; the rest are ignored.
|
||||
const MAX_AUTO_STATE_APPLICATIONS: usize = 256;
|
||||
/// PdfCraft patch (103): at most this many `/OCGs` entries are read across all of them.
|
||||
const MAX_AUTO_STATE_GROUPS: usize = 4096;
|
||||
/// PdfCraft patch (103): at most this many `/Category` names are read per application.
|
||||
const MAX_AUTO_STATE_CATEGORIES: usize = 16;
|
||||
|
||||
/// PdfCraft patch (103): apply the configuration's auto state for the View event (ISO 32000-2
|
||||
/// §8.11.4.4, Tables 99 and 101). For each usage application dictionary in `/AS` whose `/Event`
|
||||
/// is `/View`, each group in its `/OCGs` gets a recommended state from each category in its
|
||||
/// `/Category` that the group's `/Usage` gives one for. A group is ON only if every
|
||||
/// recommendation it receives, across all such dictionaries, is ON, and OFF otherwise; a group
|
||||
/// that receives none keeps its configured state.
|
||||
///
|
||||
/// Only the `/View` category (`/ViewState`) is evaluated. `/Zoom`, `/User` and `/Language` need
|
||||
/// the magnification, user and locale, which the interpreter doesn't know, so they give no
|
||||
/// recommendation. Malformed entries (not a dictionary, no `/Category`, a `/ViewState` other
|
||||
/// than ON or OFF) are skipped, and the walk is bounded by the caps above.
|
||||
fn apply_view_auto_state(config: &Dict<'_>, xref: &XRef, inactive: &mut HashSet<ObjectIdentifier>) {
|
||||
let Some(applications) = config.get::<Array<'_>>(AS) else {
|
||||
return;
|
||||
};
|
||||
let mut recommended: HashMap<ObjectIdentifier, bool> = HashMap::new();
|
||||
let mut groups_left = MAX_AUTO_STATE_GROUPS;
|
||||
for application in applications.raw_iter().take(MAX_AUTO_STATE_APPLICATIONS) {
|
||||
let application = match application {
|
||||
MaybeRef::Ref(r) => xref.get::<Dict<'_>>(r.into()),
|
||||
MaybeRef::NotRef(Object::Dict(d)) => Some(d),
|
||||
MaybeRef::NotRef(_) => None,
|
||||
};
|
||||
let Some(application) = application else {
|
||||
continue;
|
||||
};
|
||||
if application.get::<Name<'_>>(b"Event").as_deref() != Some(VIEW) {
|
||||
continue;
|
||||
}
|
||||
let views = application.get::<Array<'_>>(b"Category").is_some_and(|categories| {
|
||||
categories
|
||||
.raw_iter()
|
||||
.take(MAX_AUTO_STATE_CATEGORIES)
|
||||
.any(|c| matches!(c, MaybeRef::NotRef(Object::Name(n)) if n.as_ref() == VIEW))
|
||||
});
|
||||
if !views {
|
||||
continue;
|
||||
}
|
||||
let Some(groups) = application.get::<Array<'_>>(OCGS) else {
|
||||
continue;
|
||||
};
|
||||
for group in groups.raw_iter() {
|
||||
if groups_left == 0 {
|
||||
break;
|
||||
}
|
||||
groups_left -= 1;
|
||||
let Some(r) = group.as_obj_ref() else {
|
||||
continue;
|
||||
};
|
||||
let id: ObjectIdentifier = r.into();
|
||||
let state = xref
|
||||
.get::<Dict<'_>>(id)
|
||||
.and_then(|g| g.get::<Dict<'_>>(USAGE))
|
||||
.and_then(|u| u.get::<Dict<'_>>(VIEW))
|
||||
.and_then(|v| v.get::<Name<'_>>(VIEW_STATE));
|
||||
let on = match state.as_deref() {
|
||||
Some(ON) => true,
|
||||
Some(OFF) => false,
|
||||
_ => continue,
|
||||
};
|
||||
let entry = recommended.entry(id).or_insert(true);
|
||||
*entry &= on;
|
||||
}
|
||||
}
|
||||
for (id, on) in recommended {
|
||||
if on {
|
||||
inactive.remove(&id);
|
||||
} else {
|
||||
inactive.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (40): how deep visibility expressions may nest; deeper ones are malformed.
|
||||
const MAX_VISIBILITY_EXPRESSION_DEPTH: usize = 32;
|
||||
|
||||
|
||||
Reference in new issue
Block a user