BlueGit

timfa posprint

Files

posprint / src / shell_integration.rs

shell_integration.rs

fixes
timfa Tim Falken · pushed by timfa · 4 months ago
4ab2186f History
shell_integration.rs 1.9 KiB Download Raw
1//! Register a Explorer / file-manager "Print" action for `.pos` templates.
2
3/// Install or refresh shell integration (best-effort; ignores errors).
4pub fn ensure_print_context_menu() {
5 #[cfg(windows)]
6 windows::register_print_context_menu();
7}
8
9#[cfg(windows)]
10mod windows {
11 use std::path::Path;
12
13 pub fn register_print_context_menu() {
14 let Ok(exe) = std::env::current_exe() else {
15 return;
16 };
17 let Some(cmd) = print_command_for_exe(&exe) else {
18 return;
19 };
20 let _ = write_user_context_menu(&cmd);
21 }
22
23 pub fn print_command_for_exe(exe: &Path) -> Option<String> {
24 let exe = exe.to_string_lossy();
25 if exe.is_empty() {
26 return None;
27 }
28 Some(format!("\"{exe}\" --print \"%1\""))
29 }
30
31 fn write_user_context_menu(command: &str) -> Result<(), String> {
32 use winreg::enums::HKEY_CURRENT_USER;
33 use winreg::RegKey;
34
35 const SHELL_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint";
36 const COMMAND_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint\command";
37
38 let hkcu = RegKey::predef(HKEY_CURRENT_USER);
39 let (shell, _) = hkcu
40 .create_subkey(SHELL_KEY)
41 .map_err(|e| e.to_string())?;
42 shell
43 .set_value("", &"Print")
44 .map_err(|e| e.to_string())?;
45
46 let (cmd, _) = hkcu
47 .create_subkey(COMMAND_KEY)
48 .map_err(|e| e.to_string())?;
49 cmd.set_value("", &command)
50 .map_err(|e| e.to_string())?;
51 Ok(())
52 }
53
54 #[cfg(test)]
55 mod tests {
56 use super::*;
57
58 #[test]
59 fn builds_print_command() {
60 let cmd = print_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap();
61 assert_eq!(cmd, r#""C:\Apps\posprint.exe" --print "%1""#);
62 }
63 }
64}