Medlar/crates/app/src/autostart.rs

55 lines
2.2 KiB
Rust

//! The autostart entry: `<config>/autostart/medlar.desktop`. Callers pass the config folder, so that tests use a
//! throwaway one.
use std::io;
use std::path::{Path, PathBuf};
pub const FILE: &str = "medlar.desktop";
/// The entry's text. `exe` is the AppImage when there is one, else this program.
pub fn entry(exe: &Path, minimised: bool) -> String {
let exe = exe.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
let quoted = if exe.contains([' ', '\t']) { format!("\"{exe}\"") } else { exe };
let flag = if minimised { " --minimised" } else { "" };
format!(
"[Desktop Entry]\nType=Application\nName=Medlar\nComment=Download manager\nExec={quoted}{flag}\nIcon=medlar\nTerminal=false\nX-GNOME-Autostart-enabled=true\n"
)
}
fn program() -> PathBuf {
std::env::var_os("APPIMAGE").map(PathBuf::from).or_else(|| std::env::current_exe().ok()).unwrap_or_else(|| "medlar".into())
}
/// Makes the entry exist (`on`) or not. Without a config folder nothing is done.
pub fn sync(config: Option<PathBuf>, on: bool, minimised: bool) -> io::Result<()> {
let Some(config) = config else { return Ok(()) };
sync_with(&config, &program(), on, minimised)
}
pub fn sync_with(config: &Path, exe: &Path, on: bool, minimised: bool) -> io::Result<()> {
let file = config.join("autostart").join(FILE);
if !on {
return match std::fs::remove_file(&file) {
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
};
}
std::fs::create_dir_all(file.parent().unwrap_or(config))?;
std::fs::write(file, entry(exe, minimised))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn writes_and_removes() {
let dir = tempfile::tempdir().unwrap();
sync_with(dir.path(), Path::new("/opt/My Apps/medlar"), true, true).unwrap();
let text = std::fs::read_to_string(dir.path().join("autostart").join(FILE)).unwrap();
assert!(text.contains("Exec=\"/opt/My Apps/medlar\" --minimised\n"));
sync_with(dir.path(), Path::new("medlar"), false, false).unwrap();
assert!(!dir.path().join("autostart").join(FILE).exists());
sync_with(dir.path(), Path::new("medlar"), false, false).unwrap();
}
}