Skip to main content

clairlune_platform/
login.rs

1//! Starting at sign-in, quietly: the entry runs the app with
2//! [`BACKGROUND_ARG`], so it comes up in the tray (the menu bar on macOS)
3//! with no window. Windows keeps it in the per-user Run key (`windows.rs`);
4//! macOS in a per-user launch agent.
5// Each system writes one kind of entry; the others' are only tested here.
6#![allow(dead_code)]
7
8use std::path::Path;
9
10/// The argument a sign-in launch passes: start quietly, no window.
11pub const BACKGROUND_ARG: &str = "--background";
12
13fn xml(s: &str) -> String {
14    s.replace('&', "&")
15        .replace('<', "&lt;")
16        .replace('>', "&gt;")
17        .replace('"', "&quot;")
18}
19
20/// macOS: the launch agent, run once at each sign-in.
21pub(crate) fn launch_agent(exe: &Path) -> String {
22    format!(
23        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
24         <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
25         <plist version=\"1.0\">\n<dict>\n\
26         \t<key>Label</key>\n\t<string>{LABEL}</string>\n\
27         \t<key>ProgramArguments</key>\n\t<array>\n\t\t<string>{}</string>\n\t\t<string>{BACKGROUND_ARG}</string>\n\t</array>\n\
28         \t<key>RunAtLoad</key>\n\t<true/>\n\
29         \t<key>ProcessType</key>\n\t<string>Interactive</string>\n\
30         </dict>\n</plist>\n",
31        xml(&exe.to_string_lossy())
32    )
33}
34
35/// The launch agent's label (the app's bundle identifier).
36const LABEL: &str = "app.clairlune";
37
38/// Where the entry lives, and its text for `exe`.
39#[cfg(target_os = "macos")]
40fn entry(exe: &Path) -> Option<(std::path::PathBuf, String)> {
41    let path = crate::home_dir()?
42        .join("Library")
43        .join("LaunchAgents")
44        .join(format!("{LABEL}.plist"));
45    Some((path, launch_agent(exe)))
46}
47
48/// macOS: the entry is there, but turned off in System Settings > General >
49/// Login Items (macOS 13 and later let the user switch background items
50/// off there; Clairlune can't turn it back on itself).
51#[cfg(target_os = "macos")]
52pub(crate) fn needs_approval(exe: &Path) -> bool {
53    use objc2_foundation::{NSString, NSURL};
54    use objc2_service_management::{SMAppService, SMAppServiceStatus};
55    let Some((path, _)) = entry(exe).filter(|(path, _)| path.exists()) else {
56        return false;
57    };
58    let url = NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()));
59    // SAFETY: a file URL to the agent's plist (macOS 13, the oldest
60    // supported, has this call).
61    unsafe { SMAppService::statusForLegacyURL(&url) == SMAppServiceStatus::RequiresApproval }
62}
63
64/// macOS: System Settings at General > Login Items.
65#[cfg(target_os = "macos")]
66pub(crate) fn open_login_items() {
67    // SAFETY: no arguments; macOS 13 has it.
68    unsafe { objc2_service_management::SMAppService::openSystemSettingsLoginItems() };
69}
70
71/// Whether the entry is there and starts this `exe`.
72#[cfg(target_os = "macos")]
73pub(crate) fn registered(exe: &Path) -> bool {
74    entry(exe).is_some_and(|(path, text)| std::fs::read_to_string(path).is_ok_and(|t| t == text))
75}
76
77/// Writes or removes the entry.
78#[cfg(target_os = "macos")]
79pub(crate) fn set(exe: &Path, enable: bool) -> Result<(), crate::PlatformError> {
80    let os = |e: std::io::Error| crate::PlatformError::Os(e.to_string());
81    let (path, text) =
82        entry(exe).ok_or_else(|| crate::PlatformError::Os("no home or config folder".into()))?;
83    if enable {
84        if let Some(dir) = path.parent() {
85            std::fs::create_dir_all(dir).map_err(os)?;
86        }
87        std::fs::write(&path, text).map_err(os)
88    } else {
89        match std::fs::remove_file(&path) {
90            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(os(e)),
91            _ => Ok(()),
92        }
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn the_launch_agent_escapes_the_path_and_starts_quietly() {
102        let text = launch_agent(Path::new(
103            "/Applications/A & B.app/Contents/MacOS/clairlune",
104        ));
105        assert!(
106            text.contains("<string>/Applications/A &amp; B.app/Contents/MacOS/clairlune</string>")
107        );
108        assert!(text.contains("<string>--background</string>"));
109        assert!(text.contains("<key>RunAtLoad</key>\n\t<true/>"));
110        assert!(text.contains("<string>app.clairlune</string>"));
111    }
112}