//! Register Explorer / file-manager integration and the `posprint://` URL protocol. /// Install or refresh shell integration (best-effort; ignores errors). pub fn ensure_shell_integration() { #[cfg(windows)] windows::register_all(); } #[cfg(windows)] mod windows { use std::path::Path; pub fn register_all() { let Ok(exe) = std::env::current_exe() else { return; }; if let Some(cmd) = print_command_for_exe(&exe) { let _ = write_user_context_menu(&cmd); } if let Some(cmd) = url_command_for_exe(&exe) { let _ = write_url_protocol(&cmd); } } pub fn print_command_for_exe(exe: &Path) -> Option { let exe = exe.to_string_lossy(); if exe.is_empty() { return None; } Some(format!("\"{exe}\" --print \"%1\"")) } pub fn url_command_for_exe(exe: &Path) -> Option { let exe = exe.to_string_lossy(); if exe.is_empty() { return None; } Some(format!("\"{exe}\" \"%1\"")) } fn write_user_context_menu(command: &str) -> Result<(), String> { use winreg::enums::HKEY_CURRENT_USER; use winreg::RegKey; const SHELL_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint"; const COMMAND_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint\command"; let hkcu = RegKey::predef(HKEY_CURRENT_USER); let (shell, _) = hkcu .create_subkey(SHELL_KEY) .map_err(|e| e.to_string())?; shell .set_value("", &"Print") .map_err(|e| e.to_string())?; let (cmd, _) = hkcu .create_subkey(COMMAND_KEY) .map_err(|e| e.to_string())?; cmd.set_value("", &command) .map_err(|e| e.to_string())?; Ok(()) } fn write_url_protocol(command: &str) -> Result<(), String> { use winreg::enums::HKEY_CURRENT_USER; use winreg::RegKey; const ROOT: &str = r"Software\Classes\posprint"; const COMMAND_KEY: &str = r"Software\Classes\posprint\shell\open\command"; let hkcu = RegKey::predef(HKEY_CURRENT_USER); let (root, _) = hkcu.create_subkey(ROOT).map_err(|e| e.to_string())?; root.set_value("", &"URL:posprint Protocol") .map_err(|e| e.to_string())?; root.set_value("URL Protocol", &"") .map_err(|e| e.to_string())?; let (cmd, _) = hkcu .create_subkey(COMMAND_KEY) .map_err(|e| e.to_string())?; cmd.set_value("", &command) .map_err(|e| e.to_string())?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn builds_print_command() { let cmd = print_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap(); assert_eq!(cmd, r#""C:\Apps\posprint.exe" --print "%1""#); } #[test] fn builds_url_command() { let cmd = url_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap(); assert_eq!(cmd, r#""C:\Apps\posprint.exe" "%1""#); } } }