Set Page Boxes crops the margin you type on UserUnit pages (#7445)

* Convert Set Page Boxes margins by the page UserUnit

The dialog's margins are physical (pt, in, mm, cm) but were written as user-space units, so a UserUnit 2 page cropped twice the requested margin.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Say that page_set_box margins are user-space units

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Print readiness reads page boxes in points; Set Page Boxes batch keeps its wording

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Valentin KleinandClaude Sonnet 5.5 authored and GitHub committed 2026-11-18 00:31:36 -06:00
1 parent c4e174675e
commit df3f58d8b8
8 files changed
+147 -22

No files matched your search

+1 -1
View File
@@ -1207,7 +1207,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"page_set_box",
"Set page boxes / crop",
"Set a page box (crop by default; also trim, bleed, art, media) on pages: either margins in points from the media box [left, bottom, right, top], or an absolute rect in points from the top-left of the displayed page. Omit both to reset the box to its default. Undoable.",
"Set a page box (crop by default; also trim, bleed, art, media) on pages: either margins from the media box [left, bottom, right, top] in default user-space units of the unrotated page (not points when the page has /UserUnit), or an absolute rect in points from the top-left of the displayed page. Omit both to reset the box to its default. Undoable.",
)
.cmd("page.boxes")
.with(schema(
+11
View File
@@ -728,6 +728,17 @@ impl Document {
self.editor.as_ref().and_then(|e| pdfcraft_organize::page_boxes(&e.cos).ok()).unwrap_or_default()
}
/// Every page's `/UserUnit`: points per user-space unit, read as Acrobat reads it (1 when absent or invalid).
pub fn page_user_units(&self) -> Vec<f64> {
self.editor.as_ref().map(|e| pdfcraft_model::pages(&e.cos).iter().map(|p| p.user_unit(&e.cos)).collect()).unwrap_or_default()
}
/// Page `page`'s `/UserUnit` (see [`Self::page_user_units`]); 1 when there is no such page.
pub fn page_user_unit(&self, page: usize) -> f64 {
let Some(e) = self.editor.as_ref() else { return 1.0 };
pdfcraft_model::page_at(&e.cos, page).map_or(1.0, |p| p.user_unit(&e.cos))
}
/// Current value of a document-information entry (Title, Author, …).
pub fn info_value(&self, key: &str) -> Option<String> {
self.editor.as_ref().and_then(|e| pdfcraft_organize::info(&e.cos, key))
+24 -5
View File
@@ -256,15 +256,18 @@ fn page_reports(doc: &Document, pages: &[pdfcraft_model::Page]) -> Vec<PageBoxes
let row = boxes.get(i).copied().unwrap_or([[0.0; 4]; 5]);
let trim = row[3];
let bleed = row[2];
// The boxes are in user space; a `/UserUnit` page counts each unit as that many points.
let u = page.user_unit(doc);
let (pt_mm, rect_mm) = (|points: f64| mm(points * u), |rect: [f64; 4]| wh_mm(rect).map(|v| v * u));
PageBoxes {
page: (i + 1) as u32,
media_mm: wh_mm(row[0]),
crop_mm: wh_mm(row[1]),
trim_mm: wh_mm(trim),
bleed_mm: wh_mm(bleed),
media_mm: rect_mm(row[0]),
crop_mm: rect_mm(row[1]),
trim_mm: rect_mm(trim),
bleed_mm: rect_mm(bleed),
trim_set: page.dict.contains(b"TrimBox"),
bleed_set: page.dict.contains(b"BleedBox"),
bleed_margin_mm: [mm(trim[0] - bleed[0]), mm(trim[1] - bleed[1]), mm(bleed[2] - trim[2]), mm(bleed[3] - trim[3])],
bleed_margin_mm: [pt_mm(trim[0] - bleed[0]), pt_mm(trim[1] - bleed[1]), pt_mm(bleed[2] - trim[2]), pt_mm(bleed[3] - trim[3])],
}
})
.collect()
@@ -433,6 +436,22 @@ mod tests {
assert!(report.text().contains("verification only"));
}
#[test]
fn box_sizes_and_bleed_follow_the_pages_user_unit() {
let mut doc = Document::new_empty();
let img = image(&mut doc, 600, 600);
let p = page(&mut doc, "Im", img, "q 72 0 0 72 36 36 cm /Im Do Q");
doc.update_dict(p, |d| {
d.set(b"UserUnit".to_vec(), Object::Int(2));
d.set(b"TrimBox".to_vec(), Object::Array(vec![1.into(), 1.into(), 611.into(), 791.into()]));
})
.unwrap();
let page = &inspect(&doc).pages[0];
// 612 x 792 user units of 2 points each.
assert!((page.media_mm[0] - 612.0 * 2.0 * 25.4 / 72.0).abs() < 1e-9, "{:?}", page.media_mm);
assert!((page.bleed_margin_mm[0] - 2.0 * 25.4 / 72.0).abs() < 1e-9, "{:?}", page.bleed_margin_mm);
}
#[test]
fn untrimmed_pages_get_one_note_and_a_tight_trim_gets_a_warning() {
let mut doc = Document::new_empty();
+5
View File
@@ -100,6 +100,11 @@ pub fn pages(doc: &Document) -> Vec<Page> {
PageTree::new(doc).collect()
}
/// Leaf page `index` (0-based), walking the page tree only as far as it.
pub fn page_at(doc: &Document, index: usize) -> Option<Page> {
PageTree::new(doc).nth(index)
}
/// Approximate bytes of inherited values copied into leaf dictionaries by one page walk.
pub const MAX_INHERITED_COPIES: usize = 1 << 30;
+2 -1
View File
@@ -48,7 +48,8 @@ pub enum BoxSpec {
Remove,
/// An absolute rectangle in default user space.
Rect([f64; 4]),
/// Margins inward from the media box: left, bottom, right, top (points).
/// Margins inward from the media box: left, bottom, right, top (default user-space units of the
/// unrotated page; points only on a page without `/UserUnit`).
Margins([f64; 4]),
}
+2 -1
View File
@@ -2169,7 +2169,8 @@ fn finish_edits(app: &mut PdfCraftApp, dialog: Dialog, req: &mut Pending) {
&& let Some((i, id)) = app.active_ids()
{
let count = app.session.get(id).map(|d| d.info.pages.len()).unwrap_or(0);
let edit = app.boxes_draft.edit(app.views[i].current, count);
let units = app.session.get(id).map(|d| d.page_user_units()).unwrap_or_default();
let edit = app.boxes_draft.edit(app.views[i].current, count, &units);
app.apply_edit(edit);
app.boxes_draft.seeded = None;
}
+100 -14
View File
@@ -19,7 +19,8 @@ pub enum Range {
Pages(usize, usize),
}
/// Dialog state. Margins are kept in points: left, bottom, right, top.
/// Dialog state. Margins are kept in physical points (1/72 in): left, bottom, right, top. A page with
/// `/UserUnit` counts each user-space unit as that many points, so they are converted per page.
#[derive(Clone, Debug, PartialEq)]
pub struct BoxesDraft {
pub which: PageBox,
@@ -46,13 +47,46 @@ impl BoxesDraft {
}
}
pub fn edit(&self, current: usize, count: usize) -> Edit {
let spec =
if self.margins.iter().all(|m| *m == 0.0) && self.which != PageBox::Media { BoxSpec::Remove } else { BoxSpec::Margins(self.margins) };
Edit::SetPageBox { pages: self.pages(current, count), which: self.which, spec }
/// The edit for the draft. `user_units` is each page's `/UserUnit` (points per user-space unit):
/// the margins are physical, the page box is written in user space, so pages with different
/// units get their own margins in one undo step.
pub fn edit(&self, current: usize, count: usize, user_units: &[f64]) -> Edit {
let pages = self.pages(current, count);
if self.margins.iter().all(|m| *m == 0.0) && self.which != PageBox::Media {
return Edit::SetPageBox { pages, which: self.which, spec: BoxSpec::Remove };
}
let unit_of = |p: usize| user_units.get(p).copied().filter(|u| *u > 0.0).unwrap_or(1.0);
let mut groups: Vec<(f64, Vec<usize>)> = Vec::new();
for p in pages {
let u = unit_of(p);
match groups.iter_mut().find(|(g, _)| *g == u) {
Some((_, v)) => v.push(p),
None => groups.push((u, vec![p])),
}
}
let mut edits: Vec<Edit> = groups
.into_iter()
.map(|(u, pages)| Edit::SetPageBox { pages, which: self.which, spec: BoxSpec::Margins(self.margins.map(|m| m / u)) })
.collect();
if edits.len() == 1 {
return edits.remove(0);
}
// Worded as the single edit is (`Edit::label`), so one undo step reads the same either way.
let label = if self.which == PageBox::Crop { "Crop pages" } else { "Set page boxes" };
Edit::Batch { label: label.into(), edits }
}
}
/// The margins (left, bottom, right, top) of `which` inside the media box, in physical points: the
/// page's user-space differences times its `/UserUnit`, so the dialog shows what is written back.
fn margins_of(b: &[[f64; 4]; 5], which: PageBox, user_unit: f64) -> [f64; 4] {
let (m, x) = (b[0], b[box_index(which)]);
if which == PageBox::Media {
return [0.0; 4];
}
[x[0] - m[0], x[1] - m[1], m[2] - x[2], m[3] - x[3]].map(|v| (v.max(0.0) * user_unit * 100.0).round() / 100.0)
}
fn box_index(b: PageBox) -> usize {
match b {
PageBox::Media => 0,
@@ -69,6 +103,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (boo
let current = app.views[i].current;
let Some(doc) = app.session.get(id) else { return (false, true) };
let boxes = doc.page_boxes();
let page_unit = doc.page_user_unit(current);
let count = boxes.len().max(1);
let units = app.units;
let d = &mut app.boxes_draft;
@@ -80,12 +115,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (boo
if d.seeded != Some((current, d.which))
&& let Some(b) = boxes.get(current)
{
let (m, x) = (b[0], b[box_index(d.which)]);
d.margins = if d.which == PageBox::Media {
[0.0; 4]
} else {
[x[0] - m[0], x[1] - m[1], m[2] - x[2], m[3] - x[3]].map(|v| (v.max(0.0) * 100.0).round() / 100.0)
};
d.margins = margins_of(b, d.which, page_unit);
d.seeded = Some((current, d.which));
}
ui.label(egui::RichText::new(tl!("Set Page Boxes")).font(theme::semibold(18.0)));
@@ -172,7 +202,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> (boo
let page = Rect::from_center_size(r.center(), vec2(w as f32 * s, h as f32 * s));
ui.painter().rect_filled(page, CornerRadius::ZERO, Color32::WHITE);
ui.painter().rect_stroke(page, CornerRadius::ZERO, Stroke::new(1.0, t.border), egui::StrokeKind::Outside);
let [l, bo, ri, to] = d.margins.map(|v| v as f32 * s);
let [l, bo, ri, to] = d.margins.map(|v| (v / page_unit) as f32 * s);
let inner = Rect::from_min_max(pos2(page.left() + l, page.top() + to), pos2(page.right() - ri, page.bottom() - bo));
if inner.is_positive() {
ui.painter().rect_stroke(inner, CornerRadius::ZERO, Stroke::new(1.5, t.accent), egui::StrokeKind::Middle);
@@ -211,8 +241,64 @@ mod tests {
assert_eq!(d.pages(2, 5), [2]);
d.range = Range::Pages(2, 9);
assert_eq!(d.pages(0, 5), [1, 2, 3, 4]);
assert!(matches!(d.edit(0, 5), Edit::SetPageBox { spec: BoxSpec::Remove, .. }));
assert!(matches!(d.edit(0, 5, &[]), Edit::SetPageBox { spec: BoxSpec::Remove, .. }));
d.margins = [72.0, 0.0, 0.0, 0.0];
assert!(matches!(d.edit(0, 5), Edit::SetPageBox { spec: BoxSpec::Margins(_), which: PageBox::Crop, .. }));
assert!(matches!(d.edit(0, 5, &[]), Edit::SetPageBox { spec: BoxSpec::Margins(_), which: PageBox::Crop, .. }));
}
/// Two pages of 432 x 360 points, the first with `/UserUnit` 1 and the second with 2, opened in a session.
fn session_with_user_units() -> (pdfcraft_engine::Session, pdfcraft_engine::DocId) {
use pdfcraft_cos::{Document as Cos, Object, SaveOptions, write_full};
let mut session = pdfcraft_engine::Session::new();
let blank = session.create_blank(432.0, 360.0, 2).unwrap();
let mut cos = Cos::open(blank).unwrap();
let second = pdfcraft_model::pages(&cos)[1].obj;
cos.update_dict(second, |d| d.set(b"UserUnit".to_vec(), Object::Int(2))).unwrap();
let bytes = write_full(&cos, &SaveOptions::default()).unwrap();
let id = session.open_new("units.pdf", std::sync::Arc::new(bytes)).unwrap();
(session, id)
}
/// #7414: half an inch is 36 physical points, whatever the page's `/UserUnit`.
#[test]
fn physical_margins_are_converted_by_each_pages_user_unit() {
let (mut session, id) = session_with_user_units();
let units = session.get(id).unwrap().page_user_units();
assert_eq!(units, [1.0, 2.0]);
let mut d = BoxesDraft { which: PageBox::Crop, margins: [36.0; 4], range: Range::Current, ..Default::default() };
session.apply(id, d.edit(1, 2, &units)).unwrap();
let b = session.get(id).unwrap().page_boxes();
assert_eq!(b[1][1], [18.0, 18.0, 414.0, 342.0], "UserUnit 2: 36 points are 18 user units");
assert_eq!(b[0][1], [0.0, 0.0, 432.0, 360.0], "the page outside the range is untouched");
d.range = Range::Pages(1, 1);
session.apply(id, d.edit(0, 2, &units)).unwrap();
assert_eq!(session.get(id).unwrap().page_boxes()[0][1], [36.0, 36.0, 396.0, 324.0], "UserUnit 1 keeps the margin as typed");
}
#[test]
fn pages_with_different_user_units_get_their_own_margins_in_one_step() {
let (mut session, id) = session_with_user_units();
let units = session.get(id).unwrap().page_user_units();
let d = BoxesDraft { which: PageBox::Crop, margins: [36.0; 4], range: Range::All, ..Default::default() };
session.apply(id, d.edit(0, 2, &units)).unwrap();
let doc = session.get(id).unwrap();
let b = doc.page_boxes();
assert_eq!(b[0][1], [36.0, 36.0, 396.0, 324.0]);
assert_eq!(b[1][1], [18.0, 18.0, 414.0, 342.0]);
assert_eq!(doc.can_undo(), Some("Crop pages"));
session.undo(id).unwrap();
let b = session.get(id).unwrap().page_boxes();
assert_eq!(b[0][1], [0.0, 0.0, 432.0, 360.0], "one undo restores page 1");
assert_eq!(b[1][1], [0.0, 0.0, 432.0, 360.0], "and page 2");
}
#[test]
fn the_dialog_shows_the_saved_margins_in_physical_points() {
let (session, id) = session_with_user_units();
let doc = session.get(id).unwrap();
let mut boxes = doc.page_boxes()[1];
boxes[1] = [18.0, 18.0, 414.0, 342.0];
assert_eq!(margins_of(&boxes, PageBox::Crop, 2.0), [36.0; 4], "18 user units on a UserUnit 2 page are half an inch");
assert_eq!(margins_of(&boxes, PageBox::Media, 2.0), [0.0; 4]);
}
}
+2
View File
@@ -115,6 +115,8 @@ fn select_after_edit(
// A group moved together stays selected (its positions don't change), so it
// can be moved or copied again; anything else in a batch clears the selection.
Edit::Batch { edits, .. } if edits.iter().all(|e| matches!(e, Edit::MoveAnnotation { .. })) => {}
// Set Page Boxes over pages with different /UserUnit is a batch too; like one SetPageBox it keeps the selection.
Edit::Batch { edits, .. } if edits.iter().all(|e| matches!(e, Edit::SetPageBox { .. })) => {}
Edit::Batch { .. } => view.comments.clear_selection(),
// The copies the paste added (and nothing that was there before): select them all.
Edit::PasteComments { page, .. } => {