diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index e4301f2f23..f0700b735e 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1207,7 +1207,7 @@ pub fn tools() -> Vec { 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( diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index 8a166330b9..644ca4d54e 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -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 { + 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 { self.editor.as_ref().and_then(|e| pdfcraft_organize::info(&e.cos, key)) diff --git a/crates/engine/src/printcheck.rs b/crates/engine/src/printcheck.rs index 744e52d4e4..f236370b42 100644 --- a/crates/engine/src/printcheck.rs +++ b/crates/engine/src/printcheck.rs @@ -256,15 +256,18 @@ fn page_reports(doc: &Document, pages: &[pdfcraft_model::Page]) -> Vec Vec { 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 { + 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; diff --git a/crates/organize/src/boxes.rs b/crates/organize/src/boxes.rs index ff56c73f67..f947d2abee 100644 --- a/crates/organize/src/boxes.rs +++ b/crates/organize/src/boxes.rs @@ -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]), } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index be9b295ae7..0d98079bc2 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -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; } diff --git a/crates/ui-egui/src/dialogs/pageboxes.rs b/crates/ui-egui/src/dialogs/pageboxes.rs index 57b5edc911..b9733e6d5d 100644 --- a/crates/ui-egui/src/dialogs/pageboxes.rs +++ b/crates/ui-egui/src/dialogs/pageboxes.rs @@ -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)> = 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 = 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]); } } diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index cd61e82e43..3b641e8e3f 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -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, .. } => {