rosier 0.5.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, or an older
//!   rosier wrote a different entry, the entry is rewritten on the next start.
//!   Folders are not among its types: claiming inode/directory made rosier the
//!   default for opening every folder.
//! - 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)) && !packaged()
}

/// Installed by a package (.deb, .rpm) into /usr, which brings its own menu
/// entry: one for this user would show Rosier twice.
fn packaged() -> bool {
    cfg!(target_os = "linux")
        && std::env::current_exe().is_ok_and(|e| e.starts_with("/usr/"))
        && std::path::Path::new("/usr/share/applications/rosier.desktop").exists()
}

/// The program the menu entry starts: the AppImage file itself when run
/// from one (the running binary sits in a mount that goes away), otherwise
/// this binary.
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
fn program() -> std::io::Result<PathBuf> {
    match std::env::var_os("APPIMAGE") {
        Some(p) if !p.is_empty() => Ok(PathBuf::from(p)),
        _ => std::env::current_exe(),
    }
}

/// 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, brings its entry up to date: points it at
/// this program when the one it names is gone, and rewrites what an older
/// rosier wrote. Cheap; run once at start.
pub fn refresh() {
    if installed() {
        imp::refresh();
    }
}

#[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=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, &super::program()?)?;
        refresh_caches(&data);
        Ok(written)
    }

    /// Rewrites the entry when it differs from what this rosier writes
    /// (see `rewrite_target`), then refreshes the menu caches, which also
    /// rebuilds mimeinfo.cache from it. The user's mimeapps.list is never
    /// touched: a default they chose themselves stays.
    pub fn refresh() {
        let (Some(data), Ok(current)) = (data_dir(), super::program()) else { return };
        let Some(exe) = rewrite_target(&data.join("applications/rosier.desktop"), &current) else { return };
        if write_entry(&data, &exe).is_ok() {
            refresh_caches(&data);
        }
    }

    /// Desktops cache icons and menus; a newer directory time makes them
    /// look again, and the tools refresh where they exist.
    fn refresh_caches(data: &Path) {
        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();
    }

    /// 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);
        }
        written.push(write_entry(data, exe)?);
        Ok(written)
    }

    /// Writes the desktop entry for `exe` under `data`.
    fn write_entry(data: &Path, exe: &Path) -> anyhow::Result<PathBuf> {
        let app_dir = data.join("applications");
        std::fs::create_dir_all(&app_dir)?;
        let desktop = app_dir.join("rosier.desktop");
        std::fs::write(&desktop, entry(exe))?;
        Ok(desktop)
    }

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

    /// The program the entry at `path` should be written for, if it needs
    /// rewriting: the one it names while that still exists (another copy
    /// merely running, such as a second build, does not take it over),
    /// otherwise `current`. None when the entry already reads exactly as
    /// this rosier writes it, or there is none.
    fn rewrite_target(path: &Path, current: &Path) -> Option<PathBuf> {
        let text = std::fs::read_to_string(path).ok()?;
        let exe = exec_path(&text).filter(|p| p.exists()).unwrap_or_else(|| current.to_path_buf());
        (text != entry(&exe)).then_some(exe)
    }

    /// 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);
        }

        /// The entry used to claim inode/directory, which made rosier the
        /// default for opening any folder (xdg-open, browsers, "show in
        /// folder") wherever mimeapps.list names no default.
        #[test]
        fn entry_does_not_claim_folders() {
            let e = entry(Path::new("/usr/bin/rosier"));
            let mime = e.lines().find_map(|l| l.strip_prefix("MimeType=")).unwrap();
            assert!(!mime.split(';').any(|m| m == "inode/directory"), "{mime}");
            assert!(mime.contains("image/jpeg;") && mime.contains("video/mp4;"), "{mime}");
        }

        #[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");
            // Up to date: nothing to rewrite.
            assert_eq!(rewrite_target(&desktop, &exe), None);
            // The program is gone: the entry is rewritten for the one running.
            std::fs::remove_file(&exe).unwrap();
            let current = data.join("bin/rosier-new");
            assert_eq!(rewrite_target(&desktop, &current), Some(current));
            assert_eq!(rewrite_target(&data.join("missing.desktop"), &exe), None);
            let _ = std::fs::remove_dir_all(&data);
        }

        /// An entry an older rosier wrote (here, still claiming folders) is
        /// brought up to date on the next start, pointing at the program it
        /// already names; one for a program that is gone points at this one.
        #[test]
        fn an_entry_written_by_an_older_rosier_is_rewritten() {
            let data = std::env::temp_dir().join(format!("rosier-desktop-old-{}", std::process::id()));
            let _ = std::fs::remove_dir_all(&data);
            let (exe, running) = (data.join("bin/rosier"), data.join("dev/rosier"));
            for p in [&exe, &running] {
                std::fs::create_dir_all(p.parent().unwrap()).unwrap();
                std::fs::write(p, b"").unwrap();
            }
            write_files(&data, &exe).unwrap();
            let desktop = data.join("applications/rosier.desktop");
            assert_eq!(rewrite_target(&desktop, &running), None, "up to date: left alone");
            let old = entry(&exe).replace("MimeType=", "MimeType=inode/directory;");
            std::fs::write(&desktop, &old).unwrap();
            let target = rewrite_target(&desktop, &running);
            assert_eq!(target.as_deref(), Some(exe.as_path()), "rewritten for the program it names");
            write_entry(&data, &exe).unwrap();
            let now = std::fs::read_to_string(&desktop).unwrap();
            assert!(!now.contains("inode/directory"), "{now}");
            assert_eq!(rewrite_target(&desktop, &running), None);
            std::fs::remove_file(&exe).unwrap();
            assert_eq!(rewrite_target(&desktop, &running).as_deref(), Some(running.as_path()));
            assert_eq!(rewrite_target(&data.join("missing.desktop"), &running), None);
            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 refresh() {
        // Reading a .lnk target would need COM, so a moved exe is fixed only
        // by running `rosier install-desktop` again.
    }
}

#[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 refresh() {}
}