rosier 0.3.0

A fast picture and video viewer for large folders
//! Making rosier show up like any other app: in the app menu or Start menu,
//! with its icon and name.
//!
//! - Linux: a desktop entry and an SVG icon under `~/.local/share`
//!   (XDG_DATA_HOME), for this user only. If the binary moves, the entry is
//!   rewritten on the next start.
//! - Windows: a Start menu shortcut for this user. The icon itself is built
//!   into the exe (see build.rs).
//! - macOS: nothing at run time. An app is a `Rosier.app` bundle the user
//!   drops into Applications, and Finder and Launchpad pick it up from there
//!   (see `packaging/macos`).

use std::path::PathBuf;

/// Whether rosier can add itself to the app menu on this system.
pub fn supported() -> bool {
    cfg!(any(target_os = "linux", target_os = "freebsd", windows))
}

/// Adds rosier to the app menu (or Start menu) for this user.
pub fn install() -> anyhow::Result<Vec<PathBuf>> {
    imp::install()
}

/// Whether rosier was added before (so a moved binary can be fixed up).
pub fn installed() -> bool {
    imp::installed()
}

/// If rosier was added before and the program it points to is gone, points
/// the entry at this one. Cheap; run once at start.
pub fn refresh() {
    if installed() && imp::stale() {
        let _ = install();
    }
}

#[cfg(any(target_os = "linux", target_os = "freebsd"))]
mod imp {
    use std::path::{Path, PathBuf};

    fn data_dir() -> Option<PathBuf> {
        std::env::var_os("XDG_DATA_HOME")
            .map(PathBuf::from)
            .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
    }

    fn entry_path() -> Option<PathBuf> {
        data_dir().map(|d| d.join("applications/rosier.desktop"))
    }

    fn entry(exe: &Path) -> String {
        use crate::i18n::{LANGS, t_in};
        let mut e = String::from("[Desktop Entry]\nType=Application\nName=Rosier\n");
        // Untranslated keys first, then one line per language (ja, zh_CN, …).
        e += &format!("GenericName={}\n", t_in(0, "app.generic"));
        e += &format!("Comment={}\n", t_in(0, "app.description"));
        for (i, (code, _, _)) in LANGS.iter().enumerate().skip(1) {
            let loc = code.replace('-', "_");
            e += &format!("GenericName[{loc}]={}\n", t_in(i, "app.generic"));
            e += &format!("Comment[{loc}]={}\n", t_in(i, "app.description"));
        }
        e += &format!(
            "Exec=\"{}\" %F\nIcon=rosier\nTerminal=false\nCategories=Graphics;Viewer;Photography;\n\
             MimeType=inode/directory;image/jpeg;image/png;image/webp;image/gif;video/mp4;video/x-matroska;video/webm;\n\
             StartupWMClass=rosier\n",
            exe.display()
        );
        e
    }

    /// Icon sizes written into the hicolor theme. PNG only: some menus and
    /// panels never look at SVG icons.
    const PNG_SIZES: [u32; 8] = [16, 22, 24, 32, 48, 64, 128, 256];

    pub fn install() -> anyhow::Result<Vec<PathBuf>> {
        let data = data_dir().ok_or_else(|| anyhow::anyhow!("cannot find the user data directory"))?;
        let written = write_files(&data, &std::env::current_exe()?)?;
        // Desktops cache icons and menus; a newer directory time makes
        // them look again, and the tools refresh where they exist.
        let hicolor = data.join("icons/hicolor");
        let _ = std::fs::File::open(&hicolor).and_then(|d| d.set_modified(std::time::SystemTime::now()));
        let _ = std::process::Command::new("gtk-update-icon-cache").args(["-f", "-t"]).arg(&hicolor).output();
        let _ = std::process::Command::new("update-desktop-database").arg(data.join("applications")).output();
        let _ = std::process::Command::new("kbuildsycoca6").output();
        let _ = std::process::Command::new("xdg-desktop-menu").arg("forceupdate").output();
        Ok(written)
    }

    /// Writes the icons and the desktop entry for `exe` under `data`.
    fn write_files(data: &Path, exe: &Path) -> anyhow::Result<Vec<PathBuf>> {
        let hicolor = data.join("icons/hicolor");
        let app_dir = data.join("applications");
        std::fs::create_dir_all(&app_dir)?;
        let mut written = Vec::new();
        // Drop the SVG an older rosier wrote; the PNGs below replace it.
        let _ = std::fs::remove_file(hicolor.join("scalable/apps/rosier.svg"));
        let master = image::load_from_memory(include_bytes!("../assets/rosier-1024.png"))?;
        for side in PNG_SIZES {
            let dir = hicolor.join(format!("{side}x{side}/apps"));
            std::fs::create_dir_all(&dir)?;
            let png = dir.join("rosier.png");
            master.resize_exact(side, side, image::imageops::FilterType::Lanczos3).save(&png)?;
            written.push(png);
        }
        let desktop = app_dir.join("rosier.desktop");
        std::fs::write(&desktop, entry(exe))?;
        written.push(desktop);
        Ok(written)
    }

    pub fn installed() -> bool {
        entry_path().is_some_and(|p| p.exists())
    }

    /// True when the entry's program no longer exists (the binary moved or
    /// was replaced by another install). Another copy merely running, such
    /// as a second build, leaves the entry alone.
    pub fn stale() -> bool {
        entry_path().is_some_and(|p| stale_entry(&p))
    }

    fn stale_entry(path: &Path) -> bool {
        let Ok(text) = std::fs::read_to_string(path) else { return false };
        exec_path(&text).is_some_and(|exe| !exe.exists())
    }

    /// The program path in an entry's `Exec="<path>" %F` line.
    fn exec_path(entry: &str) -> Option<PathBuf> {
        let line = entry.lines().find_map(|l| l.strip_prefix("Exec="))?;
        let quoted = line.strip_prefix('"')?;
        Some(PathBuf::from(&quoted[..quoted.find('"')?]))
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn entry_quotes_the_exe_and_names_the_app() {
            let e = entry(Path::new("/opt/my apps/rosier"));
            assert!(e.contains("Exec=\"/opt/my apps/rosier\" %F"));
            assert!(e.contains("Name=Rosier\n"));
            assert!(e.contains("StartupWMClass=rosier\n"));
            assert!(e.contains("Comment[ja]="), "the description is translated");
            assert_eq!(exec_path(&e), Some(PathBuf::from("/opt/my apps/rosier")));
            assert_eq!(exec_path("Name=x\n"), None);
        }

        #[test]
        fn writes_icons_and_an_entry_that_goes_stale_when_the_program_moves() {
            let data = std::env::temp_dir().join(format!("rosier-desktop-{}", std::process::id()));
            let _ = std::fs::remove_dir_all(&data);
            let exe = data.join("bin/rosier");
            std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
            std::fs::write(&exe, b"").unwrap();
            let written = write_files(&data, &exe).unwrap();
            assert_eq!(written.len(), PNG_SIZES.len() + 1);
            let icon = image::open(data.join("icons/hicolor/48x48/apps/rosier.png")).unwrap();
            assert_eq!((icon.width(), icon.height()), (48, 48));
            let desktop = data.join("applications/rosier.desktop");
            assert!(!stale_entry(&desktop));
            std::fs::remove_file(&exe).unwrap();
            assert!(stale_entry(&desktop));
            assert!(!stale_entry(&data.join("missing.desktop")));
            let _ = std::fs::remove_dir_all(&data);
        }
    }
}

#[cfg(windows)]
mod imp {
    use std::path::PathBuf;

    fn shortcut_path() -> Option<PathBuf> {
        std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join(r"Microsoft\Windows\Start Menu\Programs\Rosier.lnk"))
    }

    /// Single quotes for a PowerShell string literal.
    fn ps_quote(s: &str) -> String {
        format!("'{}'", s.replace('\'', "''"))
    }

    pub fn install() -> anyhow::Result<Vec<PathBuf>> {
        let lnk = shortcut_path().ok_or_else(|| anyhow::anyhow!("cannot find the Start menu folder"))?;
        let exe = std::env::current_exe()?;
        let dir = exe.parent().map(|p| p.display().to_string()).unwrap_or_default();
        // WScript.Shell makes .lnk files without any extra dependency. The
        // icon comes from the exe's own resources.
        let script = format!(
            "$s = (New-Object -ComObject WScript.Shell).CreateShortcut({lnk}); $s.TargetPath = {exe}; \
             $s.WorkingDirectory = {dir}; $s.IconLocation = {icon}; $s.Description = {desc}; $s.Save()",
            lnk = ps_quote(&lnk.display().to_string()),
            exe = ps_quote(&exe.display().to_string()),
            dir = ps_quote(&dir),
            icon = ps_quote(&format!("{},0", exe.display())),
            desc = ps_quote(crate::i18n::t("app.description")),
        );
        let out = std::process::Command::new("powershell")
            .args(["-NoProfile", "-NonInteractive", "-Command", &script])
            .output()?;
        anyhow::ensure!(out.status.success(), "powershell: {}", String::from_utf8_lossy(&out.stderr));
        Ok(vec![lnk])
    }

    pub fn installed() -> bool {
        shortcut_path().is_some_and(|p| p.exists())
    }

    pub fn stale() -> bool {
        // Reading a .lnk target would need COM, so a moved exe is fixed only
        // by running `rosier install-desktop` again.
        false
    }
}

#[cfg(not(any(target_os = "linux", target_os = "freebsd", windows)))]
mod imp {
    use std::path::PathBuf;

    pub fn install() -> anyhow::Result<Vec<PathBuf>> {
        anyhow::bail!("on macOS, put Rosier.app in the Applications folder instead")
    }

    pub fn installed() -> bool {
        false
    }

    pub fn stale() -> bool {
        false
    }
}