| 1 | //! Windows print spooler discovery and RAW printing (like Moirai print-bridge).
|
| 2 |
|
| 3 | use std::io;
|
| 4 | use std::process::Command;
|
| 5 |
|
| 6 | #[cfg(windows)]
|
| 7 | use std::os::windows::process::CommandExt;
|
| 8 |
|
| 9 | use serde::Deserialize;
|
| 10 |
|
| 11 | use super::{PrintError, PrinterDevice, PrinterTarget};
|
| 12 |
|
| 13 | #[cfg(windows)]
|
| 14 | const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
| 15 |
|
| 16 | #[cfg(windows)]
|
| 17 | fn hidden_command(program: &str) -> Command {
|
| 18 | let mut command = Command::new(program);
|
| 19 | command.creation_flags(CREATE_NO_WINDOW);
|
| 20 | command
|
| 21 | }
|
| 22 |
|
| 23 | #[cfg(not(windows))]
|
| 24 | fn hidden_command(program: &str) -> Command {
|
| 25 | Command::new(program)
|
| 26 | }
|
| 27 |
|
| 28 | const POS_NAME_PATTERNS: &[&str] = &[
|
| 29 | "gooj", "pt-210", "pt210", "pos-58", "pos58", "thermal", "receipt", "58mm", "pos", "escpos",
|
| 30 | ];
|
| 31 |
|
| 32 | #[derive(Debug, Deserialize)]
|
| 33 | struct WinPrinterRow {
|
| 34 | #[serde(rename = "Name")]
|
| 35 | name: String,
|
| 36 | #[serde(rename = "PortName")]
|
| 37 | port: String,
|
| 38 | #[serde(rename = "DriverName")]
|
| 39 | driver: String,
|
| 40 | }
|
| 41 |
|
| 42 | pub fn list_windows_spooler_printers() -> Vec<PrinterDevice> {
|
| 43 | let Ok(rows) = query_printers() else {
|
| 44 | return Vec::new();
|
| 45 | };
|
| 46 |
|
| 47 | let usable: Vec<_> = rows
|
| 48 | .into_iter()
|
| 49 | .filter(|row| !row.name.is_empty() && !is_com_port(&row.port))
|
| 50 | .collect();
|
| 51 |
|
| 52 | let mut matched = Vec::new();
|
| 53 | let mut rest = Vec::new();
|
| 54 |
|
| 55 | for row in usable {
|
| 56 | let device = PrinterDevice {
|
| 57 | id: format!("winspool:{}", row.name),
|
| 58 | display_name: format!(
|
| 59 | "{} — Windows printer ({})",
|
| 60 | row.name,
|
| 61 | row.port.trim()
|
| 62 | ),
|
| 63 | target: PrinterTarget::WinSpooler(row.name.clone()),
|
| 64 | };
|
| 65 |
|
| 66 | if is_raw_driver(&row.driver) || matches_pos_name(&row.name) {
|
| 67 | matched.push(device);
|
| 68 | } else {
|
| 69 | rest.push(device);
|
| 70 | }
|
| 71 | }
|
| 72 |
|
| 73 | matched.extend(rest);
|
| 74 | matched
|
| 75 | }
|
| 76 |
|
| 77 | fn query_printers() -> Result<Vec<WinPrinterRow>, PrintError> {
|
| 78 | let output = hidden_command("powershell")
|
| 79 | .args([
|
| 80 | "-NoProfile",
|
| 81 | "-ExecutionPolicy",
|
| 82 | "Bypass",
|
| 83 | "-Command",
|
| 84 | "Get-Printer | Select-Object Name, PortName, DriverName | ConvertTo-Json -Compress",
|
| 85 | ])
|
| 86 | .output()
|
| 87 | .map_err(|e| PrintError::Open(e.to_string()))?;
|
| 88 |
|
| 89 | if !output.status.success() {
|
| 90 | let stderr = String::from_utf8_lossy(&output.stderr);
|
| 91 | return Err(PrintError::Open(stderr.trim().to_string()));
|
| 92 | }
|
| 93 |
|
| 94 | let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
| 95 | if text.is_empty() {
|
| 96 | return Ok(Vec::new());
|
| 97 | }
|
| 98 |
|
| 99 | if let Ok(rows) = serde_json::from_str::<Vec<WinPrinterRow>>(&text) {
|
| 100 | return Ok(rows);
|
| 101 | }
|
| 102 | if let Ok(row) = serde_json::from_str::<WinPrinterRow>(&text) {
|
| 103 | return Ok(vec![row]);
|
| 104 | }
|
| 105 | Ok(Vec::new())
|
| 106 | }
|
| 107 |
|
| 108 | fn is_com_port(port: &str) -> bool {
|
| 109 | let port = port.trim();
|
| 110 | port.len() >= 4
|
| 111 | && port[..3].eq_ignore_ascii_case("COM")
|
| 112 | && port[3..].chars().all(|c| c.is_ascii_digit())
|
| 113 | }
|
| 114 |
|
| 115 | fn is_raw_driver(driver: &str) -> bool {
|
| 116 | let driver = driver.to_ascii_lowercase();
|
| 117 | driver.contains("generic")
|
| 118 | || driver.contains("text only")
|
| 119 | || driver.contains("raw")
|
| 120 | || driver.contains("escpos")
|
| 121 | }
|
| 122 |
|
| 123 | fn matches_pos_name(name: &str) -> bool {
|
| 124 | let lower = name.to_ascii_lowercase();
|
| 125 | POS_NAME_PATTERNS.iter().any(|needle| lower.contains(needle))
|
| 126 | }
|
| 127 |
|
| 128 | pub struct WinSpoolerTransport {
|
| 129 | printer_name: String,
|
| 130 | }
|
| 131 |
|
| 132 | impl WinSpoolerTransport {
|
| 133 | pub fn new(printer_name: impl Into<String>) -> Self {
|
| 134 | Self {
|
| 135 | printer_name: printer_name.into(),
|
| 136 | }
|
| 137 | }
|
| 138 | }
|
| 139 |
|
| 140 | impl super::PrinterTransport for WinSpoolerTransport {
|
| 141 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
| 142 | // Close the handle before PowerShell reads: NamedTempFile keeps the file
|
| 143 | // open, and on Windows that blocks ReadAllBytes ("used by another process").
|
| 144 | let tmp = tempfile::NamedTempFile::new()?;
|
| 145 | std::fs::write(tmp.path(), data)?;
|
| 146 | let tmp_path = tmp.into_temp_path();
|
| 147 |
|
| 148 | let safe_printer = self.printer_name.replace('\'', "''");
|
| 149 | let safe_file = tmp_path.to_string_lossy().replace('\'', "''");
|
| 150 |
|
| 151 | let script = format!(
|
| 152 | r#"
|
| 153 | $ErrorActionPreference = 'Stop'
|
| 154 | Add-Type @"
|
| 155 | using System;
|
| 156 | using System.Runtime.InteropServices;
|
| 157 | public class RawPrinterHelper {{
|
| 158 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
|
| 159 | public class DOCINFOA {{
|
| 160 | [MarshalAs(UnmanagedType.LPStr)] public string pDocName;
|
| 161 | [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
|
| 162 | [MarshalAs(UnmanagedType.LPStr)] public string pDataType;
|
| 163 | }}
|
| 164 | [DllImport("winspool.drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi)]
|
| 165 | public static extern bool OpenPrinter(string szPrinter, out IntPtr hPrinter, IntPtr pd);
|
| 166 | [DllImport("winspool.drv", EntryPoint = "ClosePrinter", SetLastError = true)]
|
| 167 | public static extern bool ClosePrinter(IntPtr hPrinter);
|
| 168 | [DllImport("winspool.drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi)]
|
| 169 | public static extern bool StartDocPrinter(IntPtr hPrinter, int level, [In] DOCINFOA di);
|
| 170 | [DllImport("winspool.drv", EntryPoint = "EndDocPrinter", SetLastError = true)]
|
| 171 | public static extern bool EndDocPrinter(IntPtr hPrinter);
|
| 172 | [DllImport("winspool.drv", EntryPoint = "StartPagePrinter", SetLastError = true)]
|
| 173 | public static extern bool StartPagePrinter(IntPtr hPrinter);
|
| 174 | [DllImport("winspool.drv", EntryPoint = "EndPagePrinter", SetLastError = true)]
|
| 175 | public static extern bool EndPagePrinter(IntPtr hPrinter);
|
| 176 | [DllImport("winspool.drv", EntryPoint = "WritePrinter", SetLastError = true)]
|
| 177 | public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, int dwCount, out int dwWritten);
|
| 178 | public static void SendBytesToPrinter(string printerName, byte[] bytes) {{
|
| 179 | IntPtr hPrinter;
|
| 180 | if (!OpenPrinter(printerName, out hPrinter, IntPtr.Zero)) {{
|
| 181 | throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "OpenPrinter failed");
|
| 182 | }}
|
| 183 | try {{
|
| 184 | DOCINFOA di = new DOCINFOA();
|
| 185 | di.pDocName = "posprint";
|
| 186 | di.pDataType = "RAW";
|
| 187 | if (!StartDocPrinter(hPrinter, 1, di)) {{
|
| 188 | throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "StartDocPrinter failed");
|
| 189 | }}
|
| 190 | try {{
|
| 191 | if (!StartPagePrinter(hPrinter)) {{
|
| 192 | throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "StartPagePrinter failed");
|
| 193 | }}
|
| 194 | try {{
|
| 195 | const int chunkSize = 512;
|
| 196 | for (int offset = 0; offset < bytes.Length; offset += chunkSize) {{
|
| 197 | int length = Math.Min(chunkSize, bytes.Length - offset);
|
| 198 | IntPtr unmanagedBytes = Marshal.AllocCoTaskMem(length);
|
| 199 | try {{
|
| 200 | Marshal.Copy(bytes, offset, unmanagedBytes, length);
|
| 201 | int written;
|
| 202 | if (!WritePrinter(hPrinter, unmanagedBytes, length, out written) || written != length) {{
|
| 203 | throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "WritePrinter failed");
|
| 204 | }}
|
| 205 | }} finally {{
|
| 206 | Marshal.FreeCoTaskMem(unmanagedBytes);
|
| 207 | }}
|
| 208 | }}
|
| 209 | }} finally {{
|
| 210 | EndPagePrinter(hPrinter);
|
| 211 | }}
|
| 212 | }} finally {{
|
| 213 | EndDocPrinter(hPrinter);
|
| 214 | }}
|
| 215 | }} finally {{
|
| 216 | ClosePrinter(hPrinter);
|
| 217 | }}
|
| 218 | }}
|
| 219 | }}
|
| 220 | "@
|
| 221 | $bytes = [System.IO.File]::ReadAllBytes('{safe_file}')
|
| 222 | [RawPrinterHelper]::SendBytesToPrinter('{safe_printer}', $bytes)
|
| 223 | Write-Output 'OK'
|
| 224 | "#
|
| 225 | );
|
| 226 |
|
| 227 | let output = hidden_command("powershell")
|
| 228 | .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &script])
|
| 229 | .output()
|
| 230 | .map_err(io::Error::other)?;
|
| 231 |
|
| 232 | // Keep tmp_path alive until PowerShell has finished reading it.
|
| 233 | drop(tmp_path);
|
| 234 |
|
| 235 | if !output.status.success() {
|
| 236 | let stderr = String::from_utf8_lossy(&output.stderr);
|
| 237 | return Err(io::Error::other(stderr.trim()));
|
| 238 | }
|
| 239 |
|
| 240 | let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
| 241 | if stdout != "OK" {
|
| 242 | return Err(io::Error::other(stdout));
|
| 243 | }
|
| 244 | Ok(())
|
| 245 | }
|
| 246 |
|
| 247 | fn flush(&mut self) -> io::Result<()> {
|
| 248 | Ok(())
|
| 249 | }
|
| 250 | }
|
| 251 |
|
| 252 | #[cfg(test)]
|
| 253 | mod tests {
|
| 254 | use super::*;
|
| 255 |
|
| 256 | #[test]
|
| 257 | fn list_spooler_does_not_panic() {
|
| 258 | let _ = list_windows_spooler_printers();
|
| 259 | }
|
| 260 |
|
| 261 | #[test]
|
| 262 | fn detects_com_ports() {
|
| 263 | assert!(is_com_port("COM3"));
|
| 264 | assert!(!is_com_port("USB001"));
|
| 265 | }
|
| 266 |
|
| 267 | #[test]
|
| 268 | fn temp_payload_readable_after_handle_closed() {
|
| 269 | // Mirrors write_all: PowerShell ReadAllBytes needs the file closed on Windows.
|
| 270 | let tmp = tempfile::NamedTempFile::new().unwrap();
|
| 271 | std::fs::write(tmp.path(), b"escpos").unwrap();
|
| 272 | let path = tmp.into_temp_path();
|
| 273 | let bytes = std::fs::read(&path).unwrap();
|
| 274 | assert_eq!(bytes, b"escpos");
|
| 275 | }
|
| 276 | }
|