use crate::icon::{self, OwnedIcon};
use std::path::{Path, PathBuf};
pub struct AppInfo<'a> {
pub id: &'a str,
pub name: &'a str,
pub comment: &'a str,
pub categories: &'a str,
pub icons: &'a [OwnedIcon],
pub exec: Option<&'a Path>,
pub terminal: bool,
}
impl<'a> AppInfo<'a> {
pub fn new(id: &'a str, name: &'a str, icons: &'a [OwnedIcon]) -> AppInfo<'a> {
AppInfo { id, name, comment: "", categories: "Utility;", icons, exec: None, terminal: false }
}
}
#[derive(Debug, Default)]
pub struct Installed {
pub files: Vec<PathBuf>,
}
pub type Error = String;
fn check_id(id: &str) -> Result<(), Error> {
if id.is_empty() || id.len() > 255 { return Err(format!("bad app id {id:?}: empty or over 255 bytes")); }
if !id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-' || c == b'_') {
return Err(format!("bad app id {id:?}: use only [A-Za-z0-9._-]"));
}
if id.starts_with('.') || id.contains("..") { return Err(format!("bad app id {id:?}: leading dot or '..'")); }
Ok(())
}
fn home() -> Result<PathBuf, Error> {
std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| "HOME is not set".to_string())
}
fn exec_path(info: &AppInfo) -> Result<PathBuf, Error> {
match info.exec {
Some(p) => Ok(p.to_path_buf()),
None => std::env::current_exe()
.and_then(|p| p.canonicalize())
.map_err(|e| format!("cannot find the running executable: {e}")),
}
}
fn write(path: &Path, bytes: &[u8], out: &mut Installed) -> Result<(), Error> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("mkdir {}: {e}", dir.display()))?;
}
std::fs::write(path, bytes).map_err(|e| format!("write {}: {e}", path.display()))?;
out.files.push(path.to_path_buf());
Ok(())
}
#[cfg(target_os = "linux")]
fn refresh_caches(data: &Path) {
use std::process::{Command, Stdio};
let quiet = |c: &mut Command| { c.stdout(Stdio::null()).stderr(Stdio::null()); };
let mut c = Command::new("update-desktop-database");
quiet(&mut c);
let _ = c.arg(data.join("applications")).status();
let mut c = Command::new("gtk-update-icon-cache");
quiet(&mut c);
let _ = c.args(["-t", "-f"]).arg(data.join("icons/hicolor")).status();
}
pub fn install(info: &AppInfo) -> Result<Installed, Error> {
check_id(info.id)?;
if info.name.is_empty() { return Err("app name is empty".into()); }
#[cfg(target_os = "linux")]
{ install_linux(info) }
#[cfg(target_os = "macos")]
{ install_macos(info) }
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{ let _ = info; Err("install is implemented for Linux and macOS only".into()) }
}
pub fn uninstall(id: &str, name: &str) -> Result<Installed, Error> {
check_id(id)?;
#[cfg(target_os = "linux")]
{ let _ = name; uninstall_linux(id) }
#[cfg(target_os = "macos")]
{ let _ = id; uninstall_macos(name) }
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{ let _ = (id, name); Err("uninstall is implemented for Linux and macOS only".into()) }
}
pub fn is_installed(id: &str, name: &str) -> bool {
#[cfg(target_os = "linux")]
{ let _ = name; data_dir().map(|d| d.join("applications").join(format!("{id}.desktop")).exists()).unwrap_or(false) }
#[cfg(target_os = "macos")]
{ let _ = id; home().map(|h| h.join("Applications").join(format!("{name}.app")).exists()).unwrap_or(false) }
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{ let _ = (id, name); false }
}
#[cfg(target_os = "linux")]
fn data_dir() -> Result<PathBuf, Error> {
if let Some(d) = std::env::var_os("XDG_DATA_HOME") {
let p = PathBuf::from(d);
if p.is_absolute() { return Ok(p); }
}
Ok(home()?.join(".local/share"))
}
#[cfg(target_os = "linux")]
fn exec_quote(p: &Path) -> String {
let s = p.to_string_lossy();
let safe = !s.is_empty() && s.bytes().all(|c| c.is_ascii_alphanumeric() || b"/._-+".contains(&c));
if safe { return s.into_owned(); }
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
if c == '"' || c == '\\' || c == '`' || c == '$' { out.push('\\'); }
out.push(c);
}
out.push('"');
out
}
#[cfg(target_os = "linux")]
fn one_line(s: &str) -> String { s.replace(['\n', '\r'], " ") }
#[cfg(target_os = "linux")]
fn install_linux(info: &AppInfo) -> Result<Installed, Error> {
let data = data_dir()?;
let exe = exec_path(info)?;
let mut out = Installed::default();
for img in info.icons {
let path = data.join(format!("icons/hicolor/{0}x{0}/apps/{1}.png", img.side, info.id));
write(&path, &icon::encode_png(&img.as_image()), &mut out)?;
}
let mut d = String::new();
d.push_str("[Desktop Entry]\n");
d.push_str("Type=Application\n");
d.push_str("Version=1.5\n");
d.push_str(&format!("Name={}\n", one_line(info.name)));
if !info.comment.is_empty() { d.push_str(&format!("Comment={}\n", one_line(info.comment))); }
d.push_str(&format!("Exec={}\n", exec_quote(&exe)));
d.push_str(&format!("Icon={}\n", info.id));
d.push_str(&format!("StartupWMClass={}\n", info.id));
d.push_str("StartupNotify=true\n");
d.push_str(&format!("Terminal={}\n", info.terminal));
if !info.categories.is_empty() { d.push_str(&format!("Categories={}\n", one_line(info.categories))); }
let desktop = data.join("applications").join(format!("{}.desktop", info.id));
write(&desktop, d.as_bytes(), &mut out)?;
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&desktop, std::fs::Permissions::from_mode(0o755));
refresh_caches(&data);
Ok(out)
}
#[cfg(target_os = "linux")]
fn uninstall_linux(id: &str) -> Result<Installed, Error> {
let data = data_dir()?;
let mut out = Installed::default();
let desktop = data.join("applications").join(format!("{id}.desktop"));
if std::fs::remove_file(&desktop).is_ok() { out.files.push(desktop); }
let hicolor = data.join("icons/hicolor");
if let Ok(entries) = std::fs::read_dir(&hicolor) {
for e in entries.flatten() {
let p = e.path().join("apps").join(format!("{id}.png"));
if std::fs::remove_file(&p).is_ok() { out.files.push(p); }
}
}
refresh_caches(&data);
Ok(out)
}
#[cfg(target_os = "macos")]
fn plist_escape(s: &str) -> String {
s.replace('&', "&").replace('<', "<").replace('>', ">")
}
#[cfg(target_os = "macos")]
fn install_macos(info: &AppInfo) -> Result<Installed, Error> {
let exe = exec_path(info)?;
let root = home()?.join("Applications").join(format!("{}.app", info.name));
let contents = root.join("Contents");
let mut out = Installed::default();
let icns = icon::encode_icns(info.icons);
let has_icon = !icns.is_empty();
if has_icon { write(&contents.join(format!("Resources/{}.icns", info.id)), &icns, &mut out)?; }
let bin_name = exe.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| info.id.to_string());
let mut pl = String::new();
pl.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
pl.push_str("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n");
pl.push_str("<plist version=\"1.0\">\n<dict>\n");
let mut kv = |k: &str, v: &str| { pl.push_str(&format!("\t<key>{k}</key>\n\t<string>{v}</string>\n")); };
kv("CFBundleName", &plist_escape(info.name));
kv("CFBundleDisplayName", &plist_escape(info.name));
kv("CFBundleIdentifier", &plist_escape(info.id));
kv("CFBundleExecutable", &plist_escape(&bin_name));
kv("CFBundlePackageType", "APPL");
kv("CFBundleInfoDictionaryVersion", "6.0");
kv("CFBundleShortVersionString", "1.0");
kv("CFBundleVersion", "1");
if has_icon { kv("CFBundleIconFile", &plist_escape(info.id)); }
pl.push_str("\t<key>NSHighResolutionCapable</key>\n\t<true/>\n");
pl.push_str("</dict>\n</plist>\n");
write(&contents.join("Info.plist"), pl.as_bytes(), &mut out)?;
write(&contents.join("PkgInfo"), b"APPL????", &mut out)?;
let link = contents.join("MacOS").join(&bin_name);
std::fs::create_dir_all(link.parent().unwrap()).map_err(|e| format!("mkdir MacOS: {e}"))?;
let _ = std::fs::remove_file(&link);
std::os::unix::fs::symlink(&exe, &link).map_err(|e| format!("symlink {}: {e}", link.display()))?;
out.files.push(link);
let _ = std::fs::File::open(&root).and_then(|f| f.sync_all());
Ok(out)
}
#[cfg(target_os = "macos")]
fn uninstall_macos(name: &str) -> Result<Installed, Error> {
if name.is_empty() || name.contains('/') { return Err(format!("bad app name {name:?}")); }
let root = home()?.join("Applications").join(format!("{name}.app"));
let mut out = Installed::default();
if root.exists() {
std::fs::remove_dir_all(&root).map_err(|e| format!("remove {}: {e}", root.display()))?;
out.files.push(root);
}
Ok(out)
}