use serde::{Deserialize, Serialize};
use crate::error::IronError;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PrinterConnection {
USB,
Network,
Shared,
Bluetooth,
Virtual,
Legacy,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PrinterStatus {
Idle,
Printing,
Paused,
Offline,
Error,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PrinterType {
Laser,
Inkjet,
Thermal,
DotMatrix,
Printer3D,
Virtual,
Plotter,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrinterInfo {
pub name: String,
pub description: String,
pub driver: String,
pub port: String,
pub connection: PrinterConnection,
pub status: PrinterStatus,
pub printer_type: PrinterType,
pub is_default: Option<bool>,
pub accepting_jobs: Option<bool>,
pub shared: Option<bool>,
pub color: Option<bool>,
pub duplex: Option<bool>,
pub jobs_in_queue: Option<u32>,
pub location: String,
}
pub struct PrinterMonitor {
printers: Vec<PrinterInfo>,
}
#[cfg(target_os = "windows")]
fn status_from_cim(extended: u64, basic: u64) -> PrinterStatus {
fn specific(code: u64) -> Option<PrinterStatus> {
match code {
3 => Some(PrinterStatus::Idle),
4 => Some(PrinterStatus::Printing),
6 | 8 => Some(PrinterStatus::Paused),
7 => Some(PrinterStatus::Offline),
_ => None,
}
}
specific(extended)
.or_else(|| specific(basic))
.unwrap_or(PrinterStatus::Unknown)
}
impl PrinterMonitor {
pub fn new() -> Result<Self, IronError> {
let mut monitor = Self {
printers: Vec::new(),
};
monitor.refresh()?;
Ok(monitor)
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.printers.clear();
#[cfg(target_os = "linux")]
self.refresh_cups()?;
#[cfg(target_os = "macos")]
self.refresh_cups()?;
#[cfg(target_os = "windows")]
self.refresh_windows()?;
Ok(())
}
pub fn printers(&self) -> &[PrinterInfo] {
&self.printers
}
pub fn default_printer(&self) -> Option<&PrinterInfo> {
self.printers.iter().find(|p| p.is_default == Some(true))
}
pub fn printers_by_status(&self, status: PrinterStatus) -> Vec<&PrinterInfo> {
self.printers
.iter()
.filter(|p| p.status == status)
.collect()
}
pub fn network_printers(&self) -> Vec<&PrinterInfo> {
self.printers
.iter()
.filter(|p| p.connection == PrinterConnection::Network)
.collect()
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn parse_lpstat_accepting(line: &str) -> Option<bool> {
let (_name, state) = line.trim().split_once(' ')?;
if state.starts_with("not accepting requests") {
Some(false)
} else if state.starts_with("accepting requests") {
Some(true)
} else {
None
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn refresh_cups(&mut self) -> Result<(), IronError> {
let default_name: Option<String> = std::process::Command::new("lpstat")
.args(["-d"])
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| {
s.split(':')
.nth(1)
.map(|n| n.trim().to_string())
.unwrap_or_default()
});
let raw = match std::process::Command::new("lpstat")
.args(["-p", "-l"])
.output()
{
Ok(o) => o,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(IronError::CommandFailed(
"lpstat is not installed, so CUPS printers were not enumerated".to_string(),
))
}
Err(e) => return Err(IronError::CommandFailed(format!("lpstat: {e}"))),
};
if !raw.status.success() {
return Err(IronError::CommandFailed(format!(
"lpstat exited {}: {}",
raw.status,
String::from_utf8_lossy(&raw.stderr).trim()
)));
}
let output = String::from_utf8(raw.stdout)
.map_err(|e| IronError::Parse(format!("lpstat output is not UTF-8: {e}")))?;
let device_output = std::process::Command::new("lpstat")
.args(["-v"])
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.unwrap_or_default();
let mut device_map: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for line in device_output.lines() {
if let Some(rest) = line.strip_prefix("device for ") {
if let Some(colon_pos) = rest.find(':') {
let name = rest[..colon_pos].trim().to_string();
let uri = rest[colon_pos + 1..].trim().to_string();
device_map.insert(name, uri);
}
}
}
let accept_output = std::process::Command::new("lpstat")
.args(["-a"])
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.unwrap_or_default();
let mut accept_map: std::collections::HashMap<String, bool> =
std::collections::HashMap::new();
for line in accept_output.lines() {
if let (Some(name), Some(accepting)) = (
line.split_whitespace().next(),
Self::parse_lpstat_accepting(line),
) {
accept_map.insert(name.to_string(), accepting);
}
}
let mut current_name = String::new();
let mut current_desc = String::new();
let mut current_status = PrinterStatus::Unknown;
let mut in_printer = false;
for line in output.lines() {
if let Some(rest) = line.strip_prefix("printer ") {
if in_printer && !current_name.is_empty() {
let port = device_map.get(¤t_name).cloned().unwrap_or_default();
let connection = Self::classify_connection_cups(&port);
let accepting = accept_map.get(¤t_name).copied();
self.printers.push(PrinterInfo {
name: current_name.clone(),
description: current_desc.clone(),
driver: String::new(),
port,
connection,
status: current_status.clone(),
printer_type: PrinterType::Unknown,
is_default: default_name.as_deref().map(|d| d == current_name.as_str()),
accepting_jobs: accepting,
shared: None,
color: None,
duplex: None,
jobs_in_queue: None,
location: String::new(),
});
}
let (name, status) = Self::parse_lpstat_printer_line(rest);
current_name = name;
current_desc = String::new();
in_printer = true;
current_status = status;
} else if in_printer && line.starts_with("\tDescription:") {
current_desc = line
.strip_prefix("\tDescription:")
.unwrap_or("")
.trim()
.to_string();
} else if in_printer && line.starts_with("\tLocation:") {
}
}
if in_printer && !current_name.is_empty() {
let port = device_map.get(¤t_name).cloned().unwrap_or_default();
let connection = Self::classify_connection_cups(&port);
let accepting = accept_map.get(¤t_name).copied();
self.printers.push(PrinterInfo {
name: current_name.clone(),
description: current_desc,
driver: String::new(),
port,
connection,
status: current_status,
printer_type: PrinterType::Unknown,
is_default: default_name.as_deref().map(|d| d == current_name.as_str()),
accepting_jobs: accepting,
shared: None,
color: None,
duplex: None,
jobs_in_queue: None,
location: String::new(),
});
}
Ok(())
}
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(dead_code))]
fn parse_lpstat_printer_line(rest: &str) -> (String, PrinterStatus) {
let rest = rest.trim_start();
let (name, after) = match rest.split_once(char::is_whitespace) {
Some((name, after)) => (name, after.trim_start()),
None => (rest, ""),
};
let status = if after.starts_with("is idle") {
PrinterStatus::Idle
} else if after.starts_with("now printing") {
PrinterStatus::Printing
} else if after.starts_with("disabled") || after.starts_with("is stopped") {
PrinterStatus::Paused
} else {
PrinterStatus::Unknown
};
(name.to_string(), status)
}
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn is_virtual_port_win(port_lower: &str) -> bool {
port_lower.starts_with("portprompt:")
|| port_lower.starts_with("xpsport:")
|| port_lower == "nul:"
|| port_lower.contains("onenote")
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn classify_connection_cups(uri: &str) -> PrinterConnection {
let u = uri.to_lowercase();
if u.starts_with("usb:") {
PrinterConnection::USB
} else if u.starts_with("ipp:")
|| u.starts_with("ipps:")
|| u.starts_with("http:")
|| u.starts_with("https:")
|| u.starts_with("socket:")
|| u.starts_with("lpd:")
{
PrinterConnection::Network
} else if u.starts_with("smb:") {
PrinterConnection::Shared
} else if u.contains("pdf") || u.contains("cups-pdf") || u.contains("virtual") {
PrinterConnection::Virtual
} else if u.starts_with("serial:") || u.starts_with("parallel:") {
PrinterConnection::Legacy
} else {
PrinterConnection::Unknown
}
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) -> Result<(), IronError> {
const QUERY: &str = "Get-CimInstance Win32_Printer | Select-Object Name, DriverName, PortName, PrinterStatus, ExtendedPrinterStatus, Comment, Location, Shared, Capabilities, Default, PrinterState, JobCountSinceLastReset, Network | ConvertTo-Json -Compress";
let Some(val) =
crate::core::command::capture_json("powershell", &["-NoProfile", "-Command", QUERY])?
else {
return Ok(());
};
{
let items = crate::core::command::json_items(&val);
for item in &items {
let name = item["Name"].as_str().unwrap_or("").to_string();
let driver = item["DriverName"].as_str().unwrap_or("").to_string();
let port = item["PortName"].as_str().unwrap_or("").to_string();
let location = item["Location"].as_str().unwrap_or("").to_string();
let description = item["Comment"].as_str().unwrap_or("").to_string();
let shared = item["Shared"].as_bool();
let color = item["Capabilities"]
.as_array()
.filter(|caps| !caps.is_empty())
.map(|caps| {
caps.iter()
.filter_map(serde_json::Value::as_u64)
.any(|c| c == 2)
});
let is_default = item["Default"].as_bool();
let is_network = item["Network"].as_bool().unwrap_or(false);
let status = status_from_cim(
item["ExtendedPrinterStatus"].as_u64().unwrap_or(0),
item["PrinterStatus"].as_u64().unwrap_or(0),
);
let port_lower = port.to_lowercase();
let connection = if is_network {
PrinterConnection::Network
} else if port_lower.starts_with("wsd-") {
PrinterConnection::Network
} else if port_lower.contains("usb") {
PrinterConnection::USB
} else if Self::is_virtual_port_win(&port_lower) {
PrinterConnection::Virtual
} else {
PrinterConnection::Unknown
};
let printer_type = Self::infer_printer_type_win(&name, &driver);
self.printers.push(PrinterInfo {
name,
description,
driver,
port,
connection,
accepting_jobs: None,
status,
printer_type,
is_default,
shared,
color,
duplex: None,
jobs_in_queue: None,
location,
});
}
}
Ok(())
}
#[cfg(target_os = "windows")]
fn infer_printer_type_win(name: &str, driver: &str) -> PrinterType {
let combined = format!("{} {}", name, driver).to_lowercase();
if combined.contains("pdf")
|| combined.contains("xps")
|| combined.contains("onenote")
|| combined.contains("fax")
{
PrinterType::Virtual
} else if combined.contains("laser") || combined.contains("laserjet") {
PrinterType::Laser
} else if combined.contains("inkjet")
|| combined.contains("deskjet")
|| combined.contains("officejet")
|| combined.contains("pixma")
|| combined.contains("envy")
{
PrinterType::Inkjet
} else if combined.contains("thermal")
|| combined.contains("receipt")
|| combined.contains("label")
{
PrinterType::Thermal
} else if combined.contains("plotter") || combined.contains("designjet") {
PrinterType::Plotter
} else {
PrinterType::Unknown
}
}
}
impl Default for PrinterMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
printers: Vec::new(),
})
}
}
impl std::fmt::Display for PrinterStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Idle => write!(f, "Idle"),
Self::Printing => write!(f, "Printing"),
Self::Paused => write!(f, "Paused"),
Self::Offline => write!(f, "Offline"),
Self::Error => write!(f, "Error"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
impl std::fmt::Display for PrinterConnection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::USB => write!(f, "USB"),
Self::Network => write!(f, "Network"),
Self::Shared => write!(f, "Shared"),
Self::Bluetooth => write!(f, "Bluetooth"),
Self::Virtual => write!(f, "Virtual"),
Self::Legacy => write!(f, "Legacy"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_printer_monitor_creation() {
match PrinterMonitor::new() {
Ok(monitor) => {
let _ = monitor.printers();
}
Err(e) => {
let why = e.to_string();
assert!(
why.len() > 10,
"enumeration failed without saying why: {why:?}"
);
}
}
}
#[test]
fn test_printer_monitor_default() {
let monitor = PrinterMonitor::default();
let _ = monitor.printers();
let _ = monitor.default_printer();
}
#[test]
fn test_printer_serialization() {
let printer = PrinterInfo {
name: "TestPrinter".into(),
description: "A test printer".into(),
driver: "Generic".into(),
port: "USB001".into(),
connection: PrinterConnection::USB,
status: PrinterStatus::Idle,
printer_type: PrinterType::Laser,
is_default: Some(true),
accepting_jobs: Some(true),
shared: Some(false),
color: Some(true),
duplex: Some(true),
jobs_in_queue: None,
location: "Office".into(),
};
let json = serde_json::to_string(&printer).unwrap();
assert!(json.contains("TestPrinter"));
let _: PrinterInfo = serde_json::from_str(&json).unwrap();
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn lpstat_accepting_state_is_read_not_matched() {
let accepting = "HP_Laser accepting requests since Mon 05 Oct 2026 09:14:02 AM BST";
let refusing = "Office_MFP not accepting requests since Tue 06 Oct 2026 11:02:47 AM BST";
assert_eq!(
PrinterMonitor::parse_lpstat_accepting(accepting),
Some(true)
);
assert_eq!(
PrinterMonitor::parse_lpstat_accepting(refusing),
Some(false)
);
assert_eq!(PrinterMonitor::parse_lpstat_accepting("garbage"), None);
assert_eq!(PrinterMonitor::parse_lpstat_accepting(""), None);
}
#[test]
fn lpstat_state_comes_from_after_the_name() {
let parse = PrinterMonitor::parse_lpstat_printer_line;
let (name, status) = parse("HP_Laser is idle. enabled since Mon 05 Oct 2026");
assert_eq!(name, "HP_Laser");
assert_eq!(status, PrinterStatus::Idle);
let (name, status) = parse("HP_Laser now printing HP_Laser-42. enabled since Mon");
assert_eq!(name, "HP_Laser");
assert_eq!(status, PrinterStatus::Printing);
let (name, status) = parse("Office_MFP disabled since Tue 06 Oct 2026 11:02:47 AM BST");
assert_eq!(name, "Office_MFP");
assert_eq!(status, PrinterStatus::Paused);
let (name, status) = parse("idle_room is printing_bay. enabled since Mon");
assert_eq!(name, "idle_room");
assert_eq!(status, PrinterStatus::Unknown);
let (name, status) = parse("idle_room is idle. enabled since Mon");
assert_eq!(name, "idle_room");
assert_eq!(status, PrinterStatus::Idle);
let (name, status) = parse("printing_bay now printing printing_bay-7. enabled since Mon");
assert_eq!(name, "printing_bay");
assert_eq!(status, PrinterStatus::Printing);
let (name, status) = parse("stopped disabled since Mon");
assert_eq!(name, "stopped");
assert_eq!(status, PrinterStatus::Paused);
let (name, status) = parse("disabled is idle.");
assert_eq!(name, "disabled");
assert_eq!(status, PrinterStatus::Idle);
let (_, status) = parse("Lab is processing something unusual");
assert_eq!(status, PrinterStatus::Unknown);
}
#[test]
fn windows_virtual_ports_are_recognised_by_port_only() {
assert!(PrinterMonitor::is_virtual_port_win("portprompt:"));
assert!(PrinterMonitor::is_virtual_port_win("xpsport:"));
assert!(PrinterMonitor::is_virtual_port_win("nul:"));
assert!(PrinterMonitor::is_virtual_port_win(
"microsoft.office.onenotevirtualprinter_8wekyb3d8bbwe_onenote-psa:print-to-onenote_s-1"
));
assert!(!PrinterMonitor::is_virtual_port_win("usb001"));
assert!(!PrinterMonitor::is_virtual_port_win(
"wsd-89a9ad78-3c8f-4d2b-92fe-edb15cb2c4b1"
));
assert!(!PrinterMonitor::is_virtual_port_win(""));
}
#[test]
fn test_status_display() {
assert_eq!(PrinterStatus::Idle.to_string(), "Idle");
assert_eq!(PrinterStatus::Printing.to_string(), "Printing");
assert_eq!(PrinterConnection::USB.to_string(), "USB");
}
}
#[cfg(all(test, target_os = "windows"))]
mod windows_status_tests {
use super::{status_from_cim, PrinterStatus};
#[test]
fn whichever_column_names_a_state_answers() {
assert_eq!(status_from_cim(7, 1), PrinterStatus::Offline);
assert_eq!(status_from_cim(2, 3), PrinterStatus::Idle);
}
#[test]
fn two_absences_stay_an_absence() {
assert_eq!(status_from_cim(2, 1), PrinterStatus::Unknown);
assert_eq!(status_from_cim(0, 0), PrinterStatus::Unknown);
assert_eq!(status_from_cim(18, 2), PrinterStatus::Unknown);
}
}