Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M11: black-and-white RGB used beyond the page content read stays RGB

Grzegorz Martens2d0a7b22411d
diff --git a/crates/optimize/README.md b/crates/optimize/README.md
index 6383510c9..dec417867 100644
--- a/crates/optimize/README.md
+++ b/crates/optimize/README.md
@@ -45,9 +45,12 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
row, not as T.4 sends them, is read as PdfCraft draws it, which at `/K 0` may be other rows than
were coded, and an image stored again keeps them). Packed to one bit first, unless a colour-key `/Mask` is in the image's
own values: eight-bit grey of only 0 and 255; eight-bit `DeviceRGB` of only black and white,
- which becomes `DeviceGray` (not calibrated RGB or RGB with a profile, nor one drawn where
- `/DefaultGray` or `/DefaultRGB` is in force, which would then draw it otherwise, nor one whose
- soft mask has a `/Matte`); and an indexed image of 2, 4 or 8 bits that uses only palette entries
+ which becomes `DeviceGray` (not calibrated RGB or RGB with a profile, nor one drawn or listed
+ where `/DefaultGray` or `/DefaultRGB` is in force, which would then draw it otherwise, nor one
+ referred to from anywhere but the page and form resources the optimizer reads, where they may
+ be: an annotation's appearance or a pattern drawing it, directly or through resources or a form
+ it shares with a page, or another image's `/Alternates`; nor one whose soft mask has a
+ `/Matte`); and an indexed image of 2, 4 or 8 bits that uses only palette entries
0 and 1, which keeps its palette, whatever its two colours. A decode array stays when it means
the same at one bit (grey's, or RGB's if the same for each component, as grey's), and an indexed
image's default one goes, as the default at one bit; otherwise the image is left alone. The grey
diff --git a/crates/optimize/src/images.rs b/crates/optimize/src/images.rs
index a9e87e1af..54e382d13 100644
--- a/crates/optimize/src/images.rs
+++ b/crates/optimize/src/images.rs
@@ -12,11 +12,18 @@ const MAX_PIXELS: u64 = 80_000_000;
/// The resources of a page, inherited from the page tree if the page has none.
pub(crate) fn page_resources(doc: &Document, page: ObjRef) -> Option<Dict> {
+ held_page_resources(doc, page).map(|(resources, _)| resources)
+}
+
+/// [`page_resources`], and the object holding them: the page or the page-tree node they are
+/// written in (inherited from), or the resources dictionary when it is an object of its own.
+fn held_page_resources(doc: &Document, page: ObjRef) -> Option<(Dict, ObjRef)> {
let mut node = Some(page);
for _ in 0..64 {
- let d = doc.get(node?).as_dict()?.clone();
+ let n = node?;
+ let d = doc.get(n).as_dict()?.clone();
if let Some(r) = d.get(b"Resources") {
- return doc.resolve(r).as_dict().cloned();
+ return Some((doc.resolve(r).as_dict().cloned()?, r.as_ref().unwrap_or(n)));
}
node = d.reference(b"Parent");
}
@@ -53,18 +60,56 @@ struct Walk<'a> {
/// False once a use may have been missed (depth or work limit).
complete: bool,
out: HashMap<ObjRef, f64>,
- /// Images drawn at least once where `/DefaultGray` or `/DefaultRGB` is in force.
- defaults: HashSet<ObjRef>,
+ /// Images drawn or listed at least once where `/DefaultGray` or `/DefaultRGB` is in force, by
+ /// object number: a reference with another generation reaches the same image.
+ defaults: HashSet<u32>,
+ /// The references the walk followed to reach its images, and the pages and page-tree nodes
+ /// whose resources it read.
+ read: Read,
+}
+
+/// Where a walk read a reference: under a name in an `/XObject` dictionary (an image or a form),
+/// as resources' `/XObject` dictionary, or as the `/Resources` of a page, node or form.
+#[derive(Clone, PartialEq, Eq, Hash)]
+enum Entry {
+ Name(Vec<u8>),
+ XObject,
+ Resources,
+}
+
+/// The references a walk followed, by object number: (the object referred to, the object holding
+/// the reference, where in it), and the pages and page-tree nodes whose resources it read.
+#[derive(Default)]
+struct Read {
+ entries: HashSet<(u32, u32, Entry)>,
+ roots: HashSet<u32>,
}
impl Walk<'_> {
/// Walk one content stream, recording each image's displayed resolution (pixels per inch, the
- /// smaller of the two axes) and descending into form XObjects. `defaults`: an enclosing
- /// stream's resources remap a device colour space.
- fn content(&mut self, data: &[u8], resources: &Dict, ctm: Matrix, defaults: bool) {
+ /// smaller of the two axes) and descending into form XObjects. `holder` is the object holding
+ /// `resources`. `defaults`: an enclosing stream's resources remap a device colour space.
+ fn content(&mut self, data: &[u8], resources: &Dict, holder: ObjRef, ctm: Matrix, defaults: bool) {
let doc = self.doc;
let defaults = defaults || remaps_device_spaces(doc, resources);
let xobjects = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
+ let xholder = match resources.get(b"XObject").and_then(Object::as_ref) {
+ Some(x) => {
+ self.read.entries.insert((x.num, holder.num, Entry::XObject));
+ x
+ }
+ None => holder,
+ };
+ // Every entry counts as read, drawn here or not: content using these resources (a Type3
+ // glyph without its own, say) draws it under the same defaults.
+ for (name, v) in xobjects.iter() {
+ if let Some(r) = v.as_ref() {
+ self.read.entries.insert((r.num, xholder.num, Entry::Name(name.to_vec())));
+ if defaults {
+ self.defaults.insert(r.num);
+ }
+ }
+ }
let mut stack = vec![ctm];
for op in pdfcraft_content::parse(data).ops {
let top = stack.last().copied().unwrap_or(ctm);
@@ -96,10 +141,10 @@ impl Walk<'_> {
*e = e.min(ppi);
}
if defaults {
- self.defaults.insert(r);
+ self.defaults.insert(r.num);
}
}
- Some(b"Form") => self.form(r, s, resources, top, defaults),
+ Some(b"Form") => self.form(r, s, (resources, holder), top, defaults),
_ => {}
}
}
@@ -108,8 +153,37 @@ impl Walk<'_> {
}
}
- /// Descend into form `r` drawn with `ctm` from a stream whose resources are `resources`.
- fn form(&mut self, r: ObjRef, s: &Stream, resources: &Dict, ctm: Matrix, defaults: bool) {
+ /// Read the resources of page `p` and of each page-tree node above it, each of them a root: a
+ /// node's resources are its inheriting pages' (every page is walked), or no page's.
+ fn resources_above(&mut self, p: ObjRef) {
+ let doc = self.doc;
+ let mut node = Some(p);
+ for _ in 0..64 {
+ let Some(n) = node else { return };
+ // A node met before had its own nodes above it read then.
+ if !self.read.roots.insert(n.num) {
+ return;
+ }
+ let Some(d) = doc.get(n).as_dict().cloned() else { return };
+ if let Some(r) = d.get(b"Resources")
+ && let Some(resources) = doc.resolve(r).as_dict().cloned()
+ {
+ let holder = match r.as_ref() {
+ Some(res) => {
+ self.read.entries.insert((res.num, n.num, Entry::Resources));
+ res
+ }
+ None => n,
+ };
+ self.content(&[], &resources, holder, Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]), false);
+ }
+ node = d.reference(b"Parent");
+ }
+ }
+
+ /// Descend into form `r` drawn with `ctm` from a stream whose resources are `resources`, with
+ /// the object holding them.
+ fn form(&mut self, r: ObjRef, s: &Stream, (resources, holder): (&Dict, ObjRef), ctm: Matrix, defaults: bool) {
if self.path.contains(&r) {
return;
}
@@ -144,7 +218,19 @@ impl Walk<'_> {
return;
};
self.path.push(r);
- self.content(&data, own.as_ref().unwrap_or(resources), inner, defaults);
+ match &own {
+ Some(own) => {
+ let own_holder = match s.dict.get(b"Resources").and_then(Object::as_ref) {
+ Some(res) => {
+ self.read.entries.insert((res.num, r.num, Entry::Resources));
+ res
+ }
+ None => r,
+ };
+ self.content(&data, own, own_holder, inner, defaults);
+ }
+ None => self.content(&data, resources, holder, inner, defaults),
+ }
self.path.pop();
}
}
@@ -165,9 +251,10 @@ pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef
walk_pages(doc, pages).0
}
-/// [`effective_resolutions`], and the images drawn where `/DefaultGray` or `/DefaultRGB` is in
-/// force: all of them when a use may have been missed.
-fn walk_pages(doc: &Document, pages: &[ObjRef]) -> (HashMap<ObjRef, f64>, HashSet<ObjRef>) {
+/// [`effective_resolutions`], the images drawn or listed where `/DefaultGray` or `/DefaultRGB` is
+/// in force, by object number (all of them when a use may have been missed), and the references
+/// followed to reach them.
+fn walk_pages(doc: &Document, pages: &[ObjRef]) -> (HashMap<ObjRef, f64>, HashSet<u32>, Read) {
let mut walk = Walk {
doc,
path: Vec::new(),
@@ -178,12 +265,14 @@ fn walk_pages(doc: &Document, pages: &[ObjRef]) -> (HashMap<ObjRef, f64>, HashSe
complete: true,
out: HashMap::new(),
defaults: HashSet::new(),
+ read: Read::default(),
};
for p in pages {
let Some(dict) = doc.get(*p).as_dict().cloned() else { continue };
let page = pdfcraft_model::Page { obj: *p, dict };
+ walk.resources_above(*p);
let Some(contents) = page.dict.get(b"Contents") else { continue };
- let res = page_resources(doc, *p).unwrap_or_default();
+ let (res, holder) = held_page_resources(doc, *p).unwrap_or_else(|| (Dict::default(), *p));
walk.budget = DecodeBudget::page();
let Some(data) = content_bytes(doc, contents, &mut walk.budget) else {
walk.complete = false;
@@ -191,13 +280,103 @@ fn walk_pages(doc: &Document, pages: &[ObjRef]) -> (HashMap<ObjRef, f64>, HashSe
};
// Content coordinates are in page units; image resolution is in physical inches.
let unit = page.user_unit(doc);
- walk.content(&data, &res, Matrix([unit, 0.0, 0.0, unit, 0.0, 0.0]), false);
+ walk.content(&data, &res, holder, Matrix([unit, 0.0, 0.0, unit, 0.0, 0.0]), false);
}
if !walk.complete {
walk.out.values_mut().for_each(|v| *v = f64::INFINITY);
- walk.defaults.extend(walk.out.keys());
+ walk.defaults.extend(walk.out.keys().map(|r| r.num));
+ }
+ (walk.out, walk.defaults, walk.read)
+}
+
+/// Whether image `r` is one [`one_bit`] may make grey: eight-bit `DeviceRGB`, not in an image codec.
+fn device_rgb(doc: &Document, r: ObjRef) -> bool {
+ let Object::Stream(s) = &*doc.get(r) else { return false };
+ let cs = s.dict.get(b"ColorSpace").map(|cs| doc.resolve(cs));
+ let codec =
+ s.filters().iter().any(|(f, _)| matches!(f, pdfcraft_filters::Filter::Dct | pdfcraft_filters::Filter::Jpx | pdfcraft_filters::Filter::Jbig2));
+ s.dict.int(b"BitsPerComponent") == Some(8)
+ && !codec
+ && cs.as_deref().and_then(Object::as_name).is_some_and(|n| matches!(n, b"DeviceRGB" | b"RGB"))
+}
+
+/// Call `f` with every reference in `o`, a dictionary's or array's included, a stream's dictionary
+/// too, but not those in objects referred to.
+fn each_ref(o: &Object, mut f: impl FnMut(ObjRef)) {
+ // Direct objects nest finitely (the parser builds trees), so this ends.
+ let mut stack = vec![o];
+ while let Some(o) = stack.pop() {
+ match o {
+ Object::Ref(r) => f(*r),
+ Object::Dict(d) => stack.extend(d.iter().map(|(_, v)| v)),
+ Object::Array(a) => stack.extend(a),
+ Object::Stream(s) => stack.extend(s.dict.iter().map(|(_, v)| v)),
+ _ => {}
+ }
+ }
+}
+
+/// The images among `images` (by object number) that may be drawn beyond what the walk read:
+/// some object the document uses refers to the image, or to an object on the way to it from a
+/// page (an `/XObject` dictionary, resources, a form), other than as the page and form resources
+/// the walk read do. So an annotation's appearance, a pattern, a Type3 glyph or a soft mask's
+/// group drawing it, directly or through resources or a form it shares with a page, counts, as
+/// other default colour spaces may be in force there, and so does any other reference (another
+/// image's `/Alternates`, say). Objects nothing reaches from the trailer don't count.
+fn used_elsewhere(doc: &Document, images: &HashSet<u32>, read: &Read) -> HashSet<u32> {
+ if images.is_empty() {
+ return HashSet::new();
+ }
+ let targets: HashSet<u32> = read.entries.iter().map(|(target, ..)| *target).collect();
+ // References to each object the walk followed, by the object holding them.
+ let mut held: HashMap<u32, HashMap<u32, usize>> = HashMap::new();
+ let mut queue: Vec<u32> = Vec::new();
+ let mut visited = HashSet::new();
+ for (_, v) in doc.trailer().iter() {
+ each_ref(v, |r| queue.push(r.num));
+ }
+ while let Some(num) = queue.pop() {
+ if !visited.insert(num) {
+ continue;
+ }
+ let obj = doc.get(ObjRef::new(num, doc.generation(num)));
+ each_ref(&obj, |r| {
+ if targets.contains(&r.num) {
+ *held.entry(r.num).or_default().entry(num).or_default() += 1;
+ }
+ if !visited.contains(&r.num) {
+ queue.push(r.num);
+ }
+ });
+ }
+ let mut seen: HashMap<(u32, u32), usize> = HashMap::new();
+ for (target, holder, _) in &read.entries {
+ *seen.entry((*target, *holder)).or_default() += 1;
+ }
+ // Covered: every reference to it is one the walk followed, held by a page or node, or by an
+ // object covered in turn. Everything the walk reached starts covered, and whatever has a
+ // reference it didn't follow, or is held by an object taken out, is taken out, until nothing
+ // more is. Content beyond what the walk read has to refer to an object on its way to the
+ // image, which takes out everything after it; a cycle the walk read whole stays covered.
+ let mut holds: HashMap<u32, Vec<u32>> = HashMap::new();
+ for (target, holders) in &held {
+ for h in holders.keys() {
+ holds.entry(*h).or_default().push(*target);
+ }
+ }
+ let mut covered: HashSet<u32> = held.keys().copied().collect();
+ let passes = |t: u32, covered: &HashSet<u32>| {
+ held.get(&t)
+ .is_some_and(|holders| holders.iter().all(|(h, n)| seen.get(&(t, *h)) == Some(n) && (read.roots.contains(h) || covered.contains(h))))
+ };
+ let mut check: Vec<u32> = covered.iter().copied().collect();
+ while let Some(t) = check.pop() {
+ if covered.contains(&t) && !passes(t, &covered) {
+ covered.remove(&t);
+ check.extend(holds.get(&t).into_iter().flatten().copied());
+ }
}
- (walk.out, walk.defaults)
+ images.iter().copied().filter(|i| !covered.contains(i)).collect()
}
/// Colour components of a colour space PdfCraft resamples: gray (1) or RGB (3).
@@ -600,9 +779,9 @@ type Pixel = fn(&[u8]) -> Option<bool>;
/// - eight-bit `DeviceRGB` whose every pixel is black or white, which becomes `DeviceGray`. A
/// decode array the same for all three components becomes that one pair; another stops it.
/// Calibrated RGB and RGB with a profile are left out, as the profile could make them other
-/// than black and white; so is one drawn where `/DefaultGray` or `/DefaultRGB` is in force
-/// (`defaults`), which would draw it otherwise as grey, and one whose soft mask has a `/Matte`
-/// of three components;
+/// than black and white; so is one drawn where `/DefaultGray` or `/DefaultRGB` is or may be in
+/// force (`defaults`), which would draw it otherwise as grey, and one whose soft mask has a
+/// `/Matte` of three components;
/// - an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1, which stay 0 and
/// 1 at one bit, whatever their colours, so the colour space stays. A decode array other than
/// the default stops it: in index units it would mean something else at one bit.
@@ -805,7 +984,7 @@ pub(crate) fn downsample_bits(data: &[u8], w: u32, h: u32, nw: u32, nh: u32, dar
/// A black-and-white image (see [`one_bit`]) resampled and stored again per `settings`, if that is
/// smaller as stored; `ppi` is its effective resolution, and `defaults` says it is drawn where
-/// `/DefaultGray` or `/DefaultRGB` is in force. Also says whether it was resampled.
+/// `/DefaultGray` or `/DefaultRGB` is or may be in force. Also says whether it was resampled.
///
/// - **Resampled** ([`downsample_bits`]) when its resolution is above `above_ppi`, to `target_ppi`,
/// unless it has a soft mask, whose own size would then have to follow, or is a halftone or a
@@ -896,7 +1075,12 @@ pub(crate) fn run(
report: &mut Report,
progress: &mut dyn FnMut(Stage) -> bool,
) -> Result<(), OptimizeError> {
- let (ppi, defaults) = walk_pages(doc, pages);
+ let (ppi, mut defaults, read) = walk_pages(doc, pages);
+ // Black-and-white RGB becomes grey, which default colour spaces would draw otherwise: one used
+ // where the walk didn't look may be drawn so.
+ let packs = settings.mono.compression != MonoCompression::Retain;
+ let rgb: HashSet<u32> = ppi.keys().filter(|r| packs && device_rgb(doc, **r)).map(|r| r.num).collect();
+ defaults.extend(used_elsewhere(doc, &rgb, &read));
// Soft masks are processed with their image, not on their own.
let masks: HashSet<ObjRef> = ppi
.keys()
@@ -918,7 +1102,7 @@ pub(crate) fn run(
// Packed from more bits a sample, it is lossless at one bit, but the grey or colour
// settings can make it smaller still (below).
let packed_from_more = s.dict.int(b"BitsPerComponent").is_some_and(|b| b > 1);
- let (packed, mono) = match mono(doc, s, ppi, defaults.contains(&r), &settings.mono) {
+ let (packed, mono) = match mono(doc, s, ppi, defaults.contains(&r.num), &settings.mono) {
Some(m) if packed_from_more => (Some(m), None),
m => (None, m),
};
diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rs
index edfb339d7..d8fe601a3 100644
--- a/crates/optimize/tests/optimize.rs
+++ b/crates/optimize/tests/optimize.rs
@@ -1169,6 +1169,287 @@ fn black_and_white_rgb_stays_rgb_where_grey_would_be_drawn_otherwise() {
assert_eq!(stream(&doc, img).raw, before.raw, "a use not followed");
}
+/// An empty document, and a maker of images of only black and white as eight-bit `DeviceRGB`.
+fn rgb_page_fixture() -> (Document, impl Fn(&mut Document) -> ObjRef) {
+ let (w, h) = (1200u32, 480u32);
+ let rgb_data = samples_of(&bilevel(w, h, false), w, h, [&[0, 0, 0], &[255, 255, 255]], 8);
+ let image = move |doc: &mut Document| {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("XObject"));
+ d.set(b"Subtype".to_vec(), Object::name("Image"));
+ d.set(b"Width".to_vec(), Object::Int(w.into()));
+ d.set(b"Height".to_vec(), Object::Int(h.into()));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
+ doc.add(Object::Stream(Stream::flate(d, &rgb_data)))
+ };
+ (Document::new_empty(), image)
+}
+
+/// `q … cm /N Do Q` for each name, one under the other.
+fn draw_each(names: &[&str]) -> String {
+ names.iter().enumerate().map(|(i, n)| format!("q 200 0 0 80 6 {} cm /{n} Do Q ", 690 - 100 * i)).collect()
+}
+
+/// An `/XObject` dictionary of `names`.
+fn xobject_dict(names: &[(&str, ObjRef)]) -> Dict {
+ let mut x = Dict::new();
+ for (n, r) in names {
+ x.set(n.as_bytes().to_vec(), Object::Ref(*r));
+ }
+ x
+}
+
+/// A stream drawing `/Im` (or nothing) whose `/Resources` is `resources`, with `extra` in its
+/// dictionary: a form, an appearance or a tiling pattern.
+fn drawing(doc: &mut Document, resources: Option<Object>, extra: &[(&str, Object)]) -> ObjRef {
+ let mut f = Dict::new();
+ f.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]));
+ if let Some(resources) = resources {
+ f.set(b"Resources".to_vec(), resources);
+ }
+ for (k, v) in extra {
+ f.set(k.as_bytes().to_vec(), v.clone());
+ }
+ doc.add(Object::Stream(Stream::from_raw(f, draw_each(&["Im"]).into_bytes())))
+}
+
+fn form_entries() -> [(&'static str, Object); 2] {
+ [("Type", Object::name("XObject")), ("Subtype", Object::name("Form"))]
+}
+
+/// Resources of `entries`.
+fn resources_of(entries: Vec<(&str, Object)>) -> Dict {
+ let mut res = Dict::new();
+ for (k, v) in entries {
+ res.set(k.as_bytes().to_vec(), v);
+ }
+ res
+}
+
+/// Give page `p` an annotation whose normal appearance is `appearance`.
+fn annotate(doc: &mut Document, p: ObjRef, appearance: ObjRef) {
+ let mut ap = Dict::new();
+ ap.set(b"N".to_vec(), Object::Ref(appearance));
+ let mut annotation = Dict::new();
+ annotation.set(b"Subtype".to_vec(), Object::name("Square"));
+ annotation.set(b"Rect".to_vec(), Object::Array(vec![0.into(), 0.into(), 100.into(), 100.into()]));
+ annotation.set(b"AP".to_vec(), Object::Dict(ap));
+ let annotation = doc.add(Object::Dict(annotation));
+ let mut annots = doc.get(p).as_dict().and_then(|d| d.get(b"Annots").and_then(|a| a.as_array().cloned())).unwrap_or_default();
+ annots.push(Object::Ref(annotation));
+ doc.update_dict(p, |d| d.set(b"Annots".to_vec(), Object::Array(annots))).unwrap();
+}
+
+/// `/DefaultGray` as a calibrated grey, in a `/ColorSpace` resource dictionary.
+fn default_gray() -> Object {
+ let mut white_point = Dict::new();
+ white_point.set(b"WhitePoint".to_vec(), Object::Array(vec![Object::Real(0.9505), 1.into(), Object::Real(1.089)]));
+ let mut c = Dict::new();
+ c.set(b"DefaultGray".to_vec(), Object::Array(vec![Object::name("CalGray"), Object::Dict(white_point)]));
+ Object::Dict(c)
+}
+
+/// Optimize with colour and grey settings that leave images alone, so only packing acts; the
+/// report's images resampled and stored again.
+fn pack_only(doc: &mut Document) -> (usize, usize) {
+ let keep = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };
+ let r = optimize(doc, &Settings { color: keep, gray: keep, ..Settings::default() }).unwrap();
+ (r.images_resampled, r.images_recompressed)
+}
+
+/// Black-and-white RGB becomes grey for every use at once, so it stays RGB, byte for byte, when
+/// any use may be beyond the page content and forms the optimizer reads, where other default
+/// colour spaces may be in force: drawn by an annotation's appearance whose resources make
+/// `/DefaultGray` the grey it would be drawn in; by a tiling pattern; through an `/XObject`
+/// dictionary, or a form, that a page shares with such an appearance;
+/// referred to with another generation by the page than by such an appearance; drawn plainly on
+/// one page and, named with another generation, on a page whose resources set `/DefaultGray`;
+/// drawn plainly and only listed (not drawn) where `/DefaultGray` is in force, under the same
+/// generation or another, as a Type3 glyph without resources could draw it there; or held in an
+/// array elsewhere (another image's `/Alternates`).
+#[test]
+fn black_and_white_rgb_used_beyond_the_page_content_read_stays_rgb() {
+ let (mut doc, image) = rgb_page_fixture();
+ let [in_annotation, in_pattern, shared_xobjects, shared_form, other_generation, generation_under_defaults, listed, listed_as_1, in_array] =
+ [(); 9].map(|_| image(&mut doc));
+ let gray_resources = |im: Object| Some(Object::Dict(resources_of(vec![("XObject", im), ("ColorSpace", default_gray())])));
+ let direct = |im: ObjRef| Object::Dict(xobject_dict(&[("Im", im)]));
+
+ let appearance = drawing(&mut doc, gray_resources(direct(in_annotation)), &form_entries());
+ let pattern_entries =
+ [("PatternType", 1.into()), ("PaintType", 1.into()), ("TilingType", 1.into()), ("XStep", 612.into()), ("YStep", 792.into())];
+ let pattern = drawing(&mut doc, Some(Object::Dict(resources_of(vec![("XObject", direct(in_pattern))]))), &pattern_entries);
+ let p = page(&mut doc, &[("A", in_annotation), ("B", in_pattern)], &(draw_each(&["A", "B"]) + "/Pattern cs /P scn 0 0 10 10 re f"));
+ annotate(&mut doc, p, appearance);
+ doc.update_dict(p, |d| {
+ let mut res = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap();
+ let mut patterns = Dict::new();
+ patterns.set(b"P".to_vec(), Object::Ref(pattern));
+ res.set(b"Pattern".to_vec(), Object::Dict(patterns));
+ d.set(b"Resources".to_vec(), Object::Dict(res));
+ })
+ .unwrap();
+
+ // An /XObject dictionary of its own, read for a page, and a form drawn by a page, each also
+ // used by an appearance under DefaultGray.
+ let x = doc.add(Object::Dict(xobject_dict(&[("Im", shared_xobjects)])));
+ let q = page(&mut doc, &[], &draw_each(&["Im"]));
+ doc.update_dict(q, |d| d.set(b"Resources".to_vec(), Object::Dict(resources_of(vec![("XObject", Object::Ref(x))])))).unwrap();
+ let appearance = drawing(&mut doc, gray_resources(Object::Ref(x)), &form_entries());
+ annotate(&mut doc, q, appearance);
+ let form = drawing(&mut doc, Some(Object::Dict(resources_of(vec![("XObject", direct(shared_form))]))), &form_entries());
+ let q = page(&mut doc, &[("F", form)], &draw_each(&["F"]));
+ let appearance = drawing(&mut doc, gray_resources(Object::Dict(xobject_dict(&[("Im", form)]))), &form_entries());
+ annotate(&mut doc, q, appearance);
+
+ // The page names it with generation 1 (it is 0); the appearance with 0.
+ let q = page(&mut doc, &[("Im", ObjRef { generation: 1, ..other_generation })], &draw_each(&["Im"]));
+ let appearance = drawing(&mut doc, gray_resources(direct(other_generation)), &form_entries());
+ annotate(&mut doc, q, appearance);
+
+ // Drawn plainly as 0, and as 1 where DefaultGray is in force.
+ page(&mut doc, &[("Im", generation_under_defaults)], &draw_each(&["Im"]));
+ let q = page(&mut doc, &[], &draw_each(&["Im"]));
+ let gray = resources_of(vec![
+ ("XObject", Object::Dict(xobject_dict(&[("Im", ObjRef { generation: 1, ..generation_under_defaults })]))),
+ ("ColorSpace", default_gray()),
+ ]);
+ doc.update_dict(q, |d| d.set(b"Resources".to_vec(), Object::Dict(gray))).unwrap();
+
+ // Drawn plainly, and only listed where DefaultGray is in force, as 0 and as 1.
+ page(&mut doc, &[("A", listed), ("B", listed_as_1)], &draw_each(&["A", "B"]));
+ let q = page(&mut doc, &[], "");
+ let gray = resources_of(vec![
+ ("XObject", Object::Dict(xobject_dict(&[("A", listed), ("B", ObjRef { generation: 1, ..listed_as_1 })]))),
+ ("ColorSpace", default_gray()),
+ ]);
+ doc.update_dict(q, |d| d.set(b"Resources".to_vec(), Object::Dict(gray))).unwrap();
+
+ // Another image drawn on the page lists it as an alternate.
+ let mut alternate = Dict::new();
+ alternate.set(b"Image".to_vec(), Object::Ref(in_array));
+ let holder = image(&mut doc);
+ doc.update_dict(holder, |d| {
+ d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
+ d.set(b"Alternates".to_vec(), Object::Array(vec![Object::Dict(alternate)]));
+ })
+ .unwrap();
+ page(&mut doc, &[("Im", in_array), ("Alt", holder)], &draw_each(&["Im"]));
+
+ let kept = [in_annotation, in_pattern, shared_xobjects, shared_form, other_generation, generation_under_defaults, listed, listed_as_1, in_array];
+ let before = kept.map(|r| stream(&doc, r));
+ pack_only(&mut doc);
+ for (i, b) in kept.iter().zip(&before) {
+ let s = stream(&doc, *i);
+ assert_eq!((&s.dict, &s.raw), (&b.dict, &b.raw), "{i:?}");
+ }
+}
+
+/// Black-and-white RGB that the page content and forms the optimizer reads are the only uses of
+/// becomes grey, however its resources are written: drawn on two pages, by a form, under two
+/// names on one page; through resources that are an object of their own, shared by two pages,
+/// whose `/XObject` dictionary is one too; through resources an object of their own with a direct
+/// `/XObject` dictionary; through resources a page inherits from the page tree; by a form whose
+/// `/Resources` is a reference; by a form without resources, through its page's; listed under a
+/// second name nothing draws; through resources an object of their own that a page without
+/// content lists too; and with an object nothing in the document reaches referring to it as well.
+#[test]
+fn black_and_white_rgb_drawn_only_where_the_optimizer_reads_becomes_grey() {
+ let (mut doc, image) = rgb_page_fixture();
+ let [everywhere, shared_resources, resources_object, inherited, form_resources_object, no_resources, spare_name, no_contents, unreachable] =
+ [(); 9].map(|_| image(&mut doc));
+ let set_resources = |doc: &mut Document, q: ObjRef, res: Object| doc.update_dict(q, |d| d.set(b"Resources".to_vec(), res)).unwrap();
+
+ let form =
+ drawing(&mut doc, Some(Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", everywhere)])))]))), &form_entries());
+ page(&mut doc, &[("E", everywhere), ("F", form)], &draw_each(&["E", "F"]));
+ page(&mut doc, &[("E", everywhere), ("G", everywhere)], &draw_each(&["E", "G"]));
+
+ let x = doc.add(Object::Dict(xobject_dict(&[("Im", shared_resources)])));
+ let res = doc.add(Object::Dict(resources_of(vec![("XObject", Object::Ref(x))])));
+ for _ in 0..2 {
+ let q = page(&mut doc, &[], &draw_each(&["Im"]));
+ set_resources(&mut doc, q, Object::Ref(res));
+ }
+ let res = doc.add(Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", resources_object)])))])));
+ let q = page(&mut doc, &[], &draw_each(&["Im"]));
+ set_resources(&mut doc, q, Object::Ref(res));
+
+ let q = page(&mut doc, &[], &draw_each(&["I"]));
+ doc.update_dict(q, |d| {
+ d.remove(b"Resources");
+ })
+ .unwrap();
+ let pages = doc.root().and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages"))).unwrap();
+ set_resources(&mut doc, pages, Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("I", inherited)])))])));
+
+ let res = doc.add(Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", form_resources_object)])))])));
+ let form = drawing(&mut doc, Some(Object::Ref(res)), &form_entries());
+ page(&mut doc, &[("F", form)], &draw_each(&["F"]));
+ let form = drawing(&mut doc, None, &form_entries());
+ page(&mut doc, &[("F", form), ("Im", no_resources)], &draw_each(&["F"]));
+
+ page(&mut doc, &[("C", spare_name), ("D", spare_name)], &draw_each(&["C"]));
+ let res = doc.add(Object::Dict(resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", no_contents)])))])));
+ for drawn in [true, false] {
+ let q = page(&mut doc, &[], &draw_each(&["Im"]));
+ set_resources(&mut doc, q, Object::Ref(res));
+ if !drawn {
+ doc.update_dict(q, |d| {
+ d.remove(b"Contents");
+ })
+ .unwrap();
+ }
+ }
+
+ page(&mut doc, &[("Im", unreachable)], &draw_each(&["Im"]));
+ // A form nothing refers to, drawing it under DefaultGray.
+ let orphan = resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", unreachable)]))), ("ColorSpace", default_gray())]);
+ drawing(&mut doc, Some(Object::Dict(orphan)), &form_entries());
+
+ let grey = [everywhere, shared_resources, resources_object, inherited, form_resources_object, no_resources, spare_name, no_contents, unreachable];
+ assert_eq!(pack_only(&mut doc), (0, grey.len()));
+ for i in grey {
+ let s = stream(&doc, i);
+ assert_eq!((s.dict.get(b"ColorSpace"), s.dict.int(b"BitsPerComponent")), (Some(&Object::name("DeviceGray")), Some(1)), "{i:?}");
+ }
+}
+
+/// LibreOffice writes one resources object for a page and its `/Pages` node, and a transparency
+/// group's form whose `/Resources` is that same object, which the object lists in turn. Black-
+/// and-white RGB in it becomes grey: every reference is one the page walk reads, the cycle
+/// included. Drawn from outside as well, by an appearance under `/DefaultGray` that draws the
+/// form, it stays RGB.
+#[test]
+fn black_and_white_rgb_in_resources_its_page_tree_and_a_form_share_becomes_grey() {
+ for outside in [false, true] {
+ let (mut doc, image) = rgb_page_fixture();
+ let img = image(&mut doc);
+ let res = doc.add(Object::Dict(Dict::new()));
+ let form = drawing(&mut doc, Some(Object::Ref(res)), &form_entries());
+ doc.update_dict(res, |d| d.set(b"XObject".to_vec(), Object::Dict(xobject_dict(&[("Im", img), ("Tr", form)])))).unwrap();
+ let p = page(&mut doc, &[], &draw_each(&["Im", "Tr"]));
+ let pages = doc.root().and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages"))).unwrap();
+ for holder in [p, pages] {
+ doc.update_dict(holder, |d| d.set(b"Resources".to_vec(), Object::Ref(res))).unwrap();
+ }
+ if outside {
+ let gray = resources_of(vec![("XObject", Object::Dict(xobject_dict(&[("Im", form)]))), ("ColorSpace", default_gray())]);
+ let appearance = drawing(&mut doc, Some(Object::Dict(gray)), &form_entries());
+ annotate(&mut doc, p, appearance);
+ }
+ let before = stream(&doc, img);
+ pack_only(&mut doc);
+ let s = stream(&doc, img);
+ if outside {
+ assert_eq!((&s.dict, &s.raw), (&before.dict, &before.raw), "drawn from outside too");
+ } else {
+ assert_eq!((s.dict.get(b"ColorSpace"), s.dict.int(b"BitsPerComponent")), (Some(&Object::name("DeviceGray")), Some(1)));
+ }
+ }
+}
+
/// Black-and-white images above 450 ppi are averaged down to 300 ppi, by default: 1-bit Flate, CCITT
/// Group 4 (alone and behind ASCIIHexDecode), an image mask (its inverting decode array stays), and
/// eight-bit grey and RGB of only black and white (the RGB also the other way round, with a decode
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 99deb812b..26e94eda0 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -7384,8 +7384,8 @@ milestone = "M11"
status = "partial"
commands = ["optimize.advanced", "optimize.reduce"]
tools = ["doc_optimize", "doc_reduce"]
-evidence = ["crates/optimize/tests/optimize.rs::eight_bit_black_and_white_images_become_one_bit", "crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/optimize/tests/optimize.rs::group_3_fax_images_become_group_4", "crates/optimize/tests/optimize.rs::rgb_and_two_colour_indexed_black_and_white_images_become_one_bit", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]
-notes = "CCITT Group 4, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Packed to one bit first, then stored the same way (colour-key masks aside): eight-bit grey of only black and white, eight-bit DeviceRGB of only black and white (as DeviceGray; calibrated RGB, RGB with a profile, RGB drawn where /DefaultGray or /DefaultRGB is in force, and RGB whose soft mask has a /Matte aside), and an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1 (keeping its palette), unless the grey or colour settings make it smaller still, as they can a dithered scan downsampled to JPEG, its soft mask counted. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Group 3 fax images are stored again as Group 4 when that is smaller (damaged Group 3 with end-of-line codes as the decoder recovers it, as it reports no damage there; byte-aligned Group 3 with end-of-line codes but none before the first row, not as T.4 sends them, as PdfCraft draws it, which at /K 0 may be other rows than were coded). CCITT fax images are decoded to be downsampled (optimize.downsample-images), and a resampled image is stored as Group 4 or 1-bit Flate, whichever is smaller. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples."
+evidence = ["crates/optimize/tests/optimize.rs::eight_bit_black_and_white_images_become_one_bit", "crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/optimize/tests/optimize.rs::group_3_fax_images_become_group_4", "crates/optimize/tests/optimize.rs::rgb_and_two_colour_indexed_black_and_white_images_become_one_bit", "crates/optimize/tests/optimize.rs::black_and_white_rgb_used_beyond_the_page_content_read_stays_rgb", "crates/optimize/tests/optimize.rs::black_and_white_rgb_drawn_only_where_the_optimizer_reads_becomes_grey", "crates/optimize/tests/optimize.rs::black_and_white_rgb_in_resources_its_page_tree_and_a_form_share_becomes_grey", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]
+notes = "CCITT Group 4, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Packed to one bit first, then stored the same way (colour-key masks aside): eight-bit grey of only black and white, eight-bit DeviceRGB of only black and white (as DeviceGray; calibrated RGB, RGB with a profile, RGB drawn or listed where /DefaultGray or /DefaultRGB is in force or referred to from anywhere but the page and form resources read (an annotation's appearance or a pattern drawing it, directly or through resources or a form shared with a page; another image's /Alternates), and RGB whose soft mask has a /Matte aside), and an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1 (keeping its palette), unless the grey or colour settings make it smaller still, as they can a dithered scan downsampled to JPEG, its soft mask counted. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Group 3 fax images are stored again as Group 4 when that is smaller (damaged Group 3 with end-of-line codes as the decoder recovers it, as it reports no damage there; byte-aligned Group 3 with end-of-line codes but none before the first row, not as T.4 sends them, as PdfCraft draws it, which at /K 0 may be other rows than were coded). CCITT fax images are decoded to be downsampled (optimize.downsample-images), and a resampled image is stored as Group 4 or 1-bit Flate, whichever is smaller. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples."
[[feature]]
id = "optimize.only-if-smaller"