BlueGit

timfa posprint

Files

posprint / src / shell_integration.rs

shell_integration.rs

shell_integration.rs 3.2 KiB Download Raw
1//! Register Explorer / file-manager integration and the `posprint://` URL protocol.
2
3/// Install or refresh shell integration (best-effort; ignores errors).
4pub fn ensure_shell_integration() {
5 #[cfg(windows)]
6 windows::register_all();
7}
8
9#[cfg(windows)]
10mod windows {
11 use std::path::Path;
12
13 pub fn register_all() {
14 let Ok(exe) = std::env::current_exe() else {
15 return;
16 };
17 if let Some(cmd) = print_command_for_exe(&exe) {
18 let _ = write_user_context_menu(&cmd);
19 }
20 if let Some(cmd) = url_command_for_exe(&exe) {
21 let _ = write_url_protocol(&cmd);
22 }
23 }
24
25 pub fn print_command_for_exe(exe: &Path) -> Option<String> {
26 let exe = exe.to_string_lossy();
27 if exe.is_empty() {
28 return None;
29 }
30 Some(format!("\"{exe}\" --print \"%1\""))
31 }
32
33 pub fn url_command_for_exe(exe: &Path) -> Option<String> {
34 let exe = exe.to_string_lossy();
35 if exe.is_empty() {
36 return None;
37 }
38 Some(format!("\"{exe}\" \"%1\""))
39 }
40
41 fn write_user_context_menu(command: &str) -> Result<(), String> {
42 use winreg::enums::HKEY_CURRENT_USER;
43 use winreg::RegKey;
44
45 const SHELL_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint";
46 const COMMAND_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint\command";
47
48 let hkcu = RegKey::predef(HKEY_CURRENT_USER);
49 let (shell, _) = hkcu
50 .create_subkey(SHELL_KEY)
51 .map_err(|e| e.to_string())?;
52 shell
53 .set_value("", &"Print")
54 .map_err(|e| e.to_string())?;
55
56 let (cmd, _) = hkcu
57 .create_subkey(COMMAND_KEY)
58 .map_err(|e| e.to_string())?;
59 cmd.set_value("", &command)
60 .map_err(|e| e.to_string())?;
61 Ok(())
62 }
63
64 fn write_url_protocol(command: &str) -> Result<(), String> {
65 use winreg::enums::HKEY_CURRENT_USER;
66 use winreg::RegKey;
67
68 const ROOT: &str = r"Software\Classes\posprint";
69 const COMMAND_KEY: &str = r"Software\Classes\posprint\shell\open\command";
70
71 let hkcu = RegKey::predef(HKEY_CURRENT_USER);
72 let (root, _) = hkcu.create_subkey(ROOT).map_err(|e| e.to_string())?;
73 root.set_value("", &"URL:posprint Protocol")
74 .map_err(|e| e.to_string())?;
75 root.set_value("URL Protocol", &"")
76 .map_err(|e| e.to_string())?;
77
78 let (cmd, _) = hkcu
79 .create_subkey(COMMAND_KEY)
80 .map_err(|e| e.to_string())?;
81 cmd.set_value("", &command)
82 .map_err(|e| e.to_string())?;
83 Ok(())
84 }
85
86 #[cfg(test)]
87 mod tests {
88 use super::*;
89
90 #[test]
91 fn builds_print_command() {
92 let cmd = print_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap();
93 assert_eq!(cmd, r#""C:\Apps\posprint.exe" --print "%1""#);
94 }
95
96 #[test]
97 fn builds_url_command() {
98 let cmd = url_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap();
99 assert_eq!(cmd, r#""C:\Apps\posprint.exe" "%1""#);
100 }
101 }
102}