use std::path::{Path, PathBuf};
use windows::Win32::System::Registry::{KEY_READ, KEY_SET_VALUE};
use crate::os::registry::Key;
pub const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
pub const VALUE: &str = "taskbar-focus";
const MAX_COMMAND: usize = 260;
pub fn current() -> Option<String> {
Key::open(RUN_KEY, KEY_READ)?.get_string(VALUE)
}
pub fn is_on() -> bool {
current().is_some()
}
pub fn set(on: bool) -> Result<(), String> {
let done = match current() {
Some(now) => on && command().is_ok_and(|wanted| wanted == now),
None => !on,
};
if done {
return Ok(());
}
if cfg!(debug_assertions) {
crate::audit::log("autostart: debug build, so the Run value was not changed");
return Ok(());
}
let key = Key::open(RUN_KEY, KEY_READ | KEY_SET_VALUE)
.ok_or("Windows did not allow the startup setting to be changed.")?;
if !on {
crate::audit::log("autostart: removing the Run value");
return key
.delete(VALUE)
.then_some(())
.ok_or_else(|| "The startup setting could not be removed.".into());
}
let command = command()?;
crate::audit::log(&format!("autostart: setting the Run value to {command}"));
key.set_string(VALUE, &command)
.then_some(())
.ok_or_else(|| "The startup setting could not be saved.".into())
}
pub fn command() -> Result<String, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let command = format!("\"{}\"", stable_path(&exe).display());
if command.encode_utf16().count() > MAX_COMMAND {
return Err("The program's path is too long for Windows to start it.".into());
}
Ok(command)
}
fn stable_path(exe: &Path) -> PathBuf {
let scoop = || {
let version = exe.parent()?;
let app = version.parent()?;
let apps = app.parent()?;
if !apps.file_name()?.eq_ignore_ascii_case("apps") {
return None;
}
let name = exe.file_name()?;
let shim = apps.parent()?.join("shims").join(name);
let current = app.join("current").join(name);
[shim, current].into_iter().find(|p| p.exists())
};
scoop().unwrap_or_else(|| exe.to_path_buf())
}