Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Merge current main while preserving hardened print contracts through craft-print

skylar taylor-barrick83fcbe7d9bd9
diff --cc crates/engine/src/print_cmds.rs
index 37dee42ad,a6acb95a4..96dfa77fd
--- a/crates/engine/src/print_cmds.rs
+++ b/crates/engine/src/print_cmds.rs
@@@ -4,8 -4,9 +4,9 @@@
//! scale, colour handling with printer profile / intent / black-point compensation, corner and
//! centre crop marks, registration marks, description and label) with a small PDF writer
//! (ISO 32000: one page, a Flate-compressed image XObject, vector marks, Helvetica text), then
-//! hands it to the system spooler with `lp` (CUPS, macOS and Linux). `"dryRun": true` stops
-//! before spooling and reports the command line. Without an explicit PDF output, the spool file
-//! is private and removed when `lp` finishes; dry runs do not create one.
+//! hands its bytes to `craft-print` (CUPS on macOS/Linux, Windows PDF printing on Windows).
- //! `"dryRun": true` retains a diagnostic PDF and reports the backend command without spooling.
++//! `"dryRun": true` reports the backend command without spooling; a PDF is kept only at an
++//! explicit output path. Shared spooler transport files are private and automatically removed.
//!
//! Paths to Illustrator writes the document's paths as an Adobe Illustrator 3 compatible
//! PostScript file (`m`/`L`/`C` path construction, `n`/`N` unpainted closed/open paths, `*u`/`*U`
@@@ -326,51 -327,37 +327,56 @@@ pub fn layout(doc: &Document, p: &Value
Ok(PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks, emulsion_down })
}
-#[cfg(not(target_arch = "wasm32"))]
-fn private_spool_pdf(pdf: &[u8]) -> Result<tempfile::NamedTempFile> {
- private_spool_pdf_in(pdf, &std::env::temp_dir())
-}
-
-#[cfg(not(target_arch = "wasm32"))]
-fn private_spool_pdf_in(pdf: &[u8], dir: &std::path::Path) -> Result<tempfile::NamedTempFile> {
- // tempfile creates a random name with create_new semantics and mode 0600 on Unix.
- // Keeping this handle alive prevents a symlink at a guessed path from redirecting the write.
- let mut file = tempfile::Builder::new().prefix("photocraft-print-").suffix(".pdf").tempfile_in(dir).map_err(other)?;
- file.write_all(pdf).map_err(other)?;
- file.flush().map_err(other)?;
- Ok(file)
-}
-
/// Lays out, renders and (unless dry-run) spools a print. Shared by Print and Print One Copy.
fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
- do_print_with_spooler(s, p, cmd, spool_pdf)
-}
-
-fn do_print_with_spooler(s: &mut Session, p: &Value, cmd: &str, spooler: impl FnOnce(&[String]) -> Result<String>) -> Result<Value> {
- let output = p.get("output").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string);
++ let output = p.get("output").and_then(Value::as_str).filter(|v| !v.is_empty());
+ let send = p.get("send").and_then(Value::as_bool).unwrap_or(output.is_none());
+ let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false);
+ if !dry && !send && output.is_none() {
+ return Err(bad(cmd, "send: false needs an output path or dryRun: true"));
+ }
let d = s.active().ok_or(EngineError::NoDocument)?;
let doc = d.doc.clone();
- let PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks, emulsion_down } = layout(&doc, p, cmd)?;
- let (img, color) = print_image(&doc, p, cmd)?;
+ let doc_id = doc.id;
+ let params = p.clone();
+ let worker_params = params.clone();
+ let command = cmd.to_string();
- let send = p.get("send").and_then(Value::as_bool).unwrap_or(!p.get("output").and_then(Value::as_str).is_some_and(|v| !v.is_empty()));
- if send && !p.get("dryRun").and_then(Value::as_bool).unwrap_or(false) {
++ if send && !dry {
+ // Session::execute remains synchronous; the desktop's Session::start snapshots here
+ // and runs PDF composition and the potentially slow driver on a worker.
+ return crate::jobs::run(
+ s,
+ "Print",
+ false,
+ move |ctx| {
+ ctx.progress(0.0, "Print");
+ render_and_spool(&doc, &worker_params, &command)
+ },
+ move |s, result| {
+ remember_print(s, &params);
+ // A user can switch tabs while printing. Hooks belong to the source document;
+ // a closed source has no document left to modify, as for background saves.
+ let viewed = s.active().map(|st| st.doc.id);
+ if let Some(index) = s.documents().iter().position(|st| st.doc.id == doc_id) {
+ s.set_active(index);
+ crate::automate_cmds::fire_event(s, "print");
+ if let Some(index) = viewed.and_then(|id| s.documents().iter().position(|st| st.doc.id == id)) {
+ s.set_active(index);
+ }
+ }
+ Ok(result)
+ },
+ );
+ }
+ let result = render_and_spool(&doc, p, cmd)?;
+ remember_print(s, p);
+ crate::automate_cmds::fire_event(s, "print");
+ Ok(result)
+}
+
+fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result<Value> {
+ let PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks, emulsion_down } = layout(doc, p, cmd)?;
+ let (img, color) = print_image(doc, p, cmd)?;
let description = p
.get("description")
.and_then(Value::as_bool)
@@@ -378,29 -365,31 +384,28 @@@
.then(|| crate::file_cmds::read_file_info(doc.metadata.xmp.as_deref())["description"].as_str().unwrap_or_default().to_string());
let label = p.get("labels").and_then(Value::as_bool).unwrap_or(false).then(|| doc.name.clone());
let page = PrintPage { paper: (pw, ph), image: img, rect: (x, y, w, h), marks, description, label, emulsion_down };
+ let output = p.get("output").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string);
+ let send = p.get("send").and_then(Value::as_bool).unwrap_or(output.is_none());
+ let copies = crate::commands::int(p, "copies").unwrap_or(1).clamp(1, 999) as u32;
+ let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false);
let pdf = print_pdf(&page);
- if let Some(path) = &output {
- // An explicit output is the caller's requested artifact, including for dry runs.
- write_file(path, &pdf)?;
- }
- #[cfg(not(target_arch = "wasm32"))]
- let spool_file = if output.is_none() && send && !dry { Some(private_spool_pdf(&pdf)?) } else { None };
- #[cfg(target_arch = "wasm32")]
- if output.is_none() && send && !dry {
- return Err(other("printing needs the desktop app"));
- }
- // Dry-run commands use a descriptive placeholder because no spool file exists.
- let command_path = output.clone();
- #[cfg(not(target_arch = "wasm32"))]
- let command_path = command_path.or_else(|| spool_file.as_ref().map(|f| f.path().to_string_lossy().into_owned()));
- let command_path = command_path.unwrap_or_else(|| "<temporary PDF>".into());
- let copies = crate::commands::int(p, "copies").unwrap_or(1).clamp(1, 999);
- let mut argv: Vec<String> = vec!["lp".into()];
- if let Some(pr) = p.get("printer").and_then(Value::as_str).filter(|v| !v.is_empty()) {
- argv.extend(["-d".into(), pr.to_string()]);
- }
- if copies > 1 {
- argv.extend(["-n".into(), copies.to_string()]);
- }
- argv.extend(["-t".into(), doc.name.clone(), command_path]);
+ let job = craft_print::Job {
+ printer: p.get("printer").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string),
+ copies,
+ title: doc.name.clone(),
+ // PhotoCraft already placed and scaled the image on its physical sheet. Scaling again
+ // in the driver would change the preview, print resolution and crop-mark positions.
+ scaling: craft_print::Scaling::Exact,
+ ..Default::default()
+ };
+ let command = if send { json!(craft_print::command_preview(&job).map_err(other)?) } else { Value::Null };
+ let pdf_path = match output {
+ Some(path) => {
+ write_file(&path, &pdf)?;
+ Some(path)
+ }
- None if dry || !send => Some(diagnostic_pdf(&pdf)?),
+ None => None,
+ };
let mut sent = false;
let mut spool = Value::Null;
if send && !dry {
@@@ -418,25 -411,26 +423,12 @@@ fn remember_print(s: &mut Session, p: &
if let Some(o) = remembered.as_object_mut() {
o.remove("output");
o.remove("dryRun");
- // A send override can depend on the output or dry-run choice. Neither is remembered,
- // so replay and the next Print dialog must derive the default from their own output.
++ // Output and dry-run choices are not remembered, so a send override must not survive them.
+ o.remove("send");
}
s.file_menu.last_print = Some(remembered);
}
- /// A requested preview/export artifact belongs to the caller, unlike a spooler's temporary
- /// transport file. Create it exclusively and keep it so the command's `pdf` path remains usable.
--#[cfg(not(target_arch = "wasm32"))]
- fn diagnostic_pdf(pdf: &[u8]) -> Result<String> {
- let mut file = tempfile::Builder::new().prefix("photocraft-print-").suffix(".pdf").tempfile().map_err(other)?;
- file.write_all(pdf).map_err(other)?;
- file.flush().map_err(other)?;
- let (_, path) = file.keep().map_err(other)?;
- Ok(path.to_string_lossy().into_owned())
-fn spool_pdf(argv: &[String]) -> Result<String> {
- let out = std::process::Command::new(&argv[0]).args(&argv[1..]).output().map_err(|e| other(format!("could not run `lp` (CUPS): {e}")))?;
- if !out.status.success() {
- return Err(other(format!("lp failed: {}", String::from_utf8_lossy(&out.stderr).trim())));
- }
- Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
--}
--#[cfg(target_arch = "wasm32")]
- fn diagnostic_pdf(_: &[u8]) -> Result<String> {
- Err(other("printing needs the desktop app; specify an output PDF path instead"))
-fn spool_pdf(_: &[String]) -> Result<String> {
- Err(other("printing needs the desktop app"))
--}
--
fn print(s: &mut Session, p: &Value) -> Result<Value> {
do_print(s, p, "file.print")
}
@@@ -605,7 -599,7 +597,7 @@@ pub fn specs() -> Vec<CommandSpec>
CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run }
};
}
- const PRINT_PARAMS: &str = r##"{"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render a diagnostic PDF, report the backend command, don't spool)} → {pdf:path|null (null for spool-only jobs), imageRect, command:diagnostic array|null, sent}"##;
- const PRINT_PARAMS: &str = r##"{"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the lp command, don't spool; no temporary PDF is written)} → {pdf:explicit output path or null, imageRect, command, sent}"##;
++ const PRINT_PARAMS: &str = r##"{"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent}"##;
vec![
spec!("file.print", "Print…", &["File"], Some("Cmd+P"), PRINT_PARAMS, native_doc, print),
spec!(
diff --cc crates/engine/src/print_cmds/tests.rs
index c58ae86e4,ab2e8c378..988f11635
--- a/crates/engine/src/print_cmds/tests.rs
+++ b/crates/engine/src/print_cmds/tests.rs
@@@ -44,16 -45,11 +45,17 @@@ fn print_dry_run_renders_a_pdf_and_repo
)
.unwrap();
let cmd: Vec<String> = serde_json::from_value(r["command"].clone()).unwrap();
- assert_eq!(&cmd[..5], &["lp", "-d", "Office", "-n", "2"]);
- assert_eq!(cmd.last(), Some(&out));
+ #[cfg(unix)]
+ {
+ assert_eq!(&cmd[..5], &["lp", "-d", "Office", "-n", "2"]);
+ assert!(cmd.contains(&"fit-to-page=false".into()));
- assert!(!cmd.contains(&r["pdf"].as_str().unwrap().to_string()), "PDF is streamed, not passed as a file");
++ assert!(!cmd.contains(&out), "PDF bytes are streamed instead of passing a path");
+ }
+ #[cfg(windows)]
+ assert!(cmd.last().unwrap().contains("craft-print PDF spooler"));
assert_eq!(r["sent"], false);
- let pdf = std::fs::read(r["pdf"].as_str().unwrap()).unwrap();
+ assert_eq!(r["pdf"], out);
+ let pdf = std::fs::read(&out).unwrap();
assert!(pdf.starts_with(b"%PDF-1.4"));
assert!(String::from_utf8_lossy(&pdf).contains("/MediaBox [0 0 595.28 841.89]"));
let (w, h, cs, data) = pdf_image(&pdf);
@@@ -166,13 -174,107 +180,13 @@@ fn print_one_copy_repeats_the_last_sett
assert_eq!(r["paper"], json!([419.53, 595.28]));
assert_eq!(r["scale"], 50.0);
let cmd: Vec<String> = serde_json::from_value(r["command"].clone()).unwrap();
- assert!(!cmd.contains(&"-n".to_string()));
- assert_eq!(cmd.last().map(String::as_str), Some("<temporary PDF>"));
+ #[cfg(unix)]
+ assert_eq!(&cmd[..3], &["lp", "-n", "1"]);
+ #[cfg(windows)]
+ assert!(cmd.last().unwrap().contains("craft-print PDF spooler"));
- let _ = std::fs::remove_file(r["pdf"].as_str().unwrap());
+ assert!(r["pdf"].is_null());
}
-#[test]
-fn print_without_output_keeps_private_pdf_only_during_spooling() {
- let mut s = session("rgb", 8);
- let mut temporary_path = None;
- let result = do_print_with_spooler(&mut s, &json!({}), "file.print", |argv| {
- let path = std::path::PathBuf::from(argv.last().unwrap());
- let data = std::fs::read(&path).unwrap();
- assert!(data.starts_with(b"%PDF-1.4"));
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o077, 0);
- }
- temporary_path = Some(path);
- Ok("request id 1".into())
- })
- .unwrap();
- assert_eq!(result["sent"], true);
- assert!(result["pdf"].is_null(), "the temporary path must not be advertised as a retained PDF");
- assert!(!temporary_path.unwrap().exists(), "spool PDF survives after lp returns");
-}
-
-#[test]
-fn print_spool_error_removes_private_pdf() {
- let mut s = session("rgb", 8);
- let mut temporary_path = None;
- let result = do_print_with_spooler(&mut s, &json!({}), "file.print", |argv| {
- let path = std::path::PathBuf::from(argv.last().unwrap());
- assert!(path.is_file());
- temporary_path = Some(path);
- Err(other("spooler unavailable"))
- });
- assert!(result.is_err());
- assert!(!temporary_path.unwrap().exists(), "spool PDF survives a failed lp call");
-}
-
-#[cfg(unix)]
-#[test]
-fn private_spool_pdf_does_not_follow_a_guessed_symlink() {
- let dir = tmp("symlink");
- let dir = std::path::Path::new(&dir);
- let victim = dir.join("victim.pdf");
- let link = dir.join("photocraft-print-AAAAAA.pdf");
- std::fs::write(&victim, b"keep this").unwrap();
- std::os::unix::fs::symlink(&victim, &link).unwrap();
-
- let file = private_spool_pdf_in(b"%PDF-private", dir).unwrap();
- assert_ne!(file.path(), link);
- assert_eq!(std::fs::read(&victim).unwrap(), b"keep this");
- assert_eq!(std::fs::read(file.path()).unwrap(), b"%PDF-private");
- assert!(std::fs::symlink_metadata(file.path()).unwrap().file_type().is_file());
- let path = file.path().to_path_buf();
- drop(file);
- assert!(!path.exists());
- assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
-}
-
-#[test]
-fn print_dry_run_without_output_creates_no_spool_pdf() {
- let mut s = session("rgb", 8);
- let result = do_print_with_spooler(&mut s, &json!({"dryRun": true}), "file.print", |_| Err(other("dry run invoked spooler"))).unwrap();
- assert!(result["pdf"].is_null());
- assert_eq!(result["sent"], false);
- assert_eq!(result["command"].as_array().unwrap().last().unwrap(), "<temporary PDF>");
- assert!(result["bytes"].as_u64().unwrap() > 100);
-}
-
-#[test]
-fn print_without_sending_requires_an_output_unless_dry_run() {
- let mut s = session("rgb", 8);
- let before = s.file_menu.last_print.clone();
- let err = do_print_with_spooler(&mut s, &json!({"send": false}), "file.print", |_| Err(other("unexpected spooler call"))).unwrap_err();
- assert!(err.to_string().contains("needs an output path"), "{err}");
- assert_eq!(s.file_menu.last_print, before, "a rejected print must not become a remembered successful print");
- assert!(do_print_with_spooler(&mut s, &json!({"send": false, "dryRun": true}), "file.print", |_| Err(other("dry run invoked spooler"))).is_ok());
- assert!(s.file_menu.last_print.as_ref().unwrap().get("send").is_none());
-
- let output = format!("{}/export.pdf", tmp("non-sending-export"));
- do_print_with_spooler(&mut s, &json!({"output": output, "send": false}), "file.print", |_| Err(other("non-sending export invoked spooler"))).unwrap();
- assert!(std::path::Path::new(&output).is_file());
- let mut repeat = s.file_menu.last_print.clone().unwrap();
- assert!(repeat.get("send").is_none(), "a removed output must not leave send: false in remembered settings");
- repeat["copies"] = json!(1);
- let replay = do_print_with_spooler(&mut s, &repeat, "file.printOneCopy", |argv| {
- assert!(std::path::Path::new(argv.last().unwrap()).is_file());
- Ok("request id 2".into())
- })
- .unwrap();
- assert_eq!(replay["sent"], true);
- assert_eq!(replay["copies"], 1);
-
- let both = format!("{}/print-and-export.pdf", tmp("sending-export"));
- do_print_with_spooler(&mut s, &json!({"output": both, "send": true, "dryRun": true}), "file.print", |_| Err(other("dry run invoked spooler"))).unwrap();
- assert!(s.file_menu.last_print.as_ref().unwrap().get("send").is_none(), "a removed output must not leave send: true in remembered settings");
-}
-
#[test]
fn package_copies_links_and_relinks() {
let dir = tmp("package");
@@@ -235,65 -337,3 +249,104 @@@ fn paths_export_as_illustrator_postscri
assert_eq!(r["paths"], 1);
assert!(s.execute("file.export.pathsToIllustrator", json!({"paths": "Nope"})).is_err());
}
+
- /// Launch the command in a subprocess with a fake CUPS binary: the parent process's PATH and
++#[test]
++fn print_dry_run_without_output_retains_no_pdf() {
++ let mut s = session("rgb", 8);
++ let result = s.execute("file.print", json!({"dryRun": true})).unwrap();
++ assert!(result["pdf"].is_null());
++ assert_eq!(result["sent"], false);
++ assert!(result["bytes"].as_u64().unwrap() > 100);
++ assert!(result["command"].is_array());
++ assert!(s.file_menu.last_print.as_ref().unwrap().get("dryRun").is_none());
++}
++
++#[test]
++fn print_without_sending_requires_output_unless_dry_run_and_forgets_send_override() {
++ let mut s = session("rgb", 8);
++ let before = s.file_menu.last_print.clone();
++ let err = s.execute("file.print", json!({"send": false})).unwrap_err();
++ assert!(err.to_string().contains("needs an output path"), "{err}");
++ assert_eq!(s.file_menu.last_print, before);
++ let result = s.execute("file.print", json!({"send": false, "dryRun": true})).unwrap();
++ assert!(result["pdf"].is_null());
++ assert!(result["command"].is_null());
++ assert!(s.file_menu.last_print.as_ref().unwrap().get("send").is_none());
++ let out = format!("{}/export.pdf", tmp("non-sending-export"));
++ let result = s.execute("file.print", json!({"output": out, "send": false})).unwrap();
++ assert_eq!(result["sent"], false);
++ assert!(std::fs::read(&out).unwrap().starts_with(b"%PDF-1.4"));
++ assert!(s.file_menu.last_print.as_ref().unwrap().get("send").is_none());
++ s.execute("file.print", json!({"output": out, "send": true, "dryRun": true})).unwrap();
++ assert!(s.file_menu.last_print.as_ref().unwrap().get("send").is_none());
++}
+/// parallel tests are untouched, and the real spool boundary still consumes the PDF bytes.
+#[cfg(unix)]
+#[test]
+fn spool_transport_streams_pdf_and_propagates_refusal() {
+ const CHILD: &str = "PHOTOCRAFT_TEST_PRINT_TRANSPORT";
+ if let Ok(dir) = std::env::var(CHILD) {
+ let mut s = session("rgb", 8);
+ let source = s.active().unwrap().doc.id;
+ s.execute("file.scripts.scriptEventsManager", json!({"add": {"event": "print", "steps": [["image.imageRotation.90cw", {}]]}})).unwrap();
+ let crate::jobs::Started::Job(job) = s.start("file.print", json!({"printer": "Office", "copies": 3, "paper": "a4", "scale": 50})).unwrap() else {
+ panic!("desktop printing must start on a worker");
+ };
+ assert!(!s.cancel_job(job), "queue side effects must not be reported as cancelled");
+ assert_eq!(s.execute("jobs.cancel", json!({})).unwrap()["cancelled"], 0);
+ assert!(s.execute("jobs.cancel", json!({"job": job.0})).unwrap_err().to_string().contains("system print queue"));
+ s.execute("file.new", json!({"width": 40, "height": 10})).unwrap();
+ let viewed = s.active().unwrap().doc.id;
+ let journal_before_completion = s.journal.len();
+ let out = s.wait_job(job).unwrap();
+ assert_eq!(s.journal.len(), journal_before_completion + 1, "print hooks must not become duplicate recorded action steps");
+ assert_eq!(s.journal.last().unwrap().0, "file.print");
+ assert_eq!(s.active().unwrap().doc.id, viewed, "completion keeps the user's tab");
+ assert_eq!(s.active().unwrap().doc.size.width, 40, "print hook must not act on the newly viewed document");
+ let printed = &s.documents().iter().find(|st| st.doc.id == source).unwrap().doc;
+ assert_eq!((printed.size.width, printed.size.height), (150, 300), "print hook ran on the source document");
+ assert_eq!(out["sent"], true);
+ assert_eq!(out["spooler"], "request id is Office-42");
+ assert!(out["pdf"].is_null(), "spool-only printing leaves no diagnostic PDF");
+ let pdf = std::fs::read(format!("{dir}/received.pdf")).unwrap();
+ assert!(pdf.starts_with(b"%PDF-1.4"));
+ assert!(String::from_utf8_lossy(&pdf).contains("/MediaBox [0 0 595.28 841.89]"));
+ let args = std::fs::read_to_string(format!("{dir}/args")).unwrap();
+ assert!(args.contains("fit-to-page=false"));
+ assert!(args.contains("-n\n3\n"));
+ assert!(!args.contains(".pdf"));
+ let remembered = s.file_menu.last_print.clone();
+ let explicit = format!("{dir}/saved.pdf");
+ let err = s.execute("file.print", json!({"printer": "Refuse", "output": explicit, "send": true})).unwrap_err();
+ assert!(err.to_string().contains("queue refused"), "{err}");
+ assert!(std::fs::read(&explicit).unwrap().starts_with(b"%PDF-1.4"), "explicit export survives a spool refusal");
+ assert_eq!(s.file_menu.last_print, remembered, "failed printing does not replace repeat settings");
++ // Export-only choices must not disable submission when Print One Copy repeats settings.
++ let export = format!("{dir}/export-only.pdf");
++ s.execute("file.print", json!({"printer": "Office", "output": export, "send": false})).unwrap();
++ let remembered = s.file_menu.last_print.as_ref().unwrap();
++ assert!(remembered.get("send").is_none() && remembered.get("output").is_none());
++ let repeat = s.execute("file.printOneCopy", json!({})).unwrap();
++ assert_eq!(repeat["sent"], true);
++ assert_eq!(repeat["copies"], 1);
++ assert!(repeat["pdf"].is_null());
++ assert!(!std::fs::read_to_string(format!("{dir}/args")).unwrap().contains(".pdf"));
+ return;
+ }
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let script = dir.path().join("lp");
+ std::fs::write(
+ &script,
+ b"#!/bin/sh\nif [ \"$2\" = Refuse ]; then echo 'queue refused' >&2; exit 1; fi\nprintf '%s\\n' \"$@\" > \"$PHOTOCRAFT_TEST_PRINT_TRANSPORT/args\"\n/bin/cat > \"$PHOTOCRAFT_TEST_PRINT_TRANSPORT/received.pdf\"\necho 'request id is Office-42 (0 file(s))'\n",
+ ).unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let result = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", "print_cmds::tests::spool_transport_streams_pdf_and_propagates_refusal", "--nocapture"])
+ .env(CHILD, dir.path())
+ .env("PATH", dir.path())
+ .output()
+ .unwrap();
+ assert!(result.status.success(), "{}\n{}", String::from_utf8_lossy(&result.stdout), String::from_utf8_lossy(&result.stderr));
+ assert!(String::from_utf8_lossy(&result.stdout).contains("1 passed"), "child must select the transport test");
+}
diff --cc docs/development.md
index 5504958a2,1236dd65c..bb291af49
--- a/docs/development.md
+++ b/docs/development.md
@@@ -526,21 -527,3 +527,22 @@@ stroke is drawn above its clipped layer
reference point; stroke distances follow a 5 × 5 chamfer metric (1, √2, √5) seeded at sub-pixel
edge offsets; interior effects keep the layer's alpha; outside strokes blend onto the backdrop with
their own modes, an upper stroke covering lower ones.
+
+## System printing
+
+`file.print` and `file.printOneCopy` keep PDF layout, scaling, marks and ICC conversion in
+PhotoCraft and submit the rendered bytes through `craft-print` at the Git revision pinned in
+`Cargo.toml`. CUPS streams the PDF on macOS/Linux; Windows uses the shared Windows PDF backend.
+The driver receives exact physical sheet size so it does not scale PhotoCraft's layout twice.
+Windows raster printing does not establish physical-printer colour fidelity; test critical
+photo output with the actual printer and its profile.
+
+Desktop commands run composition and submission on a background worker. The UI reports success
+only when the spooler accepts the job; remove submitted jobs in the system print queue. Headless
+`Session::execute` stays synchronous. The returned `pdf` is `null` for a spool-only job, and
+`command` is a diagnostic preview, not an executable command with a PDF path. Supplying `output`
- keeps a PDF at that path and defaults `send` to false. `dryRun` renders a diagnostic PDF but never
- submits; an implicit diagnostic file is exclusively created with a random name and belongs to
- the caller, who may delete it after inspection. Shared spooler transport files are automatically
- removed on Windows; CUPS needs none.
++keeps a PDF at that path and defaults `send` to false. `dryRun` renders the PDF and reports the
++backend command without submitting; it writes a PDF only when `output` is explicit. `send: false`
++without an output requires `dryRun: true`. Remembered print settings omit `output`, `dryRun` and
++`send`, so Print One Copy derives submission from its own output choice. Shared spooler transport
++files are automatically removed on Windows; CUPS needs none.