use ::std::fs;
use ::std::path::{Path, PathBuf};
use ::std::process::Command;
use ::anyhow::{Context as _, Result, anyhow};
use super::APP_ID;
use crate::tray::ICONS;
const DESKTOP: &str = include_str!("../../data/net.b128.VoiceFilter.desktop");
const ICON: &str = include_str!("../../data/net.b128.VoiceFilter.svg");
pub fn data_home() -> Result<PathBuf> {
::std::env::var_os("XDG_DATA_HOME")
.filter(|dir| !dir.is_empty())
.map(PathBuf::from)
.or_else(|| ::std::env::var_os("HOME").map(|home| Path::new(&home).join(".local/share")))
.ok_or_else(|| anyhow!("Neither XDG_DATA_HOME nor HOME is set"))
}
pub fn install(data_home: &Path, exe: &Path) -> Result<Vec<PathBuf>> {
let exe = exe
.to_str()
.ok_or_else(|| anyhow!("The path {} isn't UTF-8", exe.display()))?;
let desktop: String = DESKTOP
.lines()
.map(|line| match line.strip_prefix("Exec=") {
Some(_) => format!("Exec={} ui\n", quote(exe)),
None => format!("{line}\n"),
})
.collect();
let entry = data_home
.join("applications")
.join(format!("{APP_ID}.desktop"));
let icon = data_home
.join("icons/hicolor/scalable/apps")
.join(format!("{APP_ID}.svg"));
let symbolic = data_home.join("icons/hicolor/symbolic/apps");
let mut files = vec![(entry, desktop.as_str()), (icon, ICON)];
files.extend(
ICONS
.into_iter()
.map(|(name, svg)| (symbolic.join(format!("{name}.svg")), svg)),
);
for (path, content) in &files {
let dir = path.parent().expect("a file in a directory");
fs::create_dir_all(dir).with_context(|| format!("Could not create {}", dir.display()))?;
fs::write(path, content).with_context(|| format!("Could not write {}", path.display()))?;
}
Ok(files.into_iter().map(|(path, _)| path).collect())
}
pub fn update_icon_cache(data_home: &Path) {
let theme = data_home.join("icons/hicolor");
for tool in ["gtk4-update-icon-cache", "gtk-update-icon-cache"] {
let updated = Command::new(tool)
.args(["--force", "--ignore-theme-index", "--quiet"])
.arg(&theme)
.status();
if updated.is_ok_and(|status| status.success()) {
return;
}
}
}
pub fn quote(path: &str) -> String {
let reserved = |c: char| " \t\n\"'\\><~|&;$*?#()`".contains(c);
let quoted = path.contains(reserved);
let mut arg = String::new();
if quoted {
arg.push('"');
}
for c in path.chars() {
match c {
'"' | '`' | '$' => {
arg.push_str(r"\\");
arg.push(c);
}
'\\' => arg.push_str(r"\\\\"),
'\n' => arg.push_str(r"\n"),
'\t' => arg.push_str(r"\t"),
'%' => arg.push_str("%%"),
c => arg.push(c),
}
}
if quoted {
arg.push('"');
}
arg
}