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

+32 -73
View File
@@ -1,79 +1,32 @@
//! Prints a PDF through the system print panel.
//! Prints a PDF through the system print dialog.
use std::path::Path;
/// This build has a system print panel.
pub const BUILT: bool = cfg!(target_os = "macos");
/// Shows the print panel for `pdf`; false when cancelled.
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
pub fn print_pdf(pdf: &Path) -> anyhow::Result<bool> {
use objc2::{AllocAnyThread, MainThreadMarker};
use objc2_app_kit::{NSPaperOrientation, NSPrintInfo, NSPrintJobSavingURL, NSPrintSaveJob};
use objc2_foundation::{NSCopying, NSSize, NSString, NSURL};
use objc2_pdf_kit::{PDFDisplayBox, PDFDocument, PDFPrintScalingMode};
mod mac;
#[cfg(windows)]
mod win;
let mtm =
MainThreadMarker::new().ok_or_else(|| anyhow::anyhow!("printing needs the main thread"))?;
let url = NSURL::fileURLWithPath(&NSString::from_str(&pdf.to_string_lossy()));
let document = unsafe { PDFDocument::initWithURL(PDFDocument::alloc(), &url) }
.ok_or_else(|| anyhow::anyhow!("{} is no readable PDF", pdf.display()))?;
let sizes: Vec<(f64, f64)> = (0..unsafe { document.pageCount() })
.filter_map(|n| unsafe { document.pageAtIndex(n) })
.map(|page| {
let size = unsafe { page.boundsForBox(PDFDisplayBox::MediaBox) }.size;
// A page turned a quarter shows its other side up.
match unsafe { page.rotation() }.rem_euclid(180) == 90 {
true => (size.height, size.width),
false => (size.width, size.height),
}
})
.collect();
let (width, height) = paper_for(&sizes).ok_or_else(|| anyhow::anyhow!("{} has no pages", pdf.display()))?;
let paper = NSSize::new(width, height);
if let Some(scale) = crate::env::value("ELY_PRINT_SHARED_SCALE") {
// Tests start from a shared scale the copy must undo.
NSPrintInfo::sharedPrintInfo().setScalingFactor(scale.parse()?);
}
// The PDF already holds the document's paper, margins and scale.
let info = NSPrintInfo::sharedPrintInfo().copy();
info.setScalingFactor(1.0);
info.setOrientation(match paper.width > paper.height {
true => NSPaperOrientation::Landscape,
false => NSPaperOrientation::Portrait,
});
info.setPaperSize(paper);
info.setTopMargin(0.0);
info.setBottomMargin(0.0);
info.setLeftMargin(0.0);
info.setRightMargin(0.0);
log::info!("print: paper {}x{} points", paper.width, paper.height);
let operation = unsafe {
document.printOperationForPrintInfo_scalingMode_autoRotate(
Some(&info),
PDFPrintScalingMode::PageScaleNone,
true,
mtm,
)
}
.ok_or_else(|| anyhow::anyhow!("no print operation for {}", pdf.display()))?;
// Tests read the real job: saved to a file.
let saved = crate::env::value("ELY_PRINT_TO");
if let Some(to) = &saved {
let info = operation.printInfo();
info.setJobDisposition(unsafe { NSPrintSaveJob });
let to = NSURL::fileURLWithPath(&NSString::from_str(to));
unsafe { info.dictionary().insert(NSPrintJobSavingURL, &to) };
}
operation.setShowsPrintPanel(saved.is_none());
operation.setShowsProgressPanel(saved.is_none());
let printed = operation.runOperation();
log::info!("print: the panel closed, printed {printed}");
Ok(printed)
#[cfg(target_os = "linux")]
pub use linux::print_pdf;
#[cfg(target_os = "macos")]
pub use mac::print_pdf;
#[cfg(windows)]
pub use win::print_pdf;
/// Paper sizes round to whole points at worst.
#[cfg(not(target_os = "macos"))]
const ROUNDING: f64 = 0.5;
/// Whether a named paper, short side first, holds a page.
#[cfg(not(target_os = "macos"))]
fn holds((across, down): (f64, f64), (short, long): (f64, f64)) -> bool {
// A named paper may run 2 mm over, never under.
let suits = |paper: f64, page: f64| paper >= page - ROUNDING && paper - page <= 2.0 * 72.0 / 25.4;
suits(across, short) && suits(down, long)
}
/// One paper holding every page, turned as needed.
#[cfg(any(target_os = "macos", test))]
fn paper_for(sizes: &[(f64, f64)]) -> Option<(f64, f64)> {
let long = sizes.iter().map(|(w, h)| w.max(*h)).fold(None, |most: Option<f64>, side| Some(most.map_or(side, |m| m.max(side))))?;
let short = sizes.iter().map(|(w, h)| w.min(*h)).fold(0.0, f64::max);
@@ -87,10 +40,16 @@ fn paper_for(sizes: &[(f64, f64)]) -> Option<(f64, f64)> {
Some(if wide { (long, short) } else { (short, long) })
}
/// Printing needs a system panel this platform build lacks.
/// Runs `work` on its own thread, off the app's.
#[cfg(not(target_os = "macos"))]
pub fn print_pdf(_: &Path) -> anyhow::Result<bool> {
anyhow::bail!("printing is not built on this platform")
async fn off<T: Send + 'static>(work: impl FnOnce() -> anyhow::Result<T> + Send + 'static) -> anyhow::Result<T> {
let (sender, answer) = futures::channel::oneshot::channel();
std::thread::Builder::new().name("ely-print".into()).spawn(move || {
if sender.send(work()).is_err() {
log::warn!("print: the job ended after its caller left");
}
})?;
answer.await.map_err(|_| anyhow::anyhow!("the print thread ended without an answer"))?
}
#[cfg(test)]