R7.6: Windows and Linux print (#3)

Windows prints through the system dialog at the document's paper;
Linux through the desktop portal, the dialog's choices laid out by Ely.
Round 3 findings fixed without a further review, as the rules say.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-16 16:59:46 -04:00
1 parent de4a38e814
commit 13546ea899
26 files changed
+2544 -114

No files matched your search

@@ -0,0 +1,245 @@
//! What the portal's dialog chose: its settings and page setup.
use std::collections::HashMap;
use anyhow::{Context as _, bail};
use zbus::zvariant::OwnedValue;
type Map = HashMap<String, OwnedValue>;
/// Which sheets print, counting from one.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Set {
All,
Even,
Odd,
}
/// How several pages fill one sheet.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Order {
pub across_first: bool,
pub leftward: bool,
pub upward: bool,
}
/// The dialog's choices; the app applies every one.
#[derive(Debug, PartialEq)]
pub(super) struct Choices {
/// Pages from zero, both ends kept; None is every page.
pub ranges: Option<Vec<(u32, u32)>>,
pub set: Set,
pub reverse: bool,
pub copies: u32,
pub collate: bool,
pub scale: f64,
pub up: u32,
pub order: Order,
/// The sheet as it lies, in points.
pub sheet: (f64, f64),
pub upside_down: bool,
}
/// GTK's settings and page setup, as the portal passes them.
pub(super) fn chosen(settings: &Map, setup: &Map) -> anyhow::Result<Choices> {
let ranges = match text(settings, "print-pages")?.unwrap_or("all") {
"all" => None,
"ranges" => Some(ranges(text(settings, "page-ranges")?.context("the print dialog gave no page ranges")?)?),
other => bail!("the print dialog chose the {other} pages; Ely offers none"),
};
let set = match text(settings, "page-set")?.unwrap_or("all") {
"all" => Set::All,
"even" => Set::Even,
"odd" => Set::Odd,
other => bail!("the print dialog chose the page set {other}"),
};
// GTK's CUPS backend sends even or odd to CUPS.
let set = match settings.contains_key("output-uri") || settings.contains_key("lpr-commandline") {
true => set,
false => Set::All,
};
let scale = number(settings, "scale", 100.0)? / 100.0;
if !(scale.is_finite() && scale > 0.0) {
bail!("the print dialog chose a scale of {}%", scale * 100.0);
}
let order = order(text(settings, "number-up-layout")?.unwrap_or("lrtb"))?;
let millimetres = |key: &str| -> anyhow::Result<f64> {
let value = setup.get(key).with_context(|| format!("the page setup gives no {key}"))?;
Ok(value.downcast_ref::<f64>().with_context(|| format!("the page setup's {key} is no number"))? * 72.0 / 25.4)
};
let (width, height) = (millimetres("Width")?, millimetres("Height")?);
let way = setup.get("Orientation").context("the page setup gives no orientation")?;
let (sheet, upside_down) = match way.downcast_ref::<&str>().context("the page setup's orientation is no text")? {
"portrait" => ((width, height), false),
"landscape" => ((height, width), false),
"reverse-portrait" => ((width, height), true),
"reverse-landscape" => ((height, width), true),
other => bail!("the page setup's orientation is {other}"),
};
Ok(Choices {
ranges,
set,
reverse: flag(settings, "reverse", false)?,
copies: count(settings, "n-copies")?,
collate: flag(settings, "collate", true)?,
scale,
up: count(settings, "number-up")?,
order,
sheet,
upside_down,
})
}
/// GTK's ranges, "0-2,4" from zero; end -1 runs on.
fn ranges(text: &str) -> anyhow::Result<Vec<(u32, u32)>> {
let page = |part: &str| part.trim().parse::<u32>().with_context(|| format!("the page range {text} is unreadable"));
let ranges = text
.split(',')
.filter(|part| !part.trim().is_empty())
.map(|part| {
let (from, to) = match part.split_once('-') {
Some((from, to)) if to.trim() == "-1" => (page(from)?, u32::MAX),
Some((from, to)) => (page(from)?, page(to)?),
None => (page(part)?, page(part)?),
};
if from > to {
bail!("the page range {text} runs backwards");
}
Ok((from, to))
})
.collect::<anyhow::Result<Vec<_>>>()?;
if ranges.is_empty() {
bail!("the page ranges are empty");
}
Ok(ranges)
}
/// GTK's n-up nick, such as "lrtb": first way, then next.
fn order(nick: &str) -> anyhow::Result<Order> {
let (first, then) = nick.split_at_checked(2).with_context(|| format!("the n-up layout {nick} is unknown"))?;
let across = |way: &str| matches!(way, "lr" | "rl");
let down = |way: &str| matches!(way, "tb" | "bt");
if !(across(first) && down(then) || down(first) && across(then)) {
bail!("the n-up layout {nick} is unknown");
}
Ok(Order { across_first: across(first), leftward: nick.contains("rl"), upward: nick.contains("bt") })
}
fn text<'a>(settings: &'a Map, key: &str) -> anyhow::Result<Option<&'a str>> {
let value = settings.get(key).map(|value| value.downcast_ref::<&str>());
value.transpose().with_context(|| format!("the print setting {key} is no text"))
}
fn number(settings: &Map, key: &str, unset: f64) -> anyhow::Result<f64> {
match text(settings, key)? {
Some(text) => text.trim().parse().with_context(|| format!("the print setting {key} is {text}")),
None => Ok(unset),
}
}
/// A whole number, at least one; one when unset.
fn count(settings: &Map, key: &str) -> anyhow::Result<u32> {
let count = match text(settings, key)? {
Some(text) => text.trim().parse().with_context(|| format!("the print setting {key} is {text}"))?,
None => 1,
};
if count == 0 {
bail!("the print setting {key} is zero");
}
Ok(count)
}
fn flag(settings: &Map, key: &str, unset: bool) -> anyhow::Result<bool> {
match text(settings, key)? {
None => Ok(unset),
Some("true") => Ok(true),
Some("false") => Ok(false),
Some(other) => bail!("the print setting {key} is {other}"),
}
}
#[cfg(test)]
mod tests {
use zbus::zvariant::{OwnedValue, Value};
use super::{Choices, Map, Order, Set, chosen};
fn map(pairs: &[(&str, Value<'static>)]) -> Map {
pairs.iter().map(|(key, value)| (key.to_string(), OwnedValue::try_from(value.clone()).expect("owned"))).collect()
}
fn a4(orientation: &'static str) -> Map {
map(&[("Width", Value::from(210.0)), ("Height", Value::from(297.0)), ("Orientation", Value::from(orientation))])
}
#[test]
fn unset_settings_print_everything_once() {
let choices = chosen(&Map::new(), &a4("portrait")).expect("reads");
let order = Order { across_first: true, leftward: false, upward: false };
let (width, height) = (210.0 * 72.0 / 25.4, 297.0 * 72.0 / 25.4);
assert_eq!(
choices,
Choices {
ranges: None,
set: Set::All,
reverse: false,
copies: 1,
collate: true,
scale: 1.0,
up: 1,
order,
sheet: (width, height),
upside_down: false
}
);
}
#[test]
fn gtk_settings_read_as_given() {
let settings = map(&[
("print-pages", Value::from("ranges")),
("page-ranges", Value::from("0-1, 4,7--1")),
("page-set", Value::from("even")),
("reverse", Value::from("true")),
("n-copies", Value::from("3")),
("collate", Value::from("false")),
("scale", Value::from("50")),
("number-up", Value::from("4")),
("number-up-layout", Value::from("btrl")),
("output-uri", Value::from("file:///tmp/out.pdf")),
]);
let choices = chosen(&settings, &a4("reverse-landscape")).expect("reads");
assert_eq!(choices.ranges, Some(vec![(0, 1), (4, 4), (7, u32::MAX)]));
assert_eq!((choices.set, choices.reverse, choices.copies, choices.collate), (Set::Even, true, 3, false));
assert_eq!((choices.scale, choices.up), (0.5, 4));
assert_eq!(choices.order, Order { across_first: false, leftward: true, upward: true });
assert_eq!((choices.sheet.0.round(), choices.sheet.1.round(), choices.upside_down), (842.0, 595.0, true));
}
#[test]
fn even_pages_are_ours_only_where_cups_leaves_them() {
let set = |backend: &[(&str, Value<'static>)]| {
let mut pairs = vec![("page-set", Value::from("even"))];
pairs.extend_from_slice(backend);
chosen(&map(&pairs), &a4("portrait")).expect("reads").set
};
// GTK's CUPS backend sends cups-page-set itself.
assert_eq!(set(&[("printer", Value::from("Office"))]), Set::All);
assert_eq!(set(&[("output-uri", Value::from("file:///tmp/out.pdf"))]), Set::Even);
assert_eq!(set(&[("lpr-commandline", Value::from("lpr"))]), Set::Even);
}
#[test]
fn what_cannot_be_honoured_fails() {
let bad = |pairs: &[(&str, Value<'static>)]| chosen(&map(pairs), &a4("portrait")).is_err();
assert!(bad(&[("print-pages", Value::from("selection"))]));
assert!(bad(&[("print-pages", Value::from("ranges")), ("page-ranges", Value::from("two"))]));
assert!(bad(&[("print-pages", Value::from("ranges")), ("page-ranges", Value::from("3-1"))]));
assert!(chosen(&Map::new(), &a4("reverse_portrait")).is_err(), "GTK writes reverse-portrait");
assert!(bad(&[("scale", Value::from("0"))]));
assert!(bad(&[("n-copies", Value::from("0"))]));
assert!(bad(&[("number-up-layout", Value::from("lrrl"))]));
assert!(bad(&[("reverse", Value::from(1u32))]));
assert!(chosen(&Map::new(), &map(&[("Width", Value::from(210.0))])).is_err(), "no height");
}
}
@@ -0,0 +1,388 @@
//! The chosen pages laid on the chosen sheets, as PDF.
use std::collections::BTreeMap;
use anyhow::{Context as _, anyhow, bail};
use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary};
use super::choices::{Choices, Set};
use crate::print::ROUNDING;
/// Catalog entries that name pages no longer there.
const STALE: [&str; 4] = ["Outlines", "OpenAction", "AcroForm", "PageLabels"];
/// A PDF matrix, `[a b c d e f]`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Matrix(pub [f64; 6]);
impl Matrix {
/// This, then `next`.
fn then(self, next: Matrix) -> Matrix {
let ([a, b, c, d, e, f], [g, h, i, j, k, l]) = (self.0, next.0);
Matrix([a * g + b * i, a * h + b * j, c * g + d * i, c * h + d * j, e * g + f * i + k, e * h + f * j + l])
}
pub(super) fn apply(self, (x, y): (f64, f64)) -> (f64, f64) {
let [a, b, c, d, e, f] = self.0;
(a * x + c * y + e, b * x + d * y + f)
}
}
/// A page's box, unit and turn.
pub(super) struct Shown {
corners: [f64; 4],
unit: f64,
turn: i64,
}
impl Shown {
pub(super) fn of(document: &Document, page: ObjectId) -> anyhow::Result<Self> {
let corners = |bounds: &Object| -> anyhow::Result<[f64; 4]> {
let numbers = bounds.as_array()?.iter().map(|n| Ok(f64::from(n.as_float()?))).collect::<anyhow::Result<Vec<_>>>()?;
let [x0, y0, x1, y1] = numbers[..] else {
bail!("a page box has {} numbers", numbers.len());
};
Ok([x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
};
let media = corners(inherited(document, page, b"MediaBox")?.ok_or_else(|| anyhow!("a page has no media box"))?)?;
// A crop box is cut to the media box.
let [x0, y0, x1, y1] = match inherited(document, page, b"CropBox")? {
Some(crop) => {
let crop = corners(crop)?;
[crop[0].max(media[0]), crop[1].max(media[1]), crop[2].min(media[2]), crop[3].min(media[3])]
}
None => media,
};
if x1 <= x0 || y1 <= y0 {
bail!("a page's crop box lies outside its media box");
}
// UserUnit is the page's own, never inherited.
let unit = match document.get_dictionary(page)?.get(b"UserUnit") {
Ok(unit) => f64::from(document.dereference(unit)?.1.as_float()?),
Err(_) => 1.0,
};
let turn = inherited(document, page, b"Rotate")?.map_or(Ok(0), Object::as_i64)?.rem_euclid(360);
if !(unit > 0.0 && turn % 90 == 0) {
bail!("a page has a unit of {unit} or a turn of {turn}");
}
Ok(Self { corners: [x0, y0, x1, y1], unit, turn })
}
/// Width and height in points, as it shows.
pub(super) fn size(&self) -> (f64, f64) {
let [x0, y0, x1, y1] = self.corners;
let (width, height) = ((x1 - x0) * self.unit, (y1 - y0) * self.unit);
// A page turned a quarter shows its other side up.
if self.turn % 180 == 90 { (height, width) } else { (width, height) }
}
/// From the page's own space to its shown points.
fn matrix(&self) -> Matrix {
let [x0, y0, x1, y1] = self.corners;
let (w, h) = ((x1 - x0) * self.unit, (y1 - y0) * self.unit);
let unit = Matrix([self.unit, 0.0, 0.0, self.unit, -x0 * self.unit, -y0 * self.unit]);
// Rotate turns the page clockwise as shown.
unit.then(Matrix(match self.turn {
90 => [0.0, -1.0, 1.0, 0.0, 0.0, w],
180 => [-1.0, 0.0, 0.0, -1.0, w, h],
270 => [0.0, 1.0, -1.0, 0.0, h, 0.0],
_ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
}))
}
}
/// `key` on the page or its nearest tree node.
pub(super) fn inherited<'a>(document: &'a Document, page: ObjectId, key: &[u8]) -> anyhow::Result<Option<&'a Object>> {
let mut node = document.get_dictionary(page)?;
// A loop in the tree must not hang.
for _ in 0..64 {
if let Ok(value) = node.get(key) {
return Ok(Some(document.dereference(value)?.1));
}
let Ok(parent) = node.get(b"Parent") else {
return Ok(None);
};
node = document.dereference(parent)?.1.as_dict()?;
}
bail!("the page tree is deeper than 64")
}
/// The PDF at `pdf`, laid out as `choices` asks.
pub(super) fn compose(pdf: &std::path::Path, choices: &Choices) -> anyhow::Result<Vec<u8>> {
let mut document = Document::load(pdf)?;
let pages: Vec<ObjectId> = document.get_pages().into_values().collect();
let picked = picked(choices, pages.len())?;
let mut forms = BTreeMap::new();
for &n in &picked {
if let std::collections::btree_map::Entry::Vacant(slot) = forms.entry(n) {
slot.insert(form(&mut document, pages[n])?);
}
}
let shown = picked.iter().map(|&n| Shown::of(&document, pages[n])).collect::<anyhow::Result<Vec<_>>>()?;
let laid = lay(choices, &picked, &shown)?;
let tree = document.new_object_id();
let (width, height) = choices.sheet;
let mut sheets = Vec::with_capacity(laid.len());
for placed in &laid {
let mut drawn = String::new();
let mut objects = Dictionary::new();
for &(n, Matrix([a, b, c, d, e, f])) in placed {
drawn.push_str(&format!("q {a:.4} {b:.4} {c:.4} {d:.4} {e:.4} {f:.4} cm /P{n} Do Q\n"));
objects.set(format!("P{n}"), forms[&n]);
}
let mut stream = Stream::new(Dictionary::new(), drawn.into_bytes());
stream.compress()?;
let contents = document.add_object(stream);
let media: Vec<Object> = vec![0.into(), 0.into(), (width as f32).into(), (height as f32).into()];
let mut sheet = dictionary! {
"Type" => "Page",
"Parent" => tree,
"MediaBox" => media,
"Resources" => dictionary! { "XObject" => objects },
"Contents" => contents,
};
if choices.upside_down {
sheet.set("Rotate", 180);
}
sheets.push(sheet);
}
let kids: Vec<Object> = arrange(choices, sheets.len())?.into_iter().map(|n| document.add_object(sheets[n].clone()).into()).collect();
let count = kids.len() as i64;
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => count }.into());
let root = document.trailer.get(b"Root")?.as_reference()?;
let catalog = document.get_object_mut(root)?.as_dict_mut()?;
catalog.set("Pages", tree);
for key in STALE {
catalog.remove(key.as_bytes());
}
document.prune_objects();
let mut bytes = Vec::new();
document.save_to(&mut bytes)?;
Ok(bytes)
}
/// The chosen pages, from zero, in the dialog's order.
fn picked(choices: &Choices, count: usize) -> anyhow::Result<Vec<usize>> {
let last = count.checked_sub(1).context("the document has no pages")? as u32;
let picked: Vec<usize> = match &choices.ranges {
None => (0..count).collect(),
Some(ranges) => ranges.iter().filter(|(from, _)| *from <= last).flat_map(|&(from, to)| from as usize..=to.min(last) as usize).collect(),
};
if picked.is_empty() {
bail!("none of the chosen pages are in the document");
}
Ok(picked)
}
/// Sheets in print order: set, reverse, then copies.
fn arrange(choices: &Choices, sheets: usize) -> anyhow::Result<Vec<usize>> {
let mut order: Vec<usize> = (0..sheets)
.filter(|n| match choices.set {
Set::All => true,
Set::Even => n % 2 == 1,
Set::Odd => n % 2 == 0,
})
.collect();
if order.is_empty() {
bail!("the chosen page set leaves no sheet to print");
}
if choices.reverse {
order.reverse();
}
let copies = choices.copies as usize;
Ok(match choices.collate {
true => order.iter().copied().cycle().take(order.len() * copies).collect(),
false => order.into_iter().flat_map(|n| std::iter::repeat_n(n, copies)).collect(),
})
}
/// Each sheet's pages: which page, and where it goes.
fn lay(choices: &Choices, picked: &[usize], shown: &[Shown]) -> anyhow::Result<Vec<Vec<(usize, Matrix)>>> {
let (width, height) = choices.sheet;
if choices.up == 1 {
return picked
.iter()
.zip(shown)
.map(|(&n, page)| {
let (w, h) = page.size();
let k = choices.scale;
let fits = |across: f64, down: f64| k * across <= width + ROUNDING && k * down <= height + ROUNDING;
// Placed from the sheet's top left; turned left if needed.
let place = match (fits(w, h), fits(h, w)) {
(true, _) => Matrix([k, 0.0, 0.0, k, 0.0, height - k * h]),
(false, true) => Matrix([0.0, k, -k, 0.0, k * h, height - k * w]),
(false, false) => bail!(
"page {} at {:.0}% is larger than the {:.0} × {:.0} mm paper",
n + 1,
k * 100.0,
width * 25.4 / 72.0,
height * 25.4 / 72.0
),
};
Ok(vec![(n, page.matrix().then(place))])
})
.collect();
}
let (cols, rows) = grid(choices.up, choices.sheet, shown);
let (cell_w, cell_h) = (width / f64::from(cols), height / f64::from(rows));
let mut sheets = Vec::new();
for (pages, looks) in picked.chunks(choices.up as usize).zip(shown.chunks(choices.up as usize)) {
let placed = pages.iter().zip(looks).enumerate().map(|(slot, (&n, page))| {
let (col, row) = cell(slot as u32, (cols, rows), choices);
let (w, h) = page.size();
let k = (cell_w / w).min(cell_h / h) * choices.scale;
// Centred in its cell.
let left = f64::from(col) * cell_w + (cell_w - k * w) / 2.0;
let bottom = height - f64::from(row + 1) * cell_h + (cell_h - k * h) / 2.0;
(n, page.matrix().then(Matrix([k, 0.0, 0.0, k, left, bottom])))
});
sheets.push(placed.collect());
}
Ok(sheets)
}
/// Columns and rows for `up` pages; the largest fit best.
fn grid(up: u32, (width, height): (f64, f64), shown: &[Shown]) -> (u32, u32) {
let (w, h) = shown.iter().map(Shown::size).fold((0.0, 0.0), |(a, b), (w, h)| (w.max(a), h.max(b)));
let fit = |(cols, rows): (u32, u32)| (width / f64::from(cols) / w).min(height / f64::from(rows) / h);
let grids = (1..=up).filter(|&cols| up.is_multiple_of(cols)).map(|cols| (cols, up / cols));
grids.fold((up, 1), |best, grid| if fit(grid) > fit(best) { grid } else { best })
}
/// Slot `n`'s column and row, by the dialog's n-up order.
fn cell(n: u32, (cols, rows): (u32, u32), choices: &Choices) -> (u32, u32) {
let order = choices.order;
let (col, row) = if order.across_first { (n % cols, n / cols) } else { (n / rows, n % rows) };
(if order.leftward { cols - 1 - col } else { col }, if order.upward { rows - 1 - row } else { row })
}
/// The page as a form, printable annotations drawn on top.
fn form(document: &mut Document, page: ObjectId) -> anyhow::Result<ObjectId> {
let mut drawn = b"q\n".to_vec();
for content in document.get_page_contents(page) {
drawn.extend(document.get_object(content)?.as_stream()?.decompressed_content()?);
drawn.push(b'\n');
}
drawn.extend(b"Q\n");
let mut resources = match inherited(document, page, b"Resources")? {
Some(resources) => resources.as_dict()?.clone(),
None => Dictionary::new(),
};
let mut objects = match resources.get(b"XObject") {
Ok(objects) => document.dereference(objects)?.1.as_dict()?.clone(),
Err(_) => Dictionary::new(),
};
let mut n = 0;
for (look, place) in appearances(document, page)? {
// Names the page already uses stay its own.
while objects.has(format!("ElyAnnot{n}").as_bytes()) {
n += 1;
}
let [a, b, c, d, e, f] = place.0;
drawn.extend(format!("q {a:.4} {b:.4} {c:.4} {d:.4} {e:.4} {f:.4} cm /ElyAnnot{n} Do Q\n").into_bytes());
objects.set(format!("ElyAnnot{n}"), look);
let look = document.get_object_mut(look)?.as_stream_mut()?;
if look.dict.get(b"Subtype").is_err() {
look.dict.set("Subtype", "Form");
}
}
resources.set("XObject", objects);
let [x0, y0, x1, y1] = Shown::of(document, page)?.corners;
let bounds: Vec<Object> = [x0, y0, x1, y1].into_iter().map(|n| (n as f32).into()).collect();
let mut dict = dictionary! { "Type" => "XObject", "Subtype" => "Form", "BBox" => bounds, "Resources" => resources };
if let Some(group) = inherited(document, page, b"Group")? {
dict.set("Group", group.clone());
}
let mut stream = Stream::new(dict, drawn);
stream.compress()?;
Ok(document.add_object(stream))
}
/// Printable annotations' looks, and where each goes on the page.
fn appearances(document: &Document, page: ObjectId) -> anyhow::Result<Vec<(ObjectId, Matrix)>> {
let Ok(annots) = document.get_dictionary(page)?.get(b"Annots") else {
return Ok(Vec::new());
};
let turn = Shown::of(document, page)?.turn;
let mut looks = Vec::new();
for annot in document.dereference(annots)?.1.as_array()? {
let annot = document.dereference(annot)?.1.as_dict()?;
let flags = annot.get(b"F").and_then(Object::as_i64).unwrap_or(0);
// Hidden, or not marked for print: left out.
if flags & 2 != 0 || flags & 4 == 0 {
continue;
}
let Some(look) = appearance(document, annot)? else {
continue;
};
let stream = document.get_object(look)?.as_stream()?;
let numbers = |object: &Object| -> anyhow::Result<Vec<f64>> {
document.dereference(object)?.1.as_array()?.iter().map(|n| Ok(f64::from(n.as_float()?))).collect()
};
let bounds = numbers(stream.dict.get(b"BBox")?)?;
let rect = numbers(annot.get(b"Rect")?)?;
let own = match stream.dict.get(b"Matrix") {
Ok(matrix) => Matrix(numbers(matrix)?.try_into().map_err(|_| anyhow!("an appearance matrix is not six numbers"))?),
Err(_) => Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]),
};
let ([bx0, by0, bx1, by1], [rx0, ry0, rx1, ry1]) = (four(&bounds)?, four(&rect)?);
// The look's box, through its matrix, fills the rectangle.
let corners = [(bx0, by0), (bx1, by0), (bx0, by1), (bx1, by1)].map(|corner| own.apply(corner));
let (lx0, ly0) = corners.iter().fold((f64::MAX, f64::MAX), |(x, y), &(a, b)| (x.min(a), y.min(b)));
let (lx1, ly1) = corners.iter().fold((f64::MIN, f64::MIN), |(x, y), &(a, b)| (x.max(a), y.max(b)));
if lx1 - lx0 <= 0.0 || ly1 - ly0 <= 0.0 {
continue;
}
let (sx, sy) = ((rx1 - rx0).abs() / (lx1 - lx0), (ry1 - ry0).abs() / (ly1 - ly0));
let mut place = Matrix([sx, 0.0, 0.0, sy, rx0.min(rx1) - sx * lx0, ry0.min(ry1) - sy * ly0]);
// NoRotate: upright as shown, turned about its top left.
if flags & 16 != 0 {
place = place.then(unturned(turn, (rx0.min(rx1), ry0.max(ry1))));
}
looks.push((look, place));
}
Ok(looks)
}
/// Turns back a page's `turn` about `(x, y)`.
fn unturned(turn: i64, (x, y): (f64, f64)) -> Matrix {
let (cos, sin) = match turn {
90 => (0.0, 1.0),
180 => (-1.0, 0.0),
270 => (0.0, -1.0),
_ => (1.0, 0.0),
};
Matrix([cos, sin, -sin, cos, x - cos * x + sin * y, y - sin * x - cos * y])
}
fn four(numbers: &[f64]) -> anyhow::Result<[f64; 4]> {
numbers.try_into().map_err(|_| anyhow!("an annotation's box is not four numbers"))
}
/// An annotation's normal look in its state; None draws nothing.
fn appearance(document: &Document, annot: &Dictionary) -> anyhow::Result<Option<ObjectId>> {
let subtype = annot.get(b"Subtype")?.as_name()?;
let normal = match annot.get(b"AP") {
Ok(looks) => document.dereference(looks)?.1.as_dict()?.get(b"N").ok(),
Err(_) => None,
};
let Some(normal) = normal else {
// Links and popups have no look of their own.
if matches!(subtype, b"Link" | b"Popup") {
return Ok(None);
}
bail!("a printable {} annotation has no appearance", String::from_utf8_lossy(subtype));
};
if let Ok(id) = normal.as_reference()
&& document.get_object(id)?.as_stream().is_ok()
{
return Ok(Some(id));
}
// A look per state: the one /AS names, if any.
let states = document.dereference(normal)?.1.as_dict()?;
let state = annot.get(b"AS").and_then(Object::as_name).context("an annotation with states names none")?;
Ok(states.get(state).ok().map(Object::as_reference).transpose()?)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,307 @@
use lopdf::{Document, Object, Stream, content::Content, dictionary};
use super::{Choices, Set, Shown, compose};
use crate::print::linux::choices::Order;
/// Pages with these boxes, each with these extra entries.
fn pages(boxes: &[([f32; 4], lopdf::Dictionary)]) -> (tempfile::TempDir, std::path::PathBuf) {
let mut document = Document::with_version("1.7");
let tree = document.new_object_id();
let kids: Vec<Object> = boxes
.iter()
.map(|(corners, extra)| {
let content = document.add_object(Stream::new(dictionary! {}, b"0 g 0 0 10 10 re f".to_vec()));
let media: Vec<Object> = corners.iter().map(|&n| n.into()).collect();
let mut page = dictionary! { "Type" => "Page", "Parent" => tree, "MediaBox" => media, "Contents" => content };
page.extend(extra);
document.add_object(page).into()
})
.collect();
let count = kids.len() as i64;
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => count }.into());
let catalog = document.add_object(dictionary! { "Type" => "Catalog", "Pages" => tree });
document.trailer.set("Root", catalog);
let folder = tempfile::tempdir().expect("a folder");
let pdf = folder.path().join("pages.pdf");
document.save(&pdf).expect("saves");
(folder, pdf)
}
fn plain(box_: [f32; 4]) -> ([f32; 4], lopdf::Dictionary) {
(box_, dictionary! {})
}
fn choices(sheet: (f64, f64)) -> Choices {
Choices {
ranges: None,
set: Set::All,
reverse: false,
copies: 1,
collate: true,
scale: 1.0,
up: 1,
order: Order { across_first: true, leftward: false, upward: false },
sheet,
upside_down: false,
}
}
/// A sheet's size; each form's width and placed corners.
type Sheet = ((i64, i64), Vec<(i64, [i64; 4])>);
fn sheets(bytes: &[u8]) -> Vec<Sheet> {
let document = Document::load_mem(bytes).expect("a PDF");
let round = |n: f64| n.round() as i64;
document
.get_pages()
.into_values()
.map(|page| {
let dict = document.get_dictionary(page).expect("a page");
let media: Vec<f64> = dict.get(b"MediaBox").and_then(Object::as_array).expect("a box").iter().map(|n| f64::from(n.as_float().expect("a number"))).collect();
let content = Content::decode(&document.get_page_content(page)).expect("content");
let objects = dict.get(b"Resources").and_then(Object::as_dict).and_then(|r| r.get(b"XObject")).and_then(Object::as_dict).expect("forms");
let mut matrix = [1.0; 6];
let mut placed = Vec::new();
for op in content.operations {
match op.operator.as_str() {
"cm" => matrix = op.operands.iter().map(|n| f64::from(n.as_float().expect("a number"))).collect::<Vec<_>>().try_into().expect("six"),
"Do" => {
let form = objects.get(op.operands[0].as_name().expect("a name")).and_then(Object::as_reference).expect("a form");
let bounds: Vec<f64> = document.get_object(form).and_then(Object::as_stream).expect("a stream").dict.get(b"BBox").and_then(Object::as_array).expect("a box").iter().map(|n| f64::from(n.as_float().expect("a number"))).collect();
let m = super::Matrix(matrix);
let corners = [(bounds[0], bounds[1]), (bounds[2], bounds[3])].map(|corner| m.apply(corner));
let (x0, x1) = (corners[0].0.min(corners[1].0), corners[0].0.max(corners[1].0));
let (y0, y1) = (corners[0].1.min(corners[1].1), corners[0].1.max(corners[1].1));
placed.push((round(bounds[2] - bounds[0]), [x0, y0, x1, y1].map(round)));
}
_ => {}
}
}
((round(media[2]), round(media[3])), placed)
})
.collect()
}
#[test]
fn a_user_unit_scales_the_page() {
let (_folder, pdf) = pages(&[([0.0, 0.0, 421.0, 297.5], dictionary! { "UserUnit" => 2 })]);
let document = Document::load(&pdf).expect("loads");
let page = document.get_pages()[&1];
assert_eq!(Shown::of(&document, page).expect("reads").size(), (842.0, 595.0));
// On A4 landscape it fills the sheet, from its corner.
let laid = sheets(&compose(&pdf, &choices((842.0, 595.0))).expect("composes"));
assert_eq!(laid, [((842, 595), vec![(421, [0, 0, 842, 595])])]);
}
#[test]
fn chosen_pages_print_scaled_from_the_top_left() {
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 595.0, 842.0]), plain([0.0, 0.0, 420.0, 595.0]), plain([0.0, 0.0, 300.0, 300.0])]);
let only_second = Choices { ranges: Some(vec![(1, 1)]), scale: 0.5, ..choices((595.0, 842.0)) };
let laid = sheets(&compose(&pdf, &only_second).expect("composes"));
assert_eq!(laid, [((595, 842), vec![(420, [0, 545, 210, 842])])]);
}
#[test]
fn a_page_that_fits_only_turned_turns_left() {
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 842.0, 595.0])]);
let bytes = compose(&pdf, &choices((595.0, 842.0))).expect("composes");
assert_eq!(sheets(&bytes), [((595, 842), vec![(842, [0, 0, 595, 842])])]);
// Its top left lands at the sheet's bottom left.
let document = Document::load_mem(&bytes).expect("a PDF");
let content = Content::decode(&document.get_page_content(document.get_pages()[&1])).expect("content");
let cm = content.operations.iter().find(|op| op.operator == "cm").expect("a matrix");
let m: Vec<f64> = cm.operands.iter().map(|n| f64::from(n.as_float().expect("a number"))).collect();
let corner = super::Matrix(m.try_into().expect("six")).apply((0.0, 595.0));
assert_eq!((corner.0.round(), corner.1.round()), (0.0, 0.0));
}
#[test]
fn a_crop_box_past_the_media_box_is_cut_to_it() {
let crop = |corners: [i64; 4]| -> Object { corners.map(Object::from).to_vec().into() };
let (_folder, pdf) = pages(&[([0.0, 0.0, 612.0, 792.0], dictionary! { "CropBox" => crop([0, 0, 700, 792]) })]);
// The form's box clips at 612: x 650 stays hidden.
let laid = sheets(&compose(&pdf, &choices((612.0, 792.0))).expect("composes"));
assert_eq!(laid, [((612, 792), vec![(612, [0, 0, 612, 792])])]);
let (_folder, pdf) = pages(&[([0.0, 0.0, 612.0, 792.0], dictionary! { "CropBox" => crop([700, 0, 800, 792]) })]);
assert!(compose(&pdf, &choices((612.0, 792.0))).is_err(), "nothing left to show");
}
#[test]
fn a_rotated_page_shows_turned() {
let (_folder, pdf) = pages(&[([0.0, 0.0, 595.0, 842.0], dictionary! { "Rotate" => 90 })]);
let document = Document::load(&pdf).expect("loads");
let shown = Shown::of(&document, document.get_pages()[&1]).expect("reads");
assert_eq!(shown.size(), (842.0, 595.0));
// Turned clockwise, the page's top left becomes its top right.
assert_eq!(shown.matrix().apply((0.0, 842.0)), (842.0, 595.0));
}
#[test]
fn too_large_a_page_fails() {
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 1000.0, 600.0])]);
let error = compose(&pdf, &choices((595.0, 842.0))).expect_err("does not fit");
assert!(error.to_string().contains("page 1 at 100% is larger than the 210 × 297 mm paper"), "{error}");
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 595.0, 842.0])]);
assert!(compose(&pdf, &Choices { scale: 2.0, ..choices((595.0, 842.0)) }).is_err(), "scaled past the paper");
// A4 is 595.28 points wide: 600 would lose its edge.
let a4 = (210.0 * 72.0 / 25.4, 297.0 * 72.0 / 25.4);
let (_folder, pdf) = pages(&[plain([0.0, 0.0, 600.0, 842.0])]);
assert!(compose(&pdf, &choices(a4)).is_err(), "a page 1.6 mm wider than A4");
// A4 in whole points still takes an A4 page.
let (_folder, pdf) = pages(&[plain([0.0, 0.0, a4.0 as f32, a4.1 as f32])]);
assert!(compose(&pdf, &choices((595.0, 842.0))).is_ok(), "rounding is no overflow");
}
#[test]
fn an_open_gtk_range_runs_to_the_last_page() {
use zbus::zvariant::{OwnedValue, Value};
let widths = [100.0, 110.0, 120.0];
let boxes: Vec<_> = widths.iter().map(|&w| plain([0.0, 0.0, w, 100.0])).collect();
let (_folder, pdf) = pages(&boxes);
let owned = |value: Value<'static>| OwnedValue::try_from(value).expect("owned");
let settings = [("print-pages", "ranges"), ("page-ranges", "1--1")].map(|(key, value)| (key.to_string(), owned(Value::from(value))));
let setup = [("Width", Value::from(210.0)), ("Height", Value::from(297.0)), ("Orientation", Value::from("portrait"))];
let setup = setup.map(|(key, value)| (key.to_string(), owned(value)));
let chosen = super::super::choices::chosen(&settings.into(), &setup.into()).expect("reads");
let printed: Vec<i64> = sheets(&compose(&pdf, &chosen).expect("composes")).iter().map(|sheet| sheet.1[0].0).collect();
assert_eq!(printed, [110, 120], "pages two and three");
}
#[test]
fn four_up_fills_cells_in_the_chosen_order() {
let sizes = [100.0, 110.0, 120.0, 130.0, 140.0];
let boxes: Vec<_> = sizes.iter().map(|&w| plain([0.0, 0.0, w, w * 1.5])).collect();
let (_folder, pdf) = pages(&boxes);
let up = Choices { up: 4, ..choices((400.0, 600.0)) };
let laid = sheets(&compose(&pdf, &up).expect("composes"));
assert_eq!(laid.len(), 2, "five pages, four a sheet");
let corner = |(width, [x0, _, _, y1]): &(i64, [i64; 4])| (*width, x0 / 200, (600 - y1) / 300);
let cells: Vec<_> = laid[0].1.iter().map(corner).collect();
assert_eq!(cells, [(100, 0, 0), (110, 1, 0), (120, 0, 1), (130, 1, 1)]);
// Every page fills its 200 × 300 cell, centred.
assert_eq!(laid[1].1, [(140, [0, 300, 200, 600])]);
let upward = Choices { order: Order { across_first: false, leftward: true, upward: true }, ..up };
let laid = sheets(&compose(&pdf, &upward).expect("composes"));
let cells: Vec<_> = laid[0].1.iter().map(corner).collect();
assert_eq!(cells, [(100, 1, 1), (110, 1, 0), (120, 0, 1), (130, 0, 0)]);
}
#[test]
fn sets_order_and_copies_choose_the_sheets() {
let widths = [100.0, 110.0, 120.0];
let boxes: Vec<_> = widths.iter().map(|&w| plain([0.0, 0.0, w, 100.0])).collect();
let (_folder, pdf) = pages(&boxes);
let order = |chosen: Choices| -> Vec<i64> { sheets(&compose(&pdf, &chosen).expect("composes")).iter().map(|sheet| sheet.1[0].0).collect() };
let base = choices((595.0, 842.0));
assert_eq!(order(Choices { set: Set::Odd, ..choices((595.0, 842.0)) }), [100, 120]);
assert_eq!(order(Choices { set: Set::Even, ..choices((595.0, 842.0)) }), [110]);
assert_eq!(order(Choices { reverse: true, ..choices((595.0, 842.0)) }), [120, 110, 100]);
assert_eq!(order(Choices { copies: 2, ..choices((595.0, 842.0)) }), [100, 110, 120, 100, 110, 120]);
assert_eq!(order(Choices { copies: 2, collate: false, ..base }), [100, 100, 110, 110, 120, 120]);
let none = compose(&pdf, &Choices { ranges: Some(vec![(5, 9)]), ..choices((595.0, 842.0)) });
assert!(none.is_err(), "no chosen page is in the document");
}
#[test]
fn printable_annotations_are_drawn_where_they_sit() {
let mut document = Document::with_version("1.7");
let look = document.add_object(Stream::new(
dictionary! { "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 10.into(), 20.into()] },
b"0 g 0 0 10 20 re f".to_vec(),
));
let rect = |x: i64| -> Object { vec![x.into(), 100.into(), (x + 30).into(), 160.into()].into() };
let shown = dictionary! { "Subtype" => "Square", "F" => 4, "Rect" => rect(50), "AP" => dictionary! { "N" => look } };
let unprinted = dictionary! { "Subtype" => "Square", "F" => 0, "Rect" => rect(200), "AP" => dictionary! { "N" => look } };
let annots: Vec<Object> = vec![document.add_object(shown).into(), document.add_object(unprinted).into()];
let tree = document.new_object_id();
let content = document.add_object(Stream::new(dictionary! {}, Vec::new()));
let media: Vec<Object> = vec![0.into(), 0.into(), 595.into(), 842.into()];
let page = document.add_object(dictionary! { "Type" => "Page", "Parent" => tree, "MediaBox" => media, "Contents" => content, "Annots" => annots });
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }.into());
let looks = super::appearances(&document, page).expect("reads");
assert_eq!(looks.len(), 1, "only the printable one");
let (id, place) = looks[0];
assert_eq!(id, look);
assert_eq!((place.apply((0.0, 0.0)), place.apply((10.0, 20.0))), ((50.0, 100.0), (80.0, 160.0)));
}
/// One A4 page, turned `rotate`: its annotations and own forms.
fn annotated(rotate: i64, build: impl FnOnce(&mut Document) -> (Vec<lopdf::Dictionary>, lopdf::Dictionary)) -> (Document, lopdf::ObjectId) {
let mut document = Document::with_version("1.7");
let (annots, own) = build(&mut document);
let annots: Vec<Object> = annots.into_iter().map(|annot| document.add_object(annot).into()).collect();
let tree = document.new_object_id();
let content = document.add_object(Stream::new(dictionary! {}, b"/ElyAnnot0 Do".to_vec()));
let media: Vec<Object> = vec![0.into(), 0.into(), 595.into(), 842.into()];
let resources = dictionary! { "XObject" => own };
let page = dictionary! { "Type" => "Page", "Parent" => tree, "MediaBox" => media, "Contents" => content, "Annots" => annots, "Rotate" => rotate, "Resources" => resources };
let page = document.add_object(page);
document.objects.insert(tree, dictionary! { "Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1 }.into());
(document, page)
}
fn square(document: &mut Document, flags: i64) -> lopdf::Dictionary {
let look = document.add_object(Stream::new(
dictionary! { "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 100.into(), 80.into()] },
b"1 0 0 rg 0 0 100 80 re f".to_vec(),
));
let rect: Vec<Object> = vec![50.into(), 100.into(), 150.into(), 180.into()];
dictionary! { "Subtype" => "Square", "F" => flags, "Rect" => rect, "AP" => dictionary! { "N" => look } }
}
#[test]
fn a_no_rotate_annotation_stays_upright_about_its_top_left() {
let (document, page) = annotated(90, |document| (vec![square(document, 20)], dictionary! {}));
let (_, place) = super::appearances(&document, page).expect("reads")[0];
let shown = Shown::of(&document, page).expect("reads").matrix();
let at = |corner| {
let (x, y) = shown.apply(place.apply(corner));
(x.round(), y.round())
};
// Shown: its top left stays put, its top runs right.
assert_eq!(at((0.0, 80.0)), (180.0, 545.0));
assert_eq!(at((100.0, 80.0)), (280.0, 545.0));
assert_eq!(at((0.0, 0.0)), (180.0, 465.0));
// Without the flag, it turns with the page.
let (document, page) = annotated(90, |document| (vec![square(document, 4)], dictionary! {}));
let (_, place) = super::appearances(&document, page).expect("reads")[0];
let (x, y) = shown.apply(place.apply((0.0, 80.0)));
assert_eq!((x.round(), y.round()), (180.0, 545.0));
let (x, y) = shown.apply(place.apply((100.0, 80.0)));
assert_eq!((x.round(), y.round()), (180.0, 445.0));
}
#[test]
fn an_annotation_name_leaves_the_page_its_own() {
let mut blue = None;
let (mut document, page) = annotated(0, |document| {
let form = dictionary! { "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 1.into(), 1.into()] };
let own = *blue.insert(document.add_object(Stream::new(form, b"0 0 1 rg".to_vec())));
(vec![square(document, 4)], dictionary! { "ElyAnnot0" => own })
});
let blue = blue.expect("made");
let form = super::form(&mut document, page).expect("a form");
let form = document.get_object(form).and_then(Object::as_stream).expect("a stream");
let objects = form.dict.get(b"Resources").and_then(Object::as_dict).and_then(|r| r.get(b"XObject")).and_then(Object::as_dict).expect("forms");
assert_eq!(objects.get(b"ElyAnnot0").and_then(Object::as_reference).expect("kept"), blue);
let drawn = String::from_utf8(form.decompressed_content().expect("content")).expect("text");
assert!(drawn.contains("/ElyAnnot0 Do") && drawn.contains("/ElyAnnot1 Do"), "{drawn}");
let added = objects.get(b"ElyAnnot1").and_then(Object::as_reference).expect("the annotation's");
assert_ne!(added, blue);
}
#[test]
fn a_printable_annotation_without_a_look_fails() {
let rect: Vec<Object> = vec![50.into(), 100.into(), 150.into(), 180.into()];
let bare = dictionary! { "Subtype" => "Square", "F" => 4, "Rect" => rect.clone() };
let (document, page) = annotated(0, |_| (vec![bare], dictionary! {}));
let error = super::appearances(&document, page).expect_err("cannot be drawn");
assert!(error.to_string().contains("a printable Square annotation has no appearance"), "{error}");
// A link draws nothing; an unset state draws nothing.
let link = dictionary! { "Subtype" => "Link", "F" => 4, "Rect" => rect.clone() };
let (mut document, page) = annotated(0, |_| (vec![link], dictionary! {}));
assert!(super::appearances(&document, page).expect("reads").is_empty());
let on = document.add_object(Stream::new(dictionary! { "BBox" => vec![0.into(), 0.into(), 1.into(), 1.into()] }, Vec::new()));
let off = dictionary! { "Subtype" => "Widget", "F" => 4, "Rect" => rect, "AS" => "Off", "AP" => dictionary! { "N" => dictionary! { "Yes" => on } } };
assert_eq!(super::appearance(&document, &off).expect("reads"), None);
}