Skip to main content

strata_platform/
print.rs

1//! Cross-platform native OS printer discovery and PDF print spooler dispatch
2//! (CUPS `lpstat`/`lp` on Linux & macOS, Win32 spooler hooks on Windows, and `MockPrintSpooler` for CI).
3
4#[cfg(unix)]
5use std::io::Write;
6#[cfg(unix)]
7use std::process::{Command, Stdio};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Mutex, OnceLock};
10
11/// Duplex (two-sided) printing mode.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum PrintDuplex {
14    #[default]
15    None,
16    LongEdge,
17    ShortEdge,
18}
19
20/// Metadata describing an installed host printer queue.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct PrinterInfo {
23    pub name: String,
24    pub is_default: bool,
25    pub status: String,
26}
27
28/// Configuration for submitting a native OS print job.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct PrintJobOptions {
31    pub printer: Option<String>,
32    pub copies: u32,
33    pub duplex: PrintDuplex,
34    pub media: String,
35    pub job_name: String,
36}
37
38impl Default for PrintJobOptions {
39    fn default() -> Self {
40        Self {
41            printer: None,
42            copies: 1,
43            duplex: PrintDuplex::None,
44            media: "A4".into(),
45            job_name: "Strata Document".into(),
46        }
47    }
48}
49
50/// Captured print payload recorded when mock print spooler mode is active.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct RecordedPrintJob {
53    pub options: PrintJobOptions,
54    pub pdf_bytes: Vec<u8>,
55}
56
57static MOCK_PRINT_ENABLED: AtomicBool = AtomicBool::new(false);
58static MOCK_PRINT_JOBS: OnceLock<Mutex<Vec<RecordedPrintJob>>> = OnceLock::new();
59
60fn mock_jobs() -> &'static Mutex<Vec<RecordedPrintJob>> {
61    MOCK_PRINT_JOBS.get_or_init(|| Mutex::new(Vec::new()))
62}
63
64/// Enables or disables deterministic in-memory mock print spooling for CI tests.
65pub fn set_mock_print_spooler(enabled: bool) {
66    MOCK_PRINT_ENABLED.store(enabled, Ordering::SeqCst);
67}
68
69/// Drains and returns all PDF jobs captured by the mock print spooler.
70pub fn take_mock_print_jobs() -> Vec<RecordedPrintJob> {
71    mock_jobs()
72        .lock()
73        .map(|mut v| std::mem::take(&mut *v))
74        .unwrap_or_default()
75}
76
77/// Enumerates printers installed on the host OS.
78pub fn list_printers() -> Vec<PrinterInfo> {
79    if MOCK_PRINT_ENABLED.load(Ordering::SeqCst) {
80        return vec![PrinterInfo {
81            name: "Strata_Virtual_PDF_Printer".into(),
82            is_default: true,
83            status: "idle".into(),
84        }];
85    }
86
87    #[allow(unused_mut)]
88    let mut printers = Vec::new();
89    #[cfg(unix)]
90    {
91        let default_name = Command::new("lpstat")
92            .arg("-d")
93            .output()
94            .ok()
95            .and_then(|o| String::from_utf8(o.stdout).ok())
96            .and_then(|s| s.split(':').nth(1).map(|p| p.trim().to_string()));
97
98        if let Ok(out) = Command::new("lpstat").arg("-p").output() {
99            if let Ok(text) = String::from_utf8(out.stdout) {
100                for line in text.lines() {
101                    if let Some(rest) = line.strip_prefix("printer ") {
102                        let mut parts = rest.split_whitespace();
103                        if let Some(name) = parts.next() {
104                            let status = parts.collect::<Vec<_>>().join(" ");
105                            printers.push(PrinterInfo {
106                                is_default: default_name.as_deref() == Some(name),
107                                name: name.to_string(),
108                                status,
109                            });
110                        }
111                    }
112                }
113            }
114        }
115    }
116    printers
117}
118
119/// Dispatches a PDF byte payload to a host OS printer queue (or mock spooler in CI).
120pub fn print_pdf_bytes(pdf: &[u8], options: &PrintJobOptions) -> Result<String, String> {
121    if !pdf.starts_with(b"%PDF-") {
122        return Err("Invalid PDF header: payload must begin with %PDF-".into());
123    }
124
125    if MOCK_PRINT_ENABLED.load(Ordering::SeqCst) {
126        if let Ok(mut jobs) = mock_jobs().lock() {
127            jobs.push(RecordedPrintJob {
128                options: options.clone(),
129                pdf_bytes: pdf.to_vec(),
130            });
131        }
132        return Ok("mock-job-1".into());
133    }
134
135    #[cfg(unix)]
136    {
137        let mut cmd = Command::new("lp");
138        if let Some(ref p) = options.printer {
139            cmd.args(["-d", p]);
140        }
141        cmd.args(["-n", &options.copies.max(1).to_string()]);
142        cmd.args(["-t", &options.job_name]);
143        cmd.args(["-o", &format!("media={}", options.media)]);
144        match options.duplex {
145            PrintDuplex::None => {}
146            PrintDuplex::LongEdge => {
147                cmd.args(["-o", "sides=two-sided-long-edge"]);
148            }
149            PrintDuplex::ShortEdge => {
150                cmd.args(["-o", "sides=two-sided-short-edge"]);
151            }
152        }
153        let mut child = cmd
154            .stdin(Stdio::piped())
155            .stdout(Stdio::piped())
156            .stderr(Stdio::piped())
157            .spawn()
158            .map_err(|e| format!("Failed to invoke CUPS `lp`: {e}"))?;
159        if let Some(mut stdin) = child.stdin.take() {
160            stdin
161                .write_all(pdf)
162                .map_err(|e| format!("Failed writing PDF to `lp` stdin: {e}"))?;
163        }
164        let output = child
165            .wait_with_output()
166            .map_err(|e| format!("Failed waiting on `lp`: {e}"))?;
167        if output.status.success() {
168            Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
169        } else {
170            Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
171        }
172    }
173
174    #[cfg(not(unix))]
175    {
176        let _ = (pdf, options);
177        Err("Direct native print dispatch requires CUPS on Unix or MockPrintSpooler".into())
178    }
179}